Python
08 Sep 2026
6 min read
Keep Request State Local with Python contextvars
Passing a request ID through every function is explicit, but after a few layers it can become noise. Logging is the example I keep running into: the logger needs the request ID, while most business functions do not actually care about it. A global variable looks tempting until two requests run concurrently. threading.local() fixes a different problem, but one event-loop thread can execute many asyncio tasks. Python’s contextvars module is designed for this kind of context-local state.