Async Context Vars Correlation
Use contextvars for request-scoped correlation IDs in async code without parameter passing.
Code
import contextvars, uuid
correlation_id = contextvars.ContextVar('correlation_id', default=None)
def set_correlation(id=None):
correlation_id.set(id or str(uuid.uuid4()))
def get_correlation():
return correlation_id.get()
async def handle_request(request):
set_correlation(request.headers.get('X-ID'))
await process(request)
await log_response()What the code does
Async Context Vars Correlation is built around the functions set_correlation, get_correlation and handle_request.
Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed.
Watch out for
- Plan for an install step:
contextvarsis a real dependency, resolved by the package manager.
Applying it
Signature: def set_correlation(id=None)
The surface worth importing is set_correlation; the helpers around it are private to the snippet.
Statements that matter
def set_correlation(id=None):
correlation_id.set(id or str(uuid.uuid4()))
async def handle_request(request):
set_correlation(request.headers.get('X-ID'))
await process(request)
await log_response()
def get_correlation():
return correlation_id.get()
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `contextvars`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.