Async Patterns (Queues, Backpressure, Cancellation)
Production async systems need more than await: you need bounded queues, backpressure, graceful cancellation, and timeouts to stay stable under load.
Introduction
Production async systems need more than await: you need bounded queues, backpressure, graceful cancellation, and timeouts to stay stable under load.
Understanding the topic
Core concepts to understand:
- Use
asyncio.Queue(maxsize=n)to cap memory growth. - Worker pools consume from queue; producers wait when queue is full.
- Use
asyncio.timeout()andTaskGroupfor structured concurrency. - Handle
CancelledErrorand always clean up resources.
Syntax reference
Visual flow / code:
import asyncioasync def producer(q: asyncio.Queue[int]):for i in range(100):await q.put(i) # blocks when queue full (backpressure)for _ in range(4):await q.put(-1) # poison pillsasync def worker(name: str, q: asyncio.Queue[int]):while True:item = await q.get()try:if item == -1:returnawait asyncio.sleep(0.01) # simulate I/Ofinally:q.task_done()async def main():q: asyncio.Queue[int] = asyncio.Queue(maxsize=32)async with asyncio.TaskGroup() as tg:tg.create_task(producer(q))for i in range(4):tg.create_task(worker(f"w{i}", q))await q.join()asyncio.run(main())
Execution workflow
Use asyncio.Queue(maxsize=n) to cap memory growth
Use asyncio.Queue(maxsize=n) to cap memory growth.
Real-world use
Message consumers, webhook pipelines, and event enrichers fail in production when they skip backpressure. Bounded queues and cancellation-safe workers prevent meltdown.
Best practices
- Bound queues.
- Use TaskGroup on Python 3.11+.
- Wrap slow calls with timeout.
- Always call task_done in finally.
Common mistakes
- Unbounded queues cause memory spikes.
- Ignoring cancellation leaks resources.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionWhat is backpressure?+
Answer
asyncio.Queue(maxsize=n): await queue.put() blocks when it is full. Other options are semaphores to limit concurrency and rejecting or shedding load at the edge.Follow-up
2AdvancedQuestionHow do you cancel async tasks safely?+
Answer
task.cancel(), which raises asyncio.CancelledError inside the task at its next await point. Let that exception propagate, or re-raise it after cleanup, and put cleanup in try/finally or async with. Then await the task to confirm it finished. Swallowing CancelledError breaks timeouts and TaskGroup, and asyncio.timeout() uses the same mechanism.Follow-up
3AdvancedQuestionTaskGroup vs gather?+
Answer
asyncio.TaskGroup (3.11+) provides structured concurrency: if one task fails, the others are cancelled and the group raises an ExceptionGroup on exit, so no tasks outlive the block. asyncio.gather by default propagates the first exception but leaves the other awaitables running, unless you use return_exceptions=True. Prefer TaskGroup for new code because its error and cancellation behavior is more predictable.Follow-up
ExceptionGroup with except*?Summary
In summary: Async reliability = queue + timeout + cancellation discipline. Structured concurrency reduces failure modes.