
The problem: threading.local lies to you under asyncio
If you came to Python from threaded web servers (Flask + WSGI, Django + gunicorn threads), you probably reached for threading.local to keep a “current request id” or “current user” without threading it through every function call.
import threading
_request = threading.local()
def set_request(rid):
_request.id = rid
def get_request():
return getattr(_request, "id", None)
That works when every request runs in its own OS thread. But under asyncio (FastAPI, Sanic, Tornado, asyncio workers), many requests share a single thread on one event loop. threading.local sees only the thread — so concurrent requests overwrite each other’s data, and get_request() returns whoever wrote last. It is a silent, hard-to-reproduce bug.
The fix: contextvars
contextvars was added (3.7) precisely for this: a variable whose value is scoped to the current execution context, not the thread. In asyncio it flows correctly across await points and into every child task you spawn — and stays isolated between concurrent coroutines.
import contextvars
request_id = contextvars.ContextVar("request_id")
def set_request(rid):
# .set() returns a Token you can use to .reset() later
return request_id.set(rid)
def get_request():
# raises LookupError if unset — pass a default to avoid it
return request_id.get("unknown")
async def handle(rid):
token = set_request(rid)
try:
await do_work() # any awaited call sees THIS request_id
print("handled", get_request())
finally:
request_id.reset(token) # restore previous value, cleanly
Run two of these concurrently and each keeps its own id — no leakage.
What makes it actually useful: it propagates to child tasks
Set a value in the parent, asyncio.create_task() a child, and the child inherits the snapshot of the context at creation time:
async def worker():
print("child sees", request_id.get())
async def handle(rid):
request_id.set(rid)
# child is born with the current context -> sees `rid`
await asyncio.gather(worker(), worker())
This is why contextvars is the backbone of request tracing, structlog context, and async DB transaction/session scoping. The value travels with the coroutine, not with a thread or a global.
Three traps to avoid
get()raisesLookupErrorwhen unset. Always pass a default (request_id.get(None)) or wrap intry/exceptif the value is optional.- Changes in a child task do NOT leak back to the parent. Context is copy-on-write at task creation; a
set()inside a worker updates only that worker’s copy. Don’t use it to “return” a value — use aFutureorreturn. - A new process starts a fresh context.
ProcessPoolExecutorormultiprocessingdoes not carry your context over. Re-seed it in the worker, or pass the value explicitly.
Where to use it
Reach for contextvars when you need ambient state that must stay correct under concurrency: request/trace ids, authenticated user, DB session/transaction binding, i18n locale, feature-flag context. Prefer explicit function arguments when the value is only needed in two or three nearby places — context vars are for state that would otherwise thread through your entire call stack.