How to Implement Correlation IDs in Logs
Correlate logs across services: carry a request id in the log context, inject it on outbound calls, and query every line for one request.
On this page
Introduction
In a system of several services, one request produces log lines in each of them, and finding the lines for that request is the first step of every investigation. A correlation id makes it possible: a value minted once and carried in every log line of the request, so a query on the id returns the whole story. Without it, correlating lines means matching timestamps and guessing, which is slow and unreliable.
This tutorial covers minting the id at the edge, binding it to the log context, injecting it on outbound calls, and querying by it. The examples use a structured logger and a request context, and the approach applies to any service that logs.
Mint the id at the edge, or accept a valid one
The correlation id originates at the entry point, the gateway or the first service the request reaches. If the caller supplied one, reuse it; otherwise generate a new one. Validate a client-supplied id against a strict pattern and a length bound, so a value with newlines or thousands of characters cannot corrupt or flood the logs. Generate a fresh id when the supplied one fails validation.
Make the id easy to spot and to copy: an opaque token, often a UUID or a compact sortable id. The id is not secret; it appears in logs and often in an error response, so a user can quote it. The important properties are uniqueness and a bounded, safe format, not secrecy.
import { randomUUID } from 'node:crypto';
const ID_PATTERN = /^[A-Za-z0-9._-]{8,128}$/;
function correlationId(req) {
const incoming = req.headers['x-request-id'];
if (typeof incoming === 'string' && ID_PATTERN.test(incoming)) return incoming;
return randomUUID(); // valid or not, the id is bounded and safe
}
Bind the id to the request’s log context
Attach the id to a child logger created for the request, so every log line emitted during the request carries it without the code re-adding it. The child logger is passed into the handlers, and a log call adds only the event-specific fields. This is the binding that makes a request’s lines findable, because no line is emitted without the id.
If the language has an async context, such as AsyncLocalStorage, the id can be carried implicitly, so the code reads the current logger from the context rather than passing it. Either way, the id is set once at the boundary and never re-added below, so a missing id in a log line is impossible by construction rather than by discipline.
import { AsyncLocalStorage } from 'node:async_hooks';
import pino from 'pino';
const base = pino();
const als = new AsyncLocalStorage();
function middleware(req, res, next) {
const id = correlationId(req);
res.setHeader('x-request-id', id);
als.run({ id, log: base.child({ requestId: id }) }, () => next());
}
function log() { return als.getStore()?.log ?? base; } // never a line without the id
Inject the id on outbound calls
Forward the id on every downstream call, in the same header, so the downstream logs carry it and the request remains one chain. Do this in a shared HTTP client wrapper, so every call inherits the current id automatically and a new call site cannot forget it. For a message queue, put the id in the message properties so the consumer continues the chain.
If the tracing system is in use, the trace context can carry the id or coincide with it, so the logs and the traces join. Log the trace id as the correlation id, or set the correlation id from the trace id, so a query on the log id returns the spans of the same request. The two views aligning is what makes an investigation efficient.
async function callDownstream(url, init = {}) {
const id = als.getStore()?.id;
const headers = { ...(init.headers ?? {}), ...(id ? { 'x-request-id': id } : {}) };
return fetch(url, { ...init, headers }); // downstream logs carry the same id
}
Query by the id to retrieve the request
The payoff of the id is a query that returns every line of one request across the services, ordered by time, which is the timeline of what happened. Filter the logs by the id, and read the sequence to see the request’s progress and where it went wrong. This turns an investigation from a search across heterogeneous logs into one filter.
Include the id in an error response, so a user reporting a problem can quote it and support can retrieve the exact lines. The id is opaque, so quoting it leaks nothing about the internals. Surfaces that expect an error body should carry the id alongside the message, because the moment a request fails is when the id is most valuable.
# one request's whole story across services, ordered by time
jq -c 'select(.requestId == "4f9c1e2a-...")' app.log service-b.log | sort
# or in a log backend: requestId:"4f9c1e2a-..."
Test that the id survives every hop
Test that an incoming id is reused when valid and a fresh one is generated when invalid, by sending a malformed header and asserting the response carries a well-formed id. Test that every log line for a request carries the id, by capturing the logs and asserting none is missing it. Test that a downstream call carries the id, by a stub that records the incoming header. Test that the id appears in the error response.
curl -sD - -o /dev/null -H 'x-request-id: bad value with spaces' $BASE/x | grep -i x-request-id
# expect a fresh, well-formed id, not the malformed one
curl -sD - -o /dev/null -H 'x-request-id: 4f9c1e2a-0b3d-4f5a-8c2e-1d2b3c4d5e6f' $BASE/x | grep -i x-request-id
# expect the same id echoed, and the same id in the logs and the downstream stub
Common pitfalls
Generating a new id at every hop so the chain breaks, trusting an unbounded client value, re-adding the id at every log call instead of binding it once, not forwarding the id on outbound calls, and not including the id in error responses so support cannot retrieve the lines are the recurring mistakes. Minting at the edge with validation, binding to the context, forwarding in a shared client, and echoing in the error address them.
Conclusion
A correlation id makes a request’s logs findable across services. Mint it at the edge or accept a validated one, bind it to the request’s logger so every line carries it, forward it on every downstream call, and query by it to retrieve the whole story. Self-check by sending a malformed id and asserting a fresh one, and a valid one and asserting it survives the hops. Then an investigation is one filter, not a search.
Sources: W3C Trace Context, OpenTelemetry: Context propagation, MDN: HTTP headers.
FAQ
- How is a correlation id different from a trace id?
- They often coincide and can be the same value. A correlation id is the id you put in every log line to retrieve a request's logs; a trace id is the id the tracing system uses to join spans. You can log the trace id as the correlation id so both views align.
- Should I trust a client-supplied id?
- Only if it matches a strict format and a bounded length; otherwise an attacker can inject newlines or a huge value into the logs. Accept it when valid, generate a fresh one when not, and always cap the length.
Report a problem with this articleOpens a pre-filled issue on GitHub.