Lesson 8 of 9 · 25m
The Classic Async Bugs: Races, Reentrancy, and Lock Abuse
The bugs senior teams keep rediscovering: mutable shared state, check-then-act races, deadlocks, starvation, and context variables that leak or vanish.
Async bugs rarely look dramatic in a unit test. They appear as one corrupted cache entry every six hours, a lock that only deadlocks during deploys, or user A briefly seeing user B's data under a traffic spike. They are race conditions with better hiding places.
Shared mutable state is still shared
connections = {}
async def connect(user_id):
if user_id not in connections:
ws = await open_ws()
connections[user_id] = ws
return connections[user_id]Two tasks can both observe user_id not in connections, both open a websocket, and one overwrite the other. No thread is involved; the interleaving happens because await open_ws() suspends between the check and the write. This is a check-then-act race.
Make the operation atomic relative to suspension points, or serialize it:
locks = defaultdict(asyncio.Lock)
async def connect(user_id):
async with locks[user_id]:
if user_id not in connections:
connections[user_id] = await open_ws()
return connections[user_id]Locks protect invariants, not lines of code
An asyncio.Lock is not a magical correctness blanket. Define the invariant: 'while this lock is held, this mapping is consistent with that external connection.' Keep the critical section as short as possible, but not shorter than the invariant requires.
Do not hold locks across unrelated slow operations:
async with lock:
await slow_remote_call() # every other task queues behind the network
shared[key] = valueFetch first, then enter the lock only to commit consistent state. If remote state itself is part of the invariant, you need a different design: ownership, compare-and-swap, or a single writer.
Deadlocks do not require threads
async def transfer(a, b, amount):
async with locks[a]:
async with locks[b]:
...Two concurrent transfers in opposite directions can acquire different first locks and wait forever. Establish a global lock ordering — for example sort account IDs before locking — or use one coordination point.
Also watch reentrancy. asyncio.Lock is not reentrant: a task that already holds it will block forever trying to acquire it again, often through a helper function added months later. If you need ownership tracking, design it explicitly; do not imitate recursive locks by accident.
contextvars are the right request context — mostly
contextvars.ContextVar carries values such as request IDs across awaits without threading them through every call. Async frameworks often use them for tracing.
request_id = contextvars.ContextVar('request_id', default='-')
async def handler():
token = request_id.set('req-01JXYZ')
try:
await business_logic()
finally:
request_id.reset(token)The trap is task creation. Tasks copy the context at creation time, so later changes in the parent do not propagate. Conversely, fire-and-forget tasks can retain request context long after the request ended, causing misleading logs. Copy deliberately and sanitize deliberately.
Starvation is quieter than deadlock
A high-priority producer can keep a queue full forever, meaning low-priority consumers never run. A task that repeatedly awaits immediate operations can monopolize the loop. Watch fairness: queue age, scheduling delays, and whether the loop heartbeat is slipping.
Field notes
- If a bug disappears when you add logging, suspect a scheduling race — logging can add enough delay to change interleavings.
asyncio.Lockownership is task-based, not thread-based. Do not pass one lock across threads and expect meaning.- Use
asyncio.Eventfor one-time state changes andasyncio.Conditionwhen consumers need predicate-based wakeups; boolean polling loops waste the loop. - Prefer making state immutable or owned by one task over sprinkling locks across the codebase.
Was this lesson helpful?