Correlation Middleware

The correlation middleware extracts, generates, and propagates correlation and trace IDs for each connection.

This facilitates distributed tracing and unified logging across microservices and async handlers.

Features

  • Priority header fallback (x-request-id, x-correlation-id, and traceparent by default).

  • W3C traceparent defensive parsing.

  • UUID4 generation fallback when no header matches.

  • The active ID is stored on the connection scope, making it available to handlers and other middlewares.

  • Optional response-header propagation.

Usage

from litestar import Litestar, Request, get
from litestar.middleware.correlation import CorrelationMiddleware, get_correlation_id


@get("/")
async def index_handler(request: Request) -> dict[str, str | None]:
    return {"correlation_id": get_correlation_id(request)}


app = Litestar(
    route_handlers=[index_handler],
    middleware=[CorrelationMiddleware()],
)

Accessing the correlation ID

The active correlation ID is stored on the connection scope and can be retrieved anywhere the scope is available - in handlers, dependencies, or other middlewares - using get_correlation_id():

from litestar import Request, get
from litestar.middleware.correlation import get_correlation_id


@get("/")
async def handler(request: Request) -> str | None:
    return get_correlation_id(request)

The helper also accepts a raw ASGI scope or a WebSocket directly:

from litestar import WebSocket, websocket


@websocket("/ws")
async def websocket_handler(socket: WebSocket) -> None:
    await socket.accept()
    await socket.send_text(get_correlation_id(socket) or "missing")

Header behavior

The middleware validates W3C traceparent values. Values from all other configured headers are treated as opaque correlation values. Additional formats, including grpc-trace-bin and provider-specific headers, can be selected without repeating the defaults:

CorrelationMiddleware(
    additional_header_names=("grpc-trace-bin", "x-cloud-trace-context"),
)

Use header_names instead to replace the complete lookup list and control its priority. The two options are mutually exclusive. The middleware does not parse additional or replacement header formats.

Incoming scope headers are not modified. By default, the selected correlation ID replaces x-request-id in the response; set response_header_name=None to disable this. This response header contains the selected correlation value, not a raw copy of the incoming header. The middleware does not propagate correlation headers to outbound requests.