Cooperative multitasking on a single thread
async and await give Python cooperative multitasking: one thread runs many coroutines, and each coroutine yields control only at an await point. The event loop is the scheduler that decides which ready coroutine runs next, much like an operating system context-switches threads, except the switch happens by agreement rather than preemption. The payoff is enormous connection counts with tiny memory overhead per task; the price is discipline โ one un-awaited blocking call stalls every coroutine sharing that loop. Interviewers ask about async to see whether you understand both halves of that trade and can design code that never accidentally blocks the loop.
Prerequisites
- !Functions, coroutines, and the difference between def and async def
- !Basic familiarity with asyncio.run
What You'll Learn
- 1Explain what happens between await points and who drives execution
- 2Use gather, wait, TaskGroup, and Semaphore to structure concurrent work
- 3Write async context managers and async generators correctly
- 4Identify blocking calls, missing awaits, and cancellation hazards in real code
Coroutines, tasks, and the event loop
An async def function returns a coroutine object when called; nothing runs until that coroutine is scheduled. asyncio.run(coro) creates an event loop, drives the coroutine to completion, and tears the loop down โ it is the entry point for scripts. Inside a coroutine, await hands control back to the loop: if the awaited object is ready, execution continues immediately; otherwise the coroutine suspends until the loop wakes it, typically when a timer fires or a socket becomes readable. asyncio.create_task schedules a coroutine concurrently and returns a handle you can await later or cancel โ the essential tool for overlapping independent operations.
The subtlety interviewers probe: forgetting to await or to create a task silently does nothing. asyncio.gather(fetch_a(), fetch_b()) runs both concurrently because gather schedules them; calling fetch_a() without awaiting merely creates a coroutine object that is eventually garbage-collected with a warning. Another classic is calling a blocking library โ synchronous HTTP, heavy CPU work, time.sleep โ directly inside a coroutine, which freezes the loop. The fixes are asyncio.to_thread(fn, args) for blocking work that can live on a worker thread, and moving CPU-heavy computation into a process pool.
import asyncio
async def fetch(url, delay):
print(f"start {url}")
await asyncio.sleep(delay) # simulated I/O โ loop stays responsive
print(f"done {url}")
return {"url": url, "status": 200}
async def main():
# Sequential: roughly delay1 + delay2 seconds
# await fetch("a", 1)
# await fetch("b", 1)
# Concurrent: roughly max(delay1, delay2) seconds
results = await asyncio.gather(
fetch("api/items", 1),
fetch("api/users", 1),
)
return results
print(asyncio.run(main()))
Structured concurrency: gather, wait, and TaskGroup
asyncio.gather is the workhorse: it schedules awaitables, waits for all, and returns results in argument order. Passing return_exceptions=True converts failures into result values, letting one slow or failing endpoint not cancel its siblings. asyncio.wait returns two sets โ done and pending โ when a timeout elapses, which you need for partial-result patterns such as racing three search backends and using whichever answers first while cancelling the rest. State the failure semantics of whichever you pick; mixing them silently is how timeout bugs slip into production.
Python 3.11 introduced TaskGroup, the structured-concurrency answer: every task created inside the group is awaited before the block exits, and if any task raises, the group cancels the siblings and re-raises an ExceptionGroup. Structure that bounds task lifetime is exactly what production systems need to prevent orphaned tasks leaking connections. asyncio.Semaphore caps concurrency โ a semaphore of five around twenty fetches prevents your client from stampeding a third-party API. And asyncio.timeout (3.11+) scopes a cancellation deadline to a block instead of hand-rolling wait_for chains.
import asyncio
async def worker(name, sem, results):
async with sem:
await asyncio.sleep(0.1)
results.append(name)
async def grouped():
sem = asyncio.Semaphore(3)
results = []
async with asyncio.TaskGroup() as tg:
for i in range(10):
tg.create_task(worker(f"job-{i}", sem, results))
return results # all tasks finished by the time this line runs
print(asyncio.run(grouped()))
Async iteration, context managers, and queues
Generators gained async cousins: async for iterates objects implementing __aiter__ and __anext__, and async def functions containing yield produce async generators that support asend, athrow, and aclose. Async comprehensions โ [x async for x in gen] โ materialize an async stream. You need these whenever each step awaits: paginated API reads, database cursors, streaming parsers.
Resource cleanup follows the same shape with async with, backed by __aenter__ and __aexit__, or the @asynccontextmanager decorator for function-style managers. An async database connection that acquires a pool slot on entry and releases it on exit โ including the exception path โ is the pattern to memorize. asyncio.Queue completes the picture for producer-consumer designs: producers await queue.put(item), consumers await queue.get(), and queue.task_done() plus await queue.join() give you backpressure and completion tracking without locks, because the loop guarantees no preemption between awaits in queue operations.
Cancellation, timeouts, and error handling
Concurrency multiplies failure modes. Timeouts should use asyncio.timeout or wait_for so hung operations release resources. Cancellation arrives as a CancelledError raised inside your coroutine; well-written code catches it only to clean up (closing files, releasing locks) and then re-raises. Swallowing cancellation is a bug that keeps tasks alive forever. gather without return_exceptions propagates the first exception but leaves other tasks running โ cancel them explicitly or move to TaskGroup for automatic cleanup. Exception groups from TaskGroup need except* syntax or ExceptionGroup iteration to handle granularly, a detail worth mentioning even if the interviewer does not push. Prefer failing fast: a deadline that cancels a slow branch is better than a request that hangs until the client gives up.
Testing and debugging async code
pytest-asyncio is the standard test harness; mark tests with @pytest.mark.asyncio or configure auto mode. For debugging, enable asyncio debug mode (python -W error::RuntimeWarning and the loop's debug flag) to surface un-awaited coroutines, slow callbacks, and tasks that never finished. Logs that print task names help correlate interleaved output. When an async service deadlocks, suspect an await that never returns โ a queue nobody drains, a lock held across an await, or a blocking call in the loop thread.
Two testing techniques repay the investment. First, inject the clock or the client: a coroutine that awaits a fetcher function you control in tests lets you drive completion order deterministically instead of sleeping and hoping. Second, asyncio.wait_for with tiny timeouts converts a hung test into a fast failure rather than a suite-wide stall. For cancellation tests, create a task, let it start, cancel it, and assert that a finally inside the coroutine ran โ that single test catches the swallow-the-error bug class.
| Situation | Right tool | Wrong tool |
|---|---|---|
| Overlapping independent I/O | gather or TaskGroup | Sequential awaits |
| Racing multiple backends | wait with timeout, cancel losers | Letting all run to completion |
| Bounding API pressure | Semaphore | Unbounded gather |
| Blocking library call | asyncio.to_thread | Calling it directly |
| CPU-heavy compute | ProcessPoolExecutor off-loop | Tight loop inside a coroutine |
| Resource lifetime | async with | Manual try/finally without aenter |
Common Mistakes
Calling a coroutine without awaiting it
Fix: await it or wrap it in create_task; otherwise nothing runs
Blocking the loop with time.sleep, requests, or heavy CPU work
Fix: Use asyncio.sleep, an async HTTP client, asyncio.to_thread, or a process pool
Catching CancelledError and continuing
Fix: Clean up and re-raise so tasks actually stop
Spawning unbounded tasks with create_task in a loop
Fix: Gate creation with a semaphore or feed work through an asyncio.Queue
Best Practices
- Prefer TaskGroup on modern Python for automatic cleanup and error aggregation
- Keep coroutine bodies small and push blocking work off the loop explicitly
- Use asyncio.timeout for deadlines rather than ad-hoc timing checks
- Log with task names so interleaved output stays diagnosable
Interview Questions
Q1: What is the difference between asyncio and threading for I/O-bound work?
Threads rely on the OS scheduler and share memory; context switches are heavier and shared state needs locks. Asyncio multiplexes many coroutines on one thread with cooperative switching and lightweight task objects, but requires an all-async stack and offers no preemption against blocking calls.
Q2: How does the event loop handle a blocking call in async code?
It cannot โ the loop thread is stuck until the call returns, freezing every coroutine. Offload with asyncio.to_thread, run the work in a process pool, or use an async-native library.
Q3: What is structured concurrency and why does it matter?
It bounds the lifetime of child tasks to a lexical block, guaranteeing all are finished or cancelled when the block exits. TaskGroup implements this, preventing leaks and simplifying error propagation via ExceptionGroup.
Q4: How do you test async code effectively?
Use pytest-asyncio, inject fake transports or monkeypatched coroutines, control time with freezegun-style helpers or short sleeps, and assert on side effects after the coroutine completes. Enable loop debug mode to catch un-awaited coroutines.
Q5: Explain backpressure in an async system.
It is the mechanism that stops fast producers from overwhelming slow consumers โ typically a bounded asyncio.Queue where put() suspends once full, so producers slow to the consumer's rate.
Key Takeaways
- async def defines a coroutine; execution starts only when awaited or scheduled
- The event loop switches at await points โ one blocking call freezes everything
- gather, wait, TaskGroup, and Semaphore structure concurrent work with different trade-offs
- Async context managers and async generators extend with/for to the async world
- Cancellation is an exception to clean up after, not to swallow
- Offload blocking and CPU work; never run it directly on the loop