Recipe 4.3 · Python
Correlation IDs Across Requests and Services
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Under load, log lines from many requests interleave. A failure in the payment service shows up seconds after the web front end logged "checkout started," and nothing ties the two together. You end up matching timestamps by hand across two servers whose clocks disagree.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Generating a request ID per call and passing it by hand
Source: ImproveCode, Chapter 4, Recipe 4.3 "Correlation IDs Across Requests and Services"
Section: The way it's often written
Book page: 86 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
uuid.uuid4() replaces Guid.NewGuid(); the fragment is wrapped in a function.
"""
from __future__ import annotations
import uuid
from typing import Any
def checkout(logger: Any, payment_client: Any, order: Any) -> None:
# Not this: an ID generated per call and passed by hand.
request_id = str(uuid.uuid4())
logger.write(request_id + " Checkout started")
payment_client.charge(order, request_id) # every signature grows
The improved recipe
Accept or create one correlation ID per incoming request, push it into the logging scope, echo it in the response, and forward it on outgoing HTTP calls.
Registration, as a usage snippet in Program.cs:
Requirements: Python 3.12+. Install: pip install fastapi httpx opentelemetry-api starlette
"""Correlation ID middleware and outgoing HTTP header propagation
Source: ImproveCode, Chapter 4, Recipe 4.3 "Correlation IDs Across Requests and Services"
Section: The improved recipe
Book page: 86-87 -- original C# listing
Converted from C# to Python.
A Starlette/FastAPI middleware replaces the ASP.NET Core middleware; a ContextVar
replaces HttpContext.TraceIdentifier/IHttpContextAccessor and the logger scope (a
logging.Filter copies it onto records); an httpx request event hook replaces the
DelegatingHandler; OpenTelemetry's current span (if installed) stands in for Activity.Current.
"""
from __future__ import annotations
import logging
import uuid
from contextvars import ContextVar
import httpx
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
HEADER_NAME = "X-Correlation-ID"
correlation_id: ContextVar[str | None] = ContextVar("correlation_id", default=None)
class CorrelationIdLogFilter(logging.Filter):
"""Adds CorrelationId to every record logged inside the request (BeginScope)."""
def filter(self, record: logging.LogRecord) -> bool:
record.CorrelationId = correlation_id.get()
return True
class CorrelationIdMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
cid = _read_or_create(request)
token = correlation_id.set(cid)
try:
response = await call_next(request)
response.headers[HEADER_NAME] = cid
return response
finally:
correlation_id.reset(token)
def _current_trace_id() -> str | None:
try:
from opentelemetry import trace # optional, like Activity.Current
except ImportError:
return None
ctx = trace.get_current_span().get_span_context()
return format(ctx.trace_id, "032x") if ctx.is_valid else None
def _read_or_create(request: Request) -> str:
incoming = request.headers.get(HEADER_NAME)
if _is_safe(incoming):
assert incoming is not None
return incoming
return _current_trace_id() or uuid.uuid4().hex
# Callers control the header, so accept only short, plain IDs.
def _is_safe(value: str | None) -> bool:
return (
bool(value)
and len(value) <= 64 # type: ignore[arg-type]
and all((c.isascii() and c.isalnum()) or c in "-_" for c in value) # type: ignore[union-attr]
)
async def add_correlation_header(request: httpx.Request) -> None:
"""httpx event hook equivalent of CorrelationIdHandler."""
cid = correlation_id.get()
if cid is not None and HEADER_NAME not in request.headers:
request.headers[HEADER_NAME] = cid
def use_correlation_id(app: FastAPI) -> FastAPI:
app.add_middleware(CorrelationIdMiddleware)
return app
Requirements: Python 3.12+. Install: pip install fastapi httpx
"""Wiring the correlation ID middleware and HTTP client hook
Source: ImproveCode, Chapter 4, Recipe 4.3 "Correlation IDs Across Requests and Services"
Section: The improved recipe
Book page: 87 -- original C# listing
Converted from C# to Python.
An httpx.AsyncClient with an event hook replaces AddHttpClient<PaymentClient>()
.AddHttpMessageHandler<CorrelationIdHandler>(); FastAPI middleware order replaces
the ASP.NET Core pipeline order. Pieces come from p086_r4_3_correlation_id_middleware_propagation.py.
"""
from __future__ import annotations
from typing import Any, Awaitable, Callable
import httpx
from fastapi import FastAPI
def configure(
app: FastAPI,
use_correlation_id: Callable[[FastAPI], FastAPI],
add_correlation_header: Callable[[httpx.Request], Awaitable[None]],
use_request_logging: Callable[[FastAPI], Any],
) -> httpx.AsyncClient:
# Typed client for PaymentClient, with the correlation hook attached.
payment_http = httpx.AsyncClient(
event_hooks={"request": [add_correlation_header]})
# Starlette runs the most recently added middleware first, so add request
# logging before the correlation middleware to get correlation outermost.
use_request_logging(app)
use_correlation_id(app) # before request logging (runs first)
return payment_http
How it works
BeginScope with a dictionary attaches CorrelationId to every log event written anywhere in
that request, by any class, without changing a single method signature. Serilog's
Enrich.FromLogContext() (from Recipe 4.2) turns scope values into properties. The built-in
console provider shows them too when IncludeScopes is on.
If the caller sent an ID, the middleware reuses it, so one ID follows a transaction from the
browser through the API to the downstream service. If not, it uses the W3C trace ID from
Activity.Current, which ASP.NET Core creates for every request and which distributed tracing
tools already understand. A GUID is the last fallback.
The header is client input, so it gets validated. An attacker who can put 10 KB of text or a line break into your logs can forge log entries or blow up your log bill. Short, ASCII, letters, digits, dashes and underscores is enough for any real ID.
OnStarting sets the response header just before headers are sent, which works even when a later
middleware short-circuits the request. Support staff can ask a user for the ID shown on an error
page and find the whole request in seconds.
The DelegatingHandler forwards the ID on every call made through IHttpClientFactory, so the
receiving service logs under the same ID.
Variations and pitfalls
- Register the middleware early, before request logging and exception handling, so those log events carry the ID too.
- Show the ID on your error page and in ProblemDetails responses (Chapter 5). "Send me the reference number" beats "what time did it happen?"
- For background jobs there is no request. Open a scope per job run with a
RunId(Recipe 4.6). - For message queues, put the ID in a message header when publishing and open a scope with it in the consumer.
- If you adopt OpenTelemetry tracing end to end, the W3C
traceparentheader does this job for you. The middleware still helps for callers that are not instrumented.