Request IDs and correlation
A single user request can generate fifty log lines across three services and one background worker. When something goes wrong, how do you find all fifty log lines for that one user? A correlation ID: a unique id attached to every log line for a single request, propagated across service boundaries. Ten seconds of code, hours of saved debugging.
import { Request, Response, NextFunction } from 'express';
import { randomUUID } from 'crypto';
import { logger } from '../logger';
export function requestId(req: Request, res: Response, next: NextFunction) {
const id = (req.headers['x-request-id'] as string) || randomUUID();
(req as any).requestId = id;
res.setHeader('X-Request-Id', id);
// A child logger with the id baked in
(req as any).log = logger.child({ requestId: id });
next();
}Generate a request ID on every inbound request. Pass it through to every log line.
Every handler downstream uses req.log instead of the global logger. Every log line that handler emits automatically carries the request id. When something fails, you grep your log system for that id and see every step of that one request in order.
When the request hits another service, pass the same id along in an X-Request-Id header. The inventory service accepts it if present, generates one if not. Now you can follow a request across multiple services by a single id. This is a poor-person's distributed tracing, and it covers 80 percent of the debugging scenarios you will ever need.
Quiz: Quiz
Loading practice…