Full answer
python
import asyncio, contextvars
request_id = contextvars.ContextVar("request_id", default="-")
def log(msg):
print(f"[{request_id.get()}] {msg}")
async def db_query():
await asyncio.sleep(0.01)
log("query done")
async def handle(rid, delay):
request_id.set(rid)
await asyncio.sleep(delay)
await db_query()
async def main():
await asyncio.gather(handle("req-1", 0.02), handle("req-2", 0.0))
log("outside requests")
asyncio.run(main())Output:
text
[req-2] query done
[req-1] query done
[-] outside requestsThe two handlers interleave: req-2 finishes first because it does not wait at the start. Each log line still shows the right id, because each task created by gather runs in its own copy of the context, and db_query reads the value without it being passed as an argument. After both tasks, the main context still has the default '-'. A module-level global would show whichever request set it last. token = var.set(x) and var.reset(token) restore previous values in synchronous code.
python
import asyncio, contextvars
request_id = contextvars.ContextVar("request_id", default="-")
def log(msg):
print(f"[{request_id.get()}] {msg}")
async def db_query():
await asyncio.sleep(0.01)
log("query done")
async def handle(rid, delay):
request_id.set(rid)
await asyncio.sleep(delay)
await db_query()
async def main():
await asyncio.gather(handle("req-1", 0.02), handle("req-2", 0.0))
log("outside requests")
asyncio.run(main())Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- ContextVar values are per context
- Tasks copy the context at creation
- No leakage between concurrent requests
- Use for request ids and tenants
- reset with tokens restores values
Common mistakes
- Using globals for request data in async servers
- Thread-locals in asyncio code
Follow-ups
- How does contextvars interact with thread pools?
- How would you add the id to all log records?
Tips
- Show interleaving with correct ids