Python Tutorial 0/52 lessons ~6 min read Lesson 44

    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.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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() and TaskGroup for structured concurrency.
    • Handle CancelledError and always clean up resources.

    Syntax reference

    Visual flow / code:

    python
    import asyncio
    async 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 pills
    async def worker(name: str, q: asyncio.Queue[int]):
    while True:
    item = await q.get()
    try:
    if item == -1:
    return
    await asyncio.sleep(0.01) # simulate I/O
    finally:
    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

    1Async Patterns (Queues, Backpressure, Cancellation) Workflow
    1 / 4

    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.

    3 questions
    1IntermediateQuestionWhat is backpressure?+

    Answer

    Backpressure is a mechanism for slowing down a producer when a consumer cannot keep up, so work does not pile up without limit in memory. In asyncio, the usual tool is a bounded 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

    What happens with an unbounded queue under sustained overload?
    2AdvancedQuestionHow do you cancel async tasks safely?+

    Answer

    Call 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

    How can you protect a critical section from cancellation?
    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

    How do you handle an ExceptionGroup with except*?

    Summary

    In summary: Async reliability = queue + timeout + cancellation discipline. Structured concurrency reduces failure modes.

    Ready to mark this lesson complete?Track your journey across the entire course.