← Back to Python, page 4

python-0069 · Hard senior

Use contextvars to carry request-scoped data, such as a request id, through async code.

A ContextVar holds a value per execution context. asyncio tasks copy the current context when created, so setting a request id in one task does not leak into concurrent tasks, unlike a global variable or thread-local in async code. Frameworks use this for request ids, tenants and database sessions.

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 requests

The 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