Advertisement
Intermediate Node.js, Logging & Monitoring

How would you implement request correlation IDs to trace a single request's logs across multiple log lines and services?

Short answer

A correlation (or request/trace) ID is generated once when a request first enters the system (or extracted if it was already provided by an upstream caller), attached to the request context (commonly via AsyncLocalStorage, as discussed earlier), and included in every log line…

Save Node.js mock interview
Advertisement
AModel answer
A correlation (or request/trace) ID is generated once when a request first enters the system (or extracted if it was already provided by an upstream caller), attached to the request context (commonly via AsyncLocalStorage, as discussed earlier), and included in every log line emitted while handling that request -- as well as forwarded in outgoing headers to any downstream services called -- letting an engineer search logs across an entire distributed system for that single ID to reconstruct the complete story of one specific request.
app.use((req, res, next) => {
  req.correlationId = req.headers['x-correlation-id'] || crypto.randomUUID();
  res.setHeader('x-correlation-id', req.correlationId);
  next();
});

// Every log line during this request includes the same ID
logger.info({ correlationId: req.correlationId, event: 'processing_order' });

// Forwarded to downstream services
fetch(downstreamUrl, { headers: { 'x-correlation-id': req.correlationId } });
Real-world example
An engineer debugging a customer-reported error asks the customer for the correlation ID shown in their error message, then searches the centralized logging system for that exact ID, instantly retrieving every log line from every microservice involved in handling that specific failed request.
Likely follow-ups
  • How does a correlation ID differ from and relate to a full distributed trace ID from a system like OpenTelemetry?
  • What happens if a downstream service fails to forward the correlation ID header, breaking the trace continuity?
Related topics