Async Context Vars Correlation

Use contextvars for request-scoped correlation IDs in async code without parameter passing.

PythonCli Tooling

Code

pythonsnippet
14 lines
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: contextvars is 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

FAQ

Which packages must be installed first?
Yes. The imports resolve to `contextvars`, which the package manager must provide.