DEV.co
Open-Source Observability · snok

asgi-correlation-id

asgi-correlation-id is a Python middleware that automatically tracks HTTP requests across your application logs by assigning each request a unique ID. It reads or generates correlation IDs from request headers and injects them into log output, making it simple to trace all logs belonging to a single user request.

Source: GitHub — github.com/snok/asgi-correlation-id
637
GitHub stars
36
Forks
Python
Primary language
MIT
License (OSI-approved)

Key facts

Objective fields from the source. Values we can't verify are shown as “Unknown” rather than guessed.

FieldValue
Repositorysnok/asgi-correlation-id
Ownersnok
Primary languagePython
LicenseMIT — OSI-approved
Stars637
Forks36
Open issues2
Latest releasev5.0.1 (2026-06-09)
Last updated2026-06-09
Sourcehttps://github.com/snok/asgi-correlation-id

What asgi-correlation-id is

ASGI middleware that implements request ID propagation by reading X-Request-ID (or custom header) from incoming requests or generating UUIDs, storing them in context-local storage, and providing a log filter for injection into Python logging records. Supports header validation, custom generators, and transformers; integrates with Starlette/FastAPI frameworks.

Quickstart

Get the asgi-correlation-id source

Clone the repository and explore it locally.

terminalbash
git clone https://github.com/snok/asgi-correlation-id.gitcd asgi-correlation-id# follow the project's README for install & configuration

Need it deployed, integrated, or customized instead? DEV.co ships production installs.

Best use cases

Multi-service request tracing

Track a single user request across multiple microservices by passing correlation IDs in headers; aggregate logs from all services to troubleshoot end-to-end failures.

Production debugging and log analysis

Correlate logs from the same HTTP request across workers, async tasks, and background jobs to reconstruct the full execution path during incident investigation.

Sentry and APM integration

Link Sentry issues and APM traces to HTTP requests via correlation IDs, enabling faster root-cause analysis and reducing mean time to resolution.

Implementation considerations

  • Middleware ordering matters: place CorrelationIdMiddleware early in the stack so correlation IDs are available to downstream middleware and handlers.
  • Logging configuration must include the CorrelationIdFilter and %(correlation_id)s format string; without this, IDs are generated but not emitted to logs.
  • For CORS requests, explicitly allow the correlation ID header in allow_headers and expose_headers; browser security policies will block cross-origin access otherwise.
  • If using custom validators or generators, ensure they are thread-safe and performant; validator is called on every incoming request and generator on every cache miss.
  • Exception handlers must explicitly include the correlation ID in 5xx error responses if you need traceability for unhandled exceptions.

When to avoid it — and what to weigh

  • Non-ASGI frameworks — This middleware is ASGI-specific; if your application uses WSGI (Django, Flask in traditional mode) or other protocols, you will need alternative solutions or adapters.
  • Minimal logging footprint required — If you are constrained by log volume or storage, adding correlation IDs increases log size; evaluate cost-benefit trade-offs in high-volume environments.
  • Full distributed tracing needs — Correlation IDs alone do not capture timing, span hierarchies, or resource metrics; if you need comprehensive tracing, pair this with OpenTelemetry or similar instrumentation.
  • Strict context isolation required — If your application runs hundreds of concurrent requests in a single thread (rare) or requires guarantees that correlation IDs never leak between requests, test context-local storage behavior under your load profile.

License & commercial use

MIT License: permissive open-source license allowing commercial use, modification, and distribution with proper attribution and no warranty.

MIT is a permissive OSI-approved license that explicitly permits commercial use without royalties or restrictions. No license review required for standard commercial deployment. Review internal policies for any project-specific compliance requirements.

DEV.co evaluation signals

Editorial assessment — not user reviews. Directional, with an explicit confidence level.

SignalAssessment
MaintenanceActive
DocumentationStrong
License clarityClear
Deployment complexityLow
DEV.co fitStrong
Assessment confidenceHigh
Security considerations

Correlation IDs are non-sensitive identifiers (typically UUIDs) not suitable for authentication or authorization. Ensure X-Request-ID response header is not exposed to untrusted clients if internal tracing details must remain hidden; CORS expose_headers configuration controls this. Default UUIDs are cryptographically generated; custom generators should maintain similar entropy.

Alternatives to consider

OpenTelemetry SDK + auto-instrumentation

Provides distributed tracing with full span hierarchies, timing, and resource metrics across services; more heavyweight but gives richer observability than correlation IDs alone.

Structlog with contextvars

General-purpose structured logging library with built-in context support; requires manual correlation ID propagation but offers more flexible log formatting and filtering.

Starlette middleware + custom context manager

Manual implementation avoids a dependency; suitable if you need minimal features or want full control, but requires maintenance and testing.

Software development agency

Build on asgi-correlation-id with DEV.co software developers

Implement asgi-correlation-id to unify logs across your ASGI application. Devco experts can help integrate this middleware into your logging stack and connect it to your observability tools.

Talk to DEV.co

Related open-source tools

Surfaced by semantic similarity across the DEV.co open-source index.

asgi-correlation-id FAQ

Can I use this with Django?
Not directly—Django uses WSGI by default. If using Django with ASGI (Daphne or similar), this middleware will work. Otherwise, use alternatives like django-requestlogs or middleware stacks designed for WSGI.
What if a request doesn't include a correlation ID header?
The middleware automatically generates a new UUID (by default) and assigns it to the request. This ensures every request has a traceable ID even if no upstream service provided one.
How do I propagate correlation IDs to background jobs or external API calls?
Manually retrieve the correlation ID via correlation_id.get() from context, then pass it as a header to outbound HTTP calls or include it in job metadata for async tasks. The library does not automate this.
Does this add significant overhead?
Overhead is negligible: UUID generation and context-local storage access are O(1) operations. The main cost is log I/O, which occurs regardless of correlation IDs.

Custom software development services

DEV.co is a software development agency delivering custom software development services to companies building on open source. Our software developers and web developers design, integrate, and ship production systems — spanning web development, APIs, AI, data, and cloud. If asgi-correlation-id is part of your open-source observability roadmap, our team can implement, customize, migrate, and maintain it.

Ready to streamline your request tracing?

Implement asgi-correlation-id to unify logs across your ASGI application. Devco experts can help integrate this middleware into your logging stack and connect it to your observability tools.