The async bug that hands one tenant's ID to another's request
It never shows in a single-user demo; under production load, a per-request ContextVar reset with its token is what keeps tenants apart.
In brief
- Thread-local variables cannot separate asyncio tasks running on the same thread, so use a ContextVar.
- A new task gets a copy of the context as it stood when the task was created, and to_thread carries the context into a worker thread.
- Set the tenant in pure ASGI middleware, reset it with the token, and clear the log context at the start of every request.
PEP 567 was adopted in 2018 on a blunt premise: thread-local variables are not enough when many asynchronous tasks run concurrently on the same OS thread. In a multi-tenant system, the consequence is that a request from customer A can read customer B’s tenant ID, because the two are interleaved on a single event loop.
On a client’s system, this kind of bug rarely shows up in a demo. In a demo one person is clicking and everything runs sequentially. The bug appears in production, with real data and real load. At that point a single log line tagged with the wrong tenant, or a query filtered by the wrong tenant, is enough to become a security incident.
This guide builds a small working example on a laptop: a tenant ID set per request, carried through child tasks and worker threads, and cleaned up when the request ends. You need Python 3.11 or later, because a parameter used in step 4 arrived in that version. To try the logging section, install structlog as well.
Step 1: declare the variable at module level
The Python documentation says context variables should be created at module level and never inside closures or functions, to avoid problems with garbage collection. Create tenant.py:
# tenant.py
import contextvars
tenant_id = contextvars.ContextVar("tenant_id")
The whole application imports this one object. According to the Python documentation, asyncio supports context variables natively with no extra configuration, so there is nothing to register with the event loop.
Check: run grep -rn "ContextVar(" . in the repo. Every match must sit at module level, not indented inside a def.
Step 2: set per request and restore the old value with the token
ContextVar.set() returns a Token object. Pass that token to reset() and the variable returns to the value it had before the set. The value therefore lives only for the duration of one request, and finally guarantees cleanup even when the handler raises.
# demo.py
import asyncio
from tenant import tenant_id
async def query_db():
await asyncio.sleep(0.1) # simulate I/O, yield to the event loop
return tenant_id.get()
async def handle(t):
token = tenant_id.set(t)
try:
child = asyncio.create_task(query_db())
return await child
finally:
tenant_id.reset(token)
async def main():
# each request runs in its own explicitly created task
req_a = asyncio.create_task(handle("acme"))
req_b = asyncio.create_task(handle("globex"))
print([await req_a, await req_b])
asyncio.run(main())
This is a contrived test case: two tenants run at once, and both pause at sleep before reading the variable. With thread-local storage, the two assignments would overwrite each other because there is only one thread. With a ContextVar, the output should be ['acme', 'globex'].
Why does the child task see the right tenant?
Under PEP 567, each asyncio task holds its own context, inherited at the moment it is created. The create_task documentation is more precise: if no context is passed, the task copies the current context and runs the coroutine inside that copy.
In the demo, main calls create_task separately for each request, so each handle(...) runs on its own copy; the set inside changes only that copy and never touches the other request.
The key words are “copy at creation”. If you call create_task before set, the child task will not see the tenant. If the child task sets a different value itself, the parent will not see that change either.
Check: swap the order in handle, creating the task first and calling set afterwards, then run it again. Because the variable has no value in the child task’s copy, tenant_id.get() without a default raises LookupError. To see the result more clearly, temporarily change the read in query_db to tenant_id.get("<unset>"): the output becomes ['<unset>', '<unset>']. Break it deliberately once and the lesson sticks.
Step 3: synchronous code via to_thread
At clients you will often meet an SDK or legacy driver that only offers synchronous functions. The Python documentation confirms that asyncio.to_thread carries the current context into the worker thread, so synchronous code can still read the tenant:
def sync_report():
return tenant_id.get() # runs in a worker thread
async def handle_report(t):
token = tenant_id.set(t)
try:
return await asyncio.to_thread(sync_report)
finally:
tenant_id.reset(token)
If the client uses Django, its documentation states that sync_to_async and async_to_sync preserve both threadlocals and contextvars in both directions across the sync/async boundary. Those two wrappers are safe. The risk lies wherever someone manages a thread pool by hand without going through them.
Step 4: background jobs and callbacks
Callbacks scheduled with loop.call_soon run in the current context by default. Called from inside a request, the callback sees that request’s tenant. That is what you want for audit logging, but it is a surprise if the callback was meant to run on behalf of all tenants.
Since Python 3.11, create_task accepts a context parameter, so you can choose the context for a background job deliberately instead of letting it copy the request’s. The practical advice: any background job that outlives its request should receive the tenant explicitly, as an argument or through a context you choose, rather than depending on where it happened to be created.
Middleware is where it most often goes wrong
Starlette warns that BaseHTTPMiddleware prevents changes to a ContextVar from propagating upwards. The concrete trap: an authentication dependency at an inner layer sets the tenant, while a logging middleware at an outer layer reads the tenant after the request finishes, and it never sees the value. Starlette recommends pure ASGI middleware to avoid this limitation:
# Simplified for illustration: in production, take the tenant from an
# authenticated token, never trust a raw header sent by the client.
class TenantMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
headers = dict(scope["headers"])
token = tenant_id.set(headers.get(b"x-tenant-id", b"").decode())
try:
await self.app(scope, receive, send)
finally:
tenant_id.reset(token)
This is the same set/reset pattern from step 2, moved to the outermost layer. Set the value here and every handler, task and thread below inherits it.
Logs must carry the right tenant, not a stale one
Logs are the most easily overlooked leak, because they break no functionality. The structlog documentation gives two rules. Processor order matters: merge_contextvars must come first for values bound to the context to appear in the log. And the handler should call clear_contextvars() at the very start of each request so that the previous request’s tenant_id does not leak into the next request’s logs.
import structlog
structlog.configure(
processors=[
structlog.contextvars.merge_contextvars, # must come first
# ... other processors (abridged)
]
)
async def handler(request):
structlog.contextvars.clear_contextvars()
...
Check: send interleaved requests for two tenants, then grep the logs for each tenant. No line belonging to one tenant may carry the other’s ID.
Taking this skill to a client
On your first day in a client’s multi-tenant codebase, do three things in this order:
- Find every place that holds a tenant or user in
threading.localor a global variable. - Check whether the middleware is
BaseHTTPMiddlewareor pure ASGI. - Open the logger configuration and see whether
merge_contextvarscomes first.
All three are code reading with no changes required, which makes them a good start before you touch any business logic.
For your career: when an FDE job posting mentions “multi-tenant”, “data isolation” or deployment on the client’s infrastructure, that is the moment to tell this story in an interview. On a CV, do not write “proficient in asyncio”. Be specific: you moved tenant context into a ContextVar, switched the middleware to ASGI, and added a test that runs two tenants concurrently to catch leaks.
The two-tenant test from step 2 is only a few dozen lines long, yet it answers the question a client asks after an incident: how do you know their data has not leaked to someone else?
Was this article useful?
Thanks for the feedback!
8 sources
- PEP 567 – Context Variables · 2018-01-22
- contextvars — Context Variables — Python documentation
- Coroutines and tasks — Python documentation
- Coroutines and tasks — Python documentation (asyncio.to_thread)
- Event loop — Python documentation
- Middleware - Starlette
- Asynchronous support | Django documentation
- Context Variables — structlog documentation