Python ContextVar: Request State, Task Inheritance and Token Reset
Keep Python async request state scoped correctly. Test ContextVar token reset, task-creation inheritance, cancellation cleanup and shared mutable values with a runnable lab.
Use a module-level ContextVar for context-local request metadata, and reset the token in finally at the owning scope. A new asyncio task normally copies the creation-time context; later parent bindings do not update it. Copied bindings can still refer to the same mutable object, so context isolation does not imply deep copying.
Why a request ID changes while a coroutine is waiting
An asynchronous service assigns a request ID, waits for a database result, and later logs a different ID. A module-level variable can produce that symptom when several requests interleave on one thread. The thread did not change, but the logical operation did. A single global slot cannot represent several independently active request scopes.
ContextVar provides context-local bindings for values such as correlation IDs. This guide focuses on the boundaries that commonly surprise developers: restoring the previous value, creating a child task, and putting a mutable object inside a copied context. It includes a complete executable fixture rather than relying on log timing to demonstrate isolation.
The example was executed on Python 3.12.14 with the default asyncio task behavior. It uses invented labels and in-memory events, without an HTTP server, framework middleware or remote calls. It tests the language-level contract; a framework or job runner can add propagation behavior that needs its own integration test.
Store a binding for the operation, then restore it
Declare the ContextVar at module scope. Calling set(value) changes its binding in the current context and returns a token. reset(token) restores the binding that preceded that set. Put the reset in a finally block around the work that owns the scope. This matters on ordinary returns, application errors and cooperative cancellation.
Restoring the token is more precise than assigning a universal fallback on exit. A nested operation may have temporarily replaced an existing request label. Its cleanup should recover the outer label rather than erase it. The fixture sets at-create, then later-parent, and resets in reverse order to verify both restoration steps.
The default outside string makes the example easy to inspect. In an application where the absence of request context is an error, consider leaving the variable without a default and handling LookupError at a deliberate boundary. Do not silently turn a missing tenant or authorization context into a privileged fallback. Correlation metadata and access-control decisions need separate contracts.
Source: Python 3.12 contextvars: variables, tokens and contexts ↗
Task creation captures a context; it is not a live parent link
With the default create_task behavior, a child task receives a copy of the current context when the task is created. A later set in the parent does not update that child’s binding. The gate in the first fixture holds the child until the parent has changed its value, making the difference visible without guessing which coroutine runs first.
The child returns at-create while the parent still reads later-parent. That observation is useful when debugging a background job that carries an older correlation ID. Check where the task was created, not only where it was awaited. Awaiting a task later does not recapture the awaiting caller’s context.
Calling an async function creates a coroutine object; it does not by itself create a separate task context. A directly awaited helper executes within the caller’s current task. The failure path below deliberately awaits request_scope directly, then checks that its finally block restored the caller’s binding. An unbalanced set in such a helper can affect subsequent caller code.
Python also allows an explicit context argument when creating tasks. That is a separate propagation policy, outside this default-behavior fixture. Review task factories and explicit context arguments when a framework behaves differently from the small example. Avoid assuming every custom scheduling path follows the same inheritance choices.
Source: Python 3.12 asyncio: task contexts, cancellation and to_thread ↗
Run an event-controlled isolation and cleanup fixture
Save this listing as context_scope_demo.py and run python context_scope_demo.py. It requires Python 3.12 or later and no third-party packages. Events establish when each request scope has entered and when it may continue. The assertions do not depend on wall-clock sleeps or on the order in which A and B print messages.
The two request tasks must both reach their waiting points before the parent releases them. Each checks its own label after resumption, and gather returns results in the order supplied to it. The parent separately checks its outside label. This distinguishes task-local bindings from a global variable that merely happened to work during one sequential run.
The cancellation test first waits for entry into the scope, then cancels and awaits the task. Its finally assertion verifies restoration inside that task. The outer test catches the expected cancellation only to continue the fixture; the request coroutine itself does not swallow it. The application-error case similarly checks restoration through an exception path.
import asyncio
from contextvars import ContextVar
request_id = ContextVar('request_id', default='outside')
metadata = ContextVar('metadata')
async def observe(gate):
await gate.wait()
return request_id.get()
async def request_scope(label, arrived, release, fail=False):
token = request_id.set(label)
try:
arrived.set()
await release.wait()
assert request_id.get() == label
if fail:
raise ValueError('fixture failure')
return request_id.get()
finally:
request_id.reset(token)
assert request_id.get() == 'outside'
async def main():
gate = asyncio.Event()
first = request_id.set('at-create')
child = asyncio.create_task(observe(gate))
second = request_id.set('later-parent')
gate.set()
assert await child == 'at-create'
assert request_id.get() == 'later-parent'
request_id.reset(second)
assert request_id.get() == 'at-create'
request_id.reset(first)
assert request_id.get() == 'outside'
arrived_a, arrived_b, release = (asyncio.Event() for _ in range(3))
a = asyncio.create_task(request_scope('A', arrived_a, release))
b = asyncio.create_task(request_scope('B', arrived_b, release))
await arrived_a.wait()
await arrived_b.wait()
assert request_id.get() == 'outside'
release.set()
assert await asyncio.gather(a, b) == ['A', 'B']
arrived, release = asyncio.Event(), asyncio.Event()
cancelled = asyncio.create_task(request_scope('cancelled', arrived, release))
await arrived.wait()
cancelled.cancel()
try:
await cancelled
except asyncio.CancelledError:
pass
else:
raise AssertionError('Expected cancellation')
arrived, release = asyncio.Event(), asyncio.Event()
release.set()
try:
await request_scope('failed', arrived, release, fail=True)
except ValueError:
pass
else:
raise AssertionError('Expected fixture failure')
assert request_id.get() == 'outside'
shared = {'labels': []}
token = metadata.set(shared)
async def append_label():
metadata.get()['labels'].append('child')
try:
await asyncio.create_task(append_label())
assert metadata.get() is shared
assert shared == {'labels': ['child']}
finally:
metadata.reset(token)
print('PASS: creation snapshot, task isolation, nested reset, failure, cancellation, shared object')
if __name__ == '__main__':
asyncio.run(main())A copied context does not clone the object stored in it
The last part intentionally stores one dictionary containing a list. The child appends to that list. The parent then observes the same dictionary and the new child label. This is a local, tested counterexample to the claim that using ContextVar automatically makes every reachable object private to one task.
There are two questions: which object a variable is bound to, and who can mutate that object. Task-local bindings address the first. If two copied bindings refer to the same dictionary, ordinary aliasing still applies. A child can set a different dictionary in its own context without rebinding the parent’s variable, yet mutating the shared dictionary is a different operation.
Prefer simple immutable correlation values when they meet the requirement. For richer metadata, define whether consumers may mutate it, whether a new object is constructed per scope, and whether nested collections must be isolated. A shallow dictionary copy still shares nested lists. The related mutable-defaults guide explores object ownership and copying in more detail; changing the storage location does not remove those decisions.
Source: Python 3.12 copy: assignment and nested object sharing ↗
Make the propagation boundary explicit
At an incoming request boundary, determine the correlation value, set it around the owned processing scope, and reset on exit. Decide what a spawned job should inherit before creating it. A task intended to outlive a request may legitimately retain that request’s label, or it may require a separately constructed job identity. Document the choice instead of depending on incidental task creation order.
This fixture deliberately keeps every task reference and awaits every child it creates. It demonstrates propagation within one process, not delivery of a context value to another service or a persistent queue. Serialize the specific metadata your application requires at those boundaries and validate it when work resumes. A ContextVar object is not a cross-process message envelope.
Keep thread-related assumptions narrow. The asyncio documentation specifies context propagation for to_thread, but that does not establish a blanket rule for every thread API, executor wrapper or worker process. If you introduce one of those boundaries, add a focused test around the exact call path. The published fixture here does not exercise threads or processes.
A logging adapter can read a correlation ContextVar when preparing a record, but installing a variable does not automatically add fields to a logging format. Test the adapter and handlers separately. If the underlying problem is repeated messages rather than an incorrect request label, the linked logging guide addresses handler ownership and propagation.
Debug the lifetime, not just the final log line
Begin with a minimal timeline: where the variable is declared, where each set occurs, which token belongs to that set, where tasks are created, and where reset executes. Use distinct synthetic request labels in tests. A production log containing sensitive request data is not needed to establish this lifecycle.
If an inner scope clears an outer value, look for cleanup that assigns a constant instead of resetting the returned token. If a child sees an older value, move the investigation to its creation boundary. If two tasks unexpectedly observe collection edits, compare object identity and inspect mutation before replacing the event loop or introducing locks.
The published fixture also passed 2,294 additional assertions across 100 seeded groups of concurrent tasks. Each task used its own label, entered a nested binding, restored it, and returned its outer value while release order varied. Those checks support the demonstrated lifecycle; they are not a performance benchmark or proof of isolation in every framework.
Add a regression test for the failure you actually observed. For middleware, include the real request boundary and an exception path. For a detached job, test the intended inheritance after the request scope finishes. For a metadata mapping, mutate a nested collection in one participant and assert the sharing or isolation your API promises. A successful value lookup alone does not cover those behaviors.
| Observed symptom | Boundary to inspect | Useful assertion |
|---|---|---|
| Parent value changes after helper | Direct await and missing token reset | Outer value restored after return and error |
| Child sees an earlier label | Task creation time | Child keeps captured value after parent set |
| Labels differ correctly but collection edits leak | Shared referenced object | Identity and nested mutation policy |
| Cancelled operation leaves unexpected state | finally cleanup in owning scope | Reset executed before cancellation propagates |
Keep scope cleanup and object ownership separate
ContextVar is useful when several logical operations need different bindings while sharing an execution environment. Pair each owned set with token reset, reason about inheritance at task creation, and keep the objects behind those bindings under an explicit mutation policy.
Use the event-controlled fixture as a starting point, then replace its synthetic boundary with your actual framework or scheduler. Keep the assertions for outer restoration, child inheritance and mutable aliasing. Those checks turn a vague “wrong request ID” report into a specific, repeatable contract for how context travels through your application.
Your next steps
- Reset the token to restore the actual preceding binding.
- Inspect task creation when a child carries an unexpected label.
- Test return, error and cancellation cleanup paths.
- A context copy can retain references to shared mutable values.
Sources & official resources
Linked resources checked on 2026-11-05. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →