One Request, Many Rooms: A Correlation Contract for Code That Leaves Home
Photo: DFID - UK Department for International Development, CC BY 2.0, via Wikimedia Commons
On a Tuesday afternoon, a customer in Ohio presses Place order. The browser sends one POST request. Twelve seconds later, support has six log lines from six services, two queue consumers, a scheduled reconciliation job, and a payment provider. None of the records share an identifier. The incident review becomes archaeology.
Correlation is not the same as tracing. A trace is a graph of spans; correlation is the thread that lets an operator gather the evidence. You can build useful correlation without a vendor and without a new platform. It starts with a decision: identity is assigned once, at the edge, and carried as ordinary data.
The contract before the code
Write the contract first. A minimal correlation context has three fields: a correlation identifier, a causation identifier, and an origin label. The correlation identifier is opaque and high-entropy. The causation identifier names the immediate cause of the current unit of work. The origin label records where the context entered the system.
Five rules keep the contract honest. Generate a correlation identifier at ingress when one is absent or untrusted. Accept an inbound identifier only from a trusted upstream. Propagate the identifier on every outbound call. Bind it to the logging context for the lifetime of the unit. Never regenerate it inside an asynchronous continuation, a retry, or a queue consumer.
This contract can coexist with W3C Trace Context. The trace parent header carries sampling and span relationships; the correlation identifier carries the durable thread an operator can search. The correlation identifier is not a security token and should not be treated as one.
Where the thread breaks
Context is lost at boundaries, not in the middle of a function. In-process asynchronous work is the first boundary. A promise callback may run after the request object has gone out of scope; a global variable fails under concurrency. Node.js provides AsyncLocalStorage for this; Python provides contextvars; other runtimes have equivalents. Use them rather than threading a context object through every signature.
Thread pools are the second boundary. A task submitted to a worker pool does not automatically inherit the caller's local context. Wrap the submitted function so it captures and restores the context. The third boundary is the queue. The message envelope is the new transport, so the correlation fields must live in the payload or an explicit attribute map, not only in broker metadata that consumers may not read.
Scheduled jobs are the fourth boundary. A nightly invoice sweep has no inbound request to inherit from. Generate a fresh correlation identifier for the job run and record the schedule as the causation. The fifth boundary is the third-party call. Outbound HTTP headers are the only portable channel; when a provider strips unknown headers, log the outbound correlation identifier next to the provider request identifier in the response record.
A small implementation
The following TypeScript sketch uses Node's AsyncLocalStorage to bind the context to the asynchronous call chain.
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';
type CorrelationContext = {
correlationId: string;
causationId?: string;
origin: string;
};
const store = new AsyncLocalStorage<CorrelationContext>();
export function withCorrelation<T>(ctx: CorrelationContext, fn: () => T): T {
return store.run(ctx, fn);
}
export function correlation(): CorrelationContext {
const ctx = store.getStore();
if (!ctx) throw new Error('correlation context missing');
return ctx;
}
At the HTTP edge, assign or accept the identifier, then bind it for the request lifetime. The trust check is application-specific; the important part is that untrusted input never becomes the system's identity.
app.use((req, res, next) => {
const inbound = req.header('x-correlation-id');
const trusted = req.header('x-internal-hop') === 'edge';
const correlationId = trusted && inbound ? inbound : randomUUID();
const ctx = { correlationId, origin: `${req.method} ${req.path}` };
res.setHeader('x-correlation-id', correlationId);
withCorrelation(ctx, () => next());
});
When publishing to a queue, put the context into the message envelope. The consumer restores it before running business logic.
await queue.publish('orders.created', {
payload: order,
meta: {
correlationId: correlation().correlationId,
causationId: randomUUID()
}
});
queue.subscribe('orders.created', async (msg) => {
const ctx = {
correlationId: msg.meta.correlationId,
causationId: msg.meta.causationId,
origin: 'queue:orders.created'
};
await withCorrelation(ctx, async () => {
await handleOrderCreated(msg.payload);
});
});
Outbound calls use a wrapper that reads the current context and sets the header. This is also the right place to record the outbound attempt with its correlation identifier.
async function correlatedFetch(url: string, init: RequestInit = {}) {
const { correlationId } = correlation();
const headers = new Headers(init.headers);
headers.set('x-correlation-id', correlationId);
return fetch(url, { ...init, headers });
}
Scheduled jobs generate a new identifier and label the origin as the schedule. They do not inherit a stale request context from process startup.
Making the evidence line up
Structured logs are the payoff. Every log line emitted during a unit of work should include the correlation identifier, the causation identifier, and the origin. Error reports should attach the same fields to the exception payload. Metrics should not use the correlation identifier as a label; that is high cardinality. Use logs and exemplars to move from a metric spike to a specific request instead.
Retention needs a policy. Correlation identifiers are operational data, so set a time to live that matches the debugging window. If identifiers can come from users, validate length and character set, and record that the origin was external. Do not put personal data inside the identifier.
A contract test is cheap: publish a job with a known correlation identifier, run the consumer, and assert that every log line carries it. A lint rule that forbids direct console logging in request paths is cheaper still.
The trace you did not write is the trace you cannot follow. The contract is small: assign once, carry everywhere, bind to context, and record at every boundary. Then one request has one thread, even when it crosses many rooms.