Most asyncio interview questions reduce to a handful of patterns. Run many things at once, cap how many run, give up after a deadline, stop cleanly when cancelled, and feed work through a queue. The API for each is small. The marks are in the semantics. You need to know what happens to the other tasks when one fails, where a CancelledError lands, and which state can change across an await.
Every snippet below is complete and runs on Python 3.12 or newer. Paste one into a file and run it. Each section ends with the mistake interviewers see most often for that pattern.
The one rule behind everything
asyncio runs on one thread. A coroutine runs until it reaches an await that has to wait, and then the event loop runs something else. Two consequences follow, and most bugs come from forgetting one of them.
First, blocking code blocks everything. time.sleep(1), a CPU-heavy loop or a synchronous HTTP call inside a coroutine stops every other task for that long. Use await asyncio.sleep(), async libraries, or asyncio.to_thread for blocking calls you can't avoid.
Second, single-threaded does not mean race-free. Code between two awaits runs without interruption, but any await is a point where another task can change shared state. If you read a value, await something, then write the value back, you have a race.
gather vs TaskGroup
asyncio.gather runs awaitables concurrently and returns their results in the order you passed them. asyncio.TaskGroup, added in Python 3.11, does the same job with stricter failure handling. The difference shows up when something raises.
import asyncio
async def fetch(i: int) -> int:
await asyncio.sleep(0.01 * i)
if i == 2:
raise ValueError(f"item {i} failed")
return i * 10
async def main() -> None:
results = await asyncio.gather(
*(fetch(i) for i in range(4)), return_exceptions=True
)
print(results) # [0, 10, ValueError('item 2 failed'), 30]
try:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(i)) for i in range(4)]
except* ValueError as group:
print("failed:", group.exceptions) # (ValueError('item 2 failed'),)
else:
print([t.result() for t in tasks])
asyncio.run(main())With return_exceptions=True, gather never raises for a child's error. Exceptions come back in the results list in their slot, and you check each one with isinstance(r, Exception). That fits "fetch everything, report what failed".
With the default return_exceptions=False, gather raises the first exception to the caller and leaves the other awaitables running. Nothing cancels them. They keep using connections and their later exceptions are never retrieved.
TaskGroup cancels the remaining tasks as soon as one fails, waits for them to finish, and raises an ExceptionGroup containing every failure. You catch it with except*. The async with block doesn't exit until every task is done, so no task outlives the block. Use it when one failure makes the rest pointless.
Common mistake. Using plain gather without return_exceptions and assuming a failure stops the other tasks. It doesn't. Either use TaskGroup, or pass return_exceptions=True and handle each result.
Bounded concurrency with Semaphore
"Fetch 10,000 URLs, at most 20 at a time" is probably the most common asyncio question. asyncio.Semaphore(n) lets n holders in at once. Everyone else waits at async with.
import asyncio
in_flight = 0
peak = 0
async def fetch(url: str) -> str:
global in_flight, peak
in_flight += 1
peak = max(peak, in_flight)
await asyncio.sleep(0.01)
in_flight -= 1
return url.upper()
async def fetch_all(urls: list[str], limit: int) -> list[str]:
sem = asyncio.Semaphore(limit)
async def one(url: str) -> str:
async with sem:
return await fetch(url)
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(one(u)) for u in urls]
return [t.result() for t in tasks]
urls = [f"u{i}" for i in range(100)]
results = asyncio.run(fetch_all(urls, limit=5))
print(results[:3], "peak:", peak) # ['U0', 'U1', 'U2'] peak: 5async with sem releases the permit even when fetch raises or the task is cancelled. Calling acquire() and release() by hand invites leaks on the error path.
This version still creates one task per URL up front. For 10,000 items that is fine. For ten million, the task objects themselves cost memory, and a fixed worker pool (below) is the better shape.
Common mistake. Creating the semaphore inside the per-item function, so every call gets its own semaphore and the limit does nothing. The semaphore must be shared by all callers. A close second is holding the permit while sleeping between retries, which wastes a slot doing nothing.
Timeouts and deadlines
Python 3.11 added asyncio.timeout(), a context manager that bounds everything inside it. asyncio.wait_for() bounds a single awaitable. Both cancel the work when time runs out and raise TimeoutError.
import asyncio
async def slow() -> str:
await asyncio.sleep(1)
return "done"
async def main() -> None:
try:
await asyncio.wait_for(slow(), timeout=0.05)
except TimeoutError:
print("wait_for timed out")
try:
async with asyncio.timeout(0.05):
await slow()
await slow()
except TimeoutError:
print("timeout block expired")
asyncio.run(main())When a timeout spans retries, put the timeout around the whole retry loop. That gives the caller one budget instead of one per attempt.
import asyncio
attempts_made = 0
async def flaky() -> str:
global attempts_made
attempts_made += 1
await asyncio.sleep(0.03)
raise ConnectionError("backend unavailable")
async def call_with_budget(budget: float, attempts: int) -> str:
async with asyncio.timeout(budget):
for attempt in range(attempts):
try:
return await flaky()
except ConnectionError:
if attempt == attempts - 1:
raise
await asyncio.sleep(0.01 * 2**attempt)
raise AssertionError("unreachable")
try:
asyncio.run(call_with_budget(budget=0.1, attempts=10))
except TimeoutError:
print("gave up after", attempts_made, "attempts") # about 3asyncio.wait(tasks, timeout=...) is a different tool. It returns (done, pending) when the time is up and cancels nothing, so the pending tasks are still yours to cancel or await.
Common mistake. Wrapping each attempt in its own wait_for(op(), timeout=2) inside a five-attempt loop and telling the interviewer the call is bounded at two seconds. It is bounded at ten seconds plus the backoff. Think in deadlines.
Cancellation
task.cancel() does not stop a task immediately. It schedules a CancelledError to be raised inside the task at the await where it is suspended. The task can clean up, and it should then let the error propagate.
import asyncio
async def worker(log: list[str]) -> None:
try:
while True:
await asyncio.sleep(0.05)
except asyncio.CancelledError:
log.append("cancelled")
raise
finally:
log.append("cleanup")
async def main() -> None:
log: list[str] = []
task = asyncio.create_task(worker(log))
await asyncio.sleep(0.01)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
print(log, task.cancelled()) # ['cancelled', 'cleanup'] True
asyncio.run(main())Release resources in finally or with async with, which covers cancellation, timeouts and ordinary errors in one place. Awaiting the task after cancel() is how you know the cleanup has finished.
Sometimes a short piece of work must finish even if the caller is cancelled, such as writing a record that has already been charged. asyncio.shield() protects the inner task from the outer cancellation. Keep the shielded work short.
import asyncio
async def save(record: str, saved: list[str]) -> None:
await asyncio.sleep(0.05)
saved.append(record)
async def handle(record: str, saved: list[str]) -> None:
write = asyncio.create_task(save(record, saved))
try:
await asyncio.shield(write)
except asyncio.CancelledError:
await write
raise
async def main() -> None:
saved: list[str] = []
task = asyncio.create_task(handle("order-1", saved))
await asyncio.sleep(0.01)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
print(saved) # ['order-1']
asyncio.run(main())The await write in the handler finishes the write and then re-raises, so the caller still sees the cancellation it asked for.
Common mistake. Swallowing CancelledError. A bare except:, an except BaseException: without raise, or except asyncio.CancelledError: return makes the task ignore cancellation. TaskGroup and asyncio.timeout() both depend on that error propagating, so swallowing it breaks them too. except Exception is safe here, because CancelledError has subclassed BaseException since Python 3.8.
Queue and a worker pool
A worker pool is a fixed number of tasks pulling jobs from a shared asyncio.Queue. It is the right shape when the input is large or arrives over time, and when you want backpressure. A bounded queue makes the producer's await queue.put() wait while the workers are behind.
import asyncio
async def process(job: int) -> int:
await asyncio.sleep(0.01)
if job == 3:
raise ValueError("bad job")
return job * job
async def worker(queue: asyncio.Queue, results: dict) -> None:
while True:
index, job = await queue.get()
try:
results[index] = await process(job)
except Exception as exc:
results[index] = exc
finally:
queue.task_done()
async def run_pool(jobs: list[int], workers: int) -> list:
queue: asyncio.Queue = asyncio.Queue(maxsize=workers * 2)
results: dict = {}
tasks = [asyncio.create_task(worker(queue, results)) for _ in range(workers)]
for item in enumerate(jobs):
await queue.put(item)
await queue.join()
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
return [results[i] for i in range(len(jobs))]
print(asyncio.run(run_pool(list(range(6)), workers=3)))
# [0, 1, 4, ValueError('bad job'), 16, 25]The details carry the marks. The worker catches per-job errors so one bad job doesn't kill it, and the pool doesn't quietly shrink to zero. task_done() sits in finally so join() can't hang. Results go into slots keyed by input index, because jobs finish out of order. After join() returns, every job is done, so cancelling the idle workers is safe.
The other standard shutdown is a sentinel. Put one None (or a private object()) per worker after the real jobs, and have each worker return when it reads one. Sentinels suit a pipeline where workers must drain and exit on their own. join() and cancel suits a pool you own end to end.
Common mistake. Letting an exception escape the worker loop. The worker dies, task_done() is never called for that job, queue.join() waits forever, and the test times out with no error message. A close second is sending fewer sentinels than there are workers.
Results as they finish with as_completed
asyncio.as_completed yields results in completion order, which suits "show each result as soon as it arrives" or "stop after the first k successes".
import asyncio
async def probe(name: str, delay: float) -> str:
await asyncio.sleep(delay)
return name
async def main() -> None:
tasks = [
asyncio.create_task(probe("slow", 0.06)),
asyncio.create_task(probe("fast", 0.01)),
asyncio.create_task(probe("medium", 0.03)),
]
for next_done in asyncio.as_completed(tasks):
first = await next_done
break
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
print("first:", first) # first: fast
asyncio.run(main())Common mistake. Breaking out of the loop and leaving the slower tasks running. Cancel and await the rest, or run them inside a TaskGroup you leave by raising.
A token bucket rate limiter
Rate limiters come up often enough to practise on their own (see rate limiting). An async token bucket refills lazily from a monotonic clock and makes callers wait for the next token.
import asyncio
import time
class TokenBucket:
def __init__(self, rate: float, capacity: float) -> None:
self.rate = rate
self.capacity = capacity
self.tokens = capacity
self.updated = time.monotonic()
self.lock = asyncio.Lock()
def _refill(self) -> None:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
async def acquire(self) -> None:
async with self.lock:
self._refill()
while self.tokens < 1:
await asyncio.sleep((1 - self.tokens) / self.rate)
self._refill()
self.tokens -= 1
async def main() -> None:
bucket = TokenBucket(rate=50, capacity=5)
start = time.monotonic()
await asyncio.gather(*(bucket.acquire() for _ in range(15)))
print(f"15 acquires took {time.monotonic() - start:.2f}s") # about 0.20s
asyncio.run(main())Five tokens go immediately as a burst, and the other ten arrive at 50 per second. The lock holds waiters in line while one of them sleeps for the next token. asyncio.Lock wakes waiters in the order they arrived, so callers are served first come, first served.
Common mistake. Checking self.tokens >= 1, awaiting something, then decrementing. Two coroutines both pass the check and the bucket goes negative. The check and the decrement must happen with no await between them, or under a lock. Using time.time() instead of time.monotonic() is the other classic slip, since wall-clock time can jump.
How to practise
Reading these patterns is the easy part. Writing them under time pressure, with tests that probe the edge cases, is what the interview measures. Each problem on this site runs on real CPython in your browser, so asyncio.run, TaskGroup and asyncio.timeout behave as they do on your machine.
- 12Inference Worker Poolmedium
Run inference requests through a fixed pool of asyncio workers sharing one queue, isolate failures, and return results in input order.
- 16Async Circuit Breakerhard
Implement an asyncio circuit breaker with closed, open and half-open states, a single recovery probe, and protection against stale in-flight calls.
- 20Dynamic Request Batcherhard
Group concurrent inference requests into batches that flush when full or when the oldest request has waited long enough, with cancellation and drain.
- 21Async TTL Cache with Request Coalescingmedium
Build an asyncio cache whose entries expire after a TTL, where concurrent misses for the same key share one fetch that survives caller cancellation.
- 22Async Retry with Exponential Backoffmedium
Retry a failing coroutine with capped exponential backoff, re-raise the last error, and never swallow cancellation.
- 25Async Request Deduplicatorhard
Collapse concurrent fetches for the same key into one shared call, with per-caller timeouts that never cancel the shared work.
Topic pages collect the related problems in one place. Start with asyncio, then timeouts, worker pools and cancellation. The practical coding interview guide covers how these questions are graded and how to run timed practice.
Frequently asked questions
What is the difference between asyncio.gather and asyncio.TaskGroup?
By default gather raises the first exception and leaves the other awaitables running, while return_exceptions=True puts exceptions in the results list instead. TaskGroup cancels the remaining tasks when one fails, waits for them, and raises an ExceptionGroup you catch with except*.
How do I limit concurrency in asyncio?
Share one asyncio.Semaphore(n) across all callers and wrap each operation in async with sem. For very large or unbounded inputs, use a fixed pool of workers reading from a bounded asyncio.Queue instead of one task per item.
Should I use asyncio.wait_for or asyncio.timeout?
wait_for bounds a single awaitable, and asyncio.timeout, added in Python 3.11, bounds everything inside an async with block. Both cancel the work and raise TimeoutError. When retrying, put one timeout around the whole retry loop so the caller gets a single deadline.
How should a coroutine handle CancelledError?
Clean up in finally or with async with, then let the CancelledError propagate. Swallowing it with a bare except or a return breaks task.cancel(), TaskGroup and asyncio.timeout.
How do I shut down an asyncio worker pool cleanly?
Either await queue.join() and then cancel the idle workers, or put one sentinel per worker after the real jobs. Call task_done() in a finally block and catch per-job errors inside the worker loop, or join() can hang forever.
Can asyncio code have race conditions if it runs on one thread?
Yes. Any await is a point where another task can run and change shared state, so a read, an await and a write back is a race. Keep check-and-update sequences free of awaits or protect them with an asyncio.Lock.