← Building blocks

Tag every log line with the request

Observability & operationsfundamental

Logs from ten services describe one failed request but nothing ties them together.

Say it like this

One failed notification touches the API, a queue, a router, a sender and a webhook, so I mint a correlation id at the edge and carry it through every header, message envelope and log line until one search returns the whole story.

Basic solution

Generate a correlation id at the edge, pass it in a header and through queue messages, and include it in every log line and span so one search shows the whole story.

X-Request-IDW3C traceparentOpenTelemetry context propagationMDC / structured log fields

One id through HTTP, queue, retry and webhook

The API mints the id and returns it to the caller; it travels in HTTP headers, then in queue message headers, is persisted with the delivery row so the retry and the webhook handler log under the same id.

How it works

  1. The edge (the gateway or the first service) checks the incoming request for an X-Request-ID or traceparent header. If there is none, it generates an id: a random 128-bit value or a ULID, never a counter, so ids cannot be guessed or used to infer traffic.
  2. The id is stored in the request context, the per-request state the framework carries through the handler, and the logging library reads it from there so every log line written during the request includes it automatically.
  3. Every outbound call copies the id into its headers. HTTP clients and gRPC interceptors add it to each request, and database drivers that support query comments can carry it there too, so the id appears in slow-query logs.
  4. When work goes asynchronous, the producer writes the id into the message envelope as a header or a field. The consumer's middleware reads it before handling the message and restores it into its own request context, so the consumer's log lines carry the same id as the producer's.
  5. The id is returned to the caller in the response headers and shown on error screens, so a user reporting a failure can quote an id that support matches directly against the server-side logs.
  6. Flows that outlast one request, such as a saga or a notification scheduled days ahead, carry a second id: the business id (notification id, order id). Both are logged, because one order generates hundreds of requests and each request needs its own id.

Correlation id versus trace id

  • They can be the same value. The trace id is what the tracing system samples and stores, so it may be missing for unsampled requests. The correlation id is what you search logs for and show to users, so it must exist on 100% of requests, sampled or not.

Worked example

Notification system, one missing OTP

  • The caller submits with idempotency key order-shipped:order123; the API generates request id 01J9X...4F and returns it in X-Request-ID along with the notification id n_88a1.
  • The API publishes to the intake queue with headers: request_id = 01J9X...4F, notification_id = n_88a1. The router consumes, restores both into its log context, applies rules, and publishes to the sms-transactional queue with the same headers.
  • The sender consumes, calls the provider with the request id in a custom header (providers that echo it make their support tickets fast), logs the 429, schedules a retry with the headers intact, and the retry succeeds 30 seconds later.
  • The webhook arrives 2 minutes later with the provider message id; the handler looks up the delivery row, which stores request_id, and logs the receipt under the same id.
  • Support query: request_id = 01J9X...4F returns 11 lines across 5 services in order: submitted 12:01:02.110, routed .140, provider 429 at .620, retry scheduled, retry sent 12:01:32, delivered webhook 12:03:15. The whole investigation takes one search and 30 seconds.
  • Volume cost: 36 bytes per line for the id across 17K lines/s ≈ 600 KB/s, about 8% of log volume. Worth it.

Variants and when each wins

Random request id per request

  • A fresh random id is minted at the edge with no structure inside it. It wins by being the simplest and is the default.

Trace id reused as the correlation id

  • One id serves both tracing and logs. It wins because the two stores join on one field; make sure the id is generated even when the trace was not sampled.

Business id as the correlation key

  • The order id, notification id or trip id is used as the key. It wins for following one business object across days; it must be paired with a per-request id, because one order generates hundreds of requests.

Hierarchical ids (parent.child)

  • The id grows at each hop to encode the call path. It wins when you want causality without a tracing system; headers get long and the value becomes awkward to index.

Recommendation: a random or trace-derived request id on every request plus the business id where one exists, both as structured log fields.

Failure modes

Dropped at the async boundary

  • Logs stop at the API, and the sender's lines carry a different id or none at all. It happens because the id lived in a thread-local variable that did not travel with the queue message. Put the id in the message envelope, restore it in the consumer middleware, and add a consumer-side test that asserts it is present.

Trusting an inbound id blindly

  • A caller sends a 10 KB X-Request-ID, or reuses one id for every request, and lookups break. It happens because the edge accepts whatever value arrives. Validate the format and length, generate a fresh id when the incoming one is invalid, and keep the caller's value as a separate field.

Scheduled and retried work loses context

  • A retry 30 seconds later logs under a new id, so the retry cannot be connected to the original attempt. It happens because the retry path rebuilds the job from the database row, which did not store the id. Persist the request id with the job or delivery row and reload it on retry.

Id not returned to the client

  • A user reports an error and support cannot find it in the logs. It happens because the id was internal only. Return it in a response header, display it on error pages, and ask for it in the support form.

Sequential ids leak information

  • A caller can guess other requests' ids or work out your traffic volume from the numbers. It happens because a counter was used as the id. Use random 128-bit or ULID values.

Interviewer follow-ups

Answer out loud before you open each one.

How is a correlation id different from a trace id, and do you need both?

A trace id is for the tracing system and is often only sampled; a correlation id is for logs and support and must exist on every request. They can be the same value as long as it is generated on every request even when the trace is not sampled, which is the setup to prefer.

How does the id survive a queue hop?

The producer writes it into the message headers alongside the business id; the consumer middleware reads the headers before handling the message and sets them in its log context. Delayed and dead-letter requeues must copy headers forward too.

Where should the id be generated?

At the first component you control, usually the gateway or load balancer, so the id covers the whole server-side path. Accept a client-supplied id as an extra field for mobile apps that want to correlate with their own logs, but never as the primary id.

What would you log with the id to make a support case solvable?

Request start and end with outcome and duration, each outbound call with its target and result, each queue publish and consume, and every decision point such as which rule deferred a notification. With those, the sequence of one request reads like a narrative.

Connections

In study paths
Knowing what broke
Pairs with
Log so you can query · Follow one request across services · Decouple producer from consumer · Make retries safe · Park poison messages
Used in
Notification System

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingNotification API, SMS sender, Webhook handlerCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon SQSIntake queuePub/Sub, Cloud TasksService Bus queues, Queue StorageRabbitMQ, ActiveMQ