Logging & Observability interview question · Most asked
What is a correlation (request) ID and how do you propagate it?
Summary
A correlation ID is a unique identifier assigned to a request at the edge and attached to every log line, outbound call and message it causes, so you can reconstruct everything that happened for one request across services.
Longer Answer
Generate it at the first entry point (or accept an incoming X-Request-ID / W3C traceparent from a trusted proxy), store it in request-scoped context (AsyncLocalStorage in Node, contextvars in Python, MDC in Java, a request attribute in PHP), add it to every log line automatically, forward it in headers to downstream HTTP calls, and include it in queue message metadata. Return it in the response so users and support can quote it. With OpenTelemetry, the trace ID serves this purpose.
Code Example
# Python (FastAPI middleware + contextvars)
import uuid, contextvars, logging
request_id = contextvars.ContextVar("request_id", default="-")
class RequestIdFilter(logging.Filter):
def filter(self, record):
record.request_id = request_id.get()
return True
@app.middleware("http")
async def assign_request_id(request, call_next):
rid = request.headers.get("x-request-id") or str(uuid.uuid4())
token = request_id.set(rid)
try:
response = await call_next(request)
finally:
request_id.reset(token)
response.headers["x-request-id"] = rid
return response
Key Points
- Assigned at the edge
- Stored in request-scoped context
- Auto-added to logs
- Forwarded in headers and message metadata
- Returned to clients for support
More most-asked Logging & Observability questions
- What are the three pillars of observability, and how do they differ?
- What is structured logging and why is it preferred over plain text logs?
- What is distributed tracing and how does OpenTelemetry fit in?
- What are the RED, USE and Four Golden Signals methods?
- What are SLIs, SLOs and error budgets?
- What should never be logged, and how do you prevent it?
- Walk through how you would investigate a sudden latency spike in production.