Correlation IDs — Tracing Requests Across Microservices with Correlation IDs
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Correlation Ids. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Correlation IDs uniquely identify a request across all services it traverses, enabling end-to-end traceability.
// Correlation ID middleware
const { v4: uuidv4 } = require('uuid');
function correlationIdMiddleware(req, res, next) {
const correlationId = req.headers['x-correlation-id'] || uuidv4();
req.correlationId = correlationId;
res.setHeader('x-correlation-id', correlationId);
next();
}
// Propagation to downstream services
async function callDownstreamService(req, url, body) {
return axios.post(url, body, {
headers: {
'x-correlation-id': req.correlationId,
'x-span-id': uuidv4(),
'x-parent-span-id': req.spanId
}
});
}
// Structured log with correlation
logger.info({
message: 'Scan initiated',
correlationId: req.correlationId,
spanId: req.spanId,
scanId: scan.id,
duration: 0
});
// Async context for automatic correlation
const { AsyncLocalStorage } = require('async_hooks');
const asyncContext = new AsyncLocalStorage();
function contextMiddleware(req, res, next) {
asyncContext.run({
correlationId: req.correlationId,
userId: req.user?.id,
startTime: Date.now()
}, () => next());
}
function getContext() {
return asyncContext.getStore();
}
// Logger with automatic context injection
const contextualLogger = {
info: (msg, data) => {
const ctx = getContext();
logger.info({ ...ctx, message: msg, ...data });
}
};
Correlation IDs transform distributed request flows into coherent, traceable paths across service boundaries.
← Previous
Log Aggregation — Centralizing Logs with Aggregation Systems
Next →
Log Level Management — Dynamic Log Level Management in Production
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro