Skip to main content
← CONCEPTS / CONCURRENCY
An end-to-end domain learning journey

Python Asyncio: Event Loops,
Coroutines, Tasks & Backpressure.

Python's asyncio achieves high-throughput single-threaded I/O concurrency via a cooperative event loop, non-blocking coroutines (async def / await), asyncio.TaskGroup, and bounded asyncio.Semaphore / asyncio.Queue backpressure.
Start the journey7 sections· Last modified Nov 16, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When naive scans degrade into quadratic bottlenecks, Coroutines, Tasks & Backpressure, never call blocking I/O (requests.get, time.sleep) or heavy CPU loops directly on the event loop; offload blocking calls with `asyncio.to_thread` and bound fan-out with `asyncio.Semaphore`.

TL;DR30-second simplified summary
▾

Core Mechanics: Python asyncio is a single-threaded, cooperative concurrency runtime built around an event loop (epoll / kqueue).

Visual & Structural Flow: Depicts Asyncio Event Loop Task State Machine (RUNNING -> SUSPENDED (I/O) -> LOOP BLOCKED); TaskGroup + Semaphore Backpressure Flow (TaskGroup -> Semaphore(20) -> httpx.AsyncClient -> Upstream API).

Trade-Offs & Production: Choose the concurrency primitive based on I/O vs. A FastAPI LLM proxy uses uvicorn workers with asyncio.Semaphore(50) capping upstream GPU calls, a bounded asyncio.Queue(maxsize=200) for SSE token streaming, and.

Failure Modes & Application: Explore event-loop starvation prevention, async rate-limited scrapers, and Python no-GIL concurrency.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Python GIL-Free Concurrency, Asyncio & Coroutines
Free-threaded Python (PEP 703, CPython 3.13t+) removes the Global Interpreter Lock so multiple threads execute Python bytecode simultaneously across CPU cores within a single shared memory space.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is Python Asyncio.

Why this matters: The mechanism: understand how Python Asyncio works from first principles.

Python asyncio is a single-threaded, cooperative concurrency runtime built around an event loop (epoll / kqueue). Coroutines (async def) only yield control back to the event loop at explicit await points—keeping per-task memory in kilobytes with zero lock contention on shared single-thread structures.

Python 3.11+ asyncio.TaskGroup provides structured concurrency: if any child task raises an exception, sibling tasks are cancelled cleanly before the group exits.

Coroutine Scheduling

Asyncio Event Loop Task State Machine

await socket / sleepI/O ready -> loop resumesrequests.get() /…RUNNINGExecuting until awaitSUSPENDED (I/O)Registered on epoll/kqueLOOP BLOCKEDSync I/O stalls all task

Because scheduling is cooperative, a single synchronous call freezes every coroutine on the loop.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need Asyncio (and how One Blocking Call Freezes FastAPI).

Why this matters: The problem: see what breaks without Asyncio under real concurrency or scale.

Think of Why we need Asyncio (and how One Blocking Call Freezes FastAPI) as the intuition layer for Python Asyncio: Event Loops, Coroutines, Tasks & Backpressure: The problem: see what breaks without Asyncio under real concurrency or scale.

A single requests.get() or time.sleep(2) inside an async def FastAPI handler blocks the entire event loop thread for all concurrent users. Conversely, running unbounded asyncio.gather(*100_000_tasks) opens 100,000 sockets simultaneously, exhausting OS file descriptors (EMFILE) and crashing downstream services.

Request & State Flow

Why we need Asyncio (and how One Blocking Call Freezes FastAPI)

Producer ThreadBounded Queue /RingWorker PoolShared State1. Try non-blocking offer / CAS2. Dispatch to idle worker thread3. Execute without holding outerlocks4. Release permit / signalcompletion
Engineering Decision Framework
Problem
How to implement Python Asyncio: Event Loops, Coroutines, Tasks & Backpressure without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When naive scans degrade into quadratic bottlenecks, coroutines, Tasks & Backpressure, never call blocking I/O (requests.get, time.sleep) or heavy CPU loops directly on the event loop; offload blocking calls with asyncio.to_thread and bound fan-out with asyncio.Semaphore.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Python Asyncio: Event Loops, Coroutines, Tasks & Backpressure experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Keep References to `asyncio.create_task`

The event loop holds only a weak reference to fire-and-forget tasks; unreferenced tasks can be garbage-collected mid-flight.

Always Bound Fan-Out

Wrap outbound HTTP/DB calls in asyncio.Semaphore(N) or a bounded asyncio.Queue(maxsize=M) to enforce backpressure.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Asyncio excels (and where Threads/Processes win).

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where Asyncio excels (and where Threads/Processes win) as the intuition layer for Python Asyncio: Event Loops, Coroutines, Tasks & Backpressure: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Use asyncio for high-concurrency network I/O; use ProcessPoolExecutor or free-threaded Python 3.13t+ for CPU-bound work.

ChoiceWhat it buysWhat it costs
Good Candidate: API Gateways, LLM Streaming & Async ScrapersHandles 10,000+ concurrent sockets on a single process with kilobytes of RAM per task.Requires async-native drivers (`httpx`, `asyncpg`, `redis.asyncio`) end-to-end.
Avoid: CPU-Heavy Number Crunching on the LoopOffload to `ProcessPoolExecutor` or Python 3.13t free-threaded workers.Tight Python CPU loops never hit `await`, starving all network heartbeats.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How TaskGroup, Semaphores & `to_thread` are used.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Think of How TaskGroup, Semaphores & to_thread are used as the intuition layer for Python Asyncio: Event Loops, Coroutines, Tasks & Backpressure: Operational control: configure bounds, failure handling, and safe production defaults.

Use asyncio.TaskGroup for structured error handling, asyncio.Semaphore for bounded concurrency, asyncio.timeout() for deadlines, and asyncio.to_thread() for unavoidable synchronous libraries.

Design Trade-Off

How TaskGroup, Semaphores & `to_thread` are used

Before · Unbounded Pool + Nested Locks
  • AB-BA deadlock or OOM heap
  • Blocking I/O starves event loop
  • False sharing thrashes L1 cache
After · Bounded Permits + Lock-Free CAS
  • CallerRuns / shed at capacity
  • Padded cache lines prevent bouncing
  • Structured timeouts release leaks
import asyncio, httpx

async def fetch_all_bounded(urls: list[str], max_concurrency: int = 20) -> list[int]:
    sem = asyncio.Semaphore(max_concurrency)
    results: list[int] = []

    async def fetch_one(client: httpx.AsyncClient, url: str) -> None:
        async with sem:
            async with asyncio.timeout(5.0):
                resp = await client.get(url)
                results.append(resp.status_code)

    async with httpx.AsyncClient() as client:
        async with asyncio.TaskGroup() as tg:
            for u in urls:
                tg.create_task(fetch_one(client, u))
    return results
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: Asyncio vs. ThreadPool vs. ProcessPool / No-GIL.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: Asyncio vs. ThreadPool vs. ProcessPool / No-GIL as the intuition layer for Python Asyncio: Event Loops, Coroutines, Tasks & Backpressure: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Choose the concurrency primitive based on I/O vs. CPU dominance and library ecosystem.

ChoiceWhat it buysWhat it costs
asyncio Event LoopMinimal memory (~KB per coroutine) and zero GIL/lock contention for I/O.One accidental blocking call stalls all tasks on the loop.
ThreadPoolExecutor (`asyncio.to_thread`)Isolates blocking C extensions or sync SDKs (`boto3`) off the event loop.Higher OS thread stack memory and context-switching overhead.
ProcessPoolExecutor / Free-Threaded 3.13tTrue multi-core CPU parallelism across cores.IPC/pickle overhead (multiprocessing) or thread-safety discipline (3.13t).
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production example: Rate-Limited Async Scraper & LLM Proxy.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production example: Rate-Limited Async Scraper & LLM Proxy as the intuition layer for Python Asyncio: Event Loops, Coroutines, Tasks & Backpressure: Production architecture: see how the components compose end to end under real load.

A FastAPI LLM proxy uses uvicorn workers with asyncio.Semaphore(50) capping upstream GPU calls, a bounded asyncio.Queue(maxsize=200) for SSE token streaming, and loop.set_debug(True) / slow-callback logging (>100 ms) in staging to catch accidental sync calls.

Bounded Fan-Out

TaskGroup + Semaphore Backpressure Flow

TaskGroupSemaphore(20)httpx.AsyncClientUpstream API1. Spawn 500 tasks (480 wait)2. 20 acquire slot + 5s timeout3. Non-blocking await on epoll4. Release slot -> wake next task

Bounding fan-out with Semaphore(20) prevents EMFILE descriptor exhaustion and upstream overload.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved by Asyncio & Related Concurrency Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved by Asyncio & Related Concurrency Concepts as the intuition layer for Python Asyncio: Event Loops, Coroutines, Tasks & Backpressure: Applied problems: connect these internals to concrete system design and debugging scenarios.

Explore event-loop starvation prevention, async rate-limited scrapers, and Python no-GIL concurrency.

Component Topology

Problems solved by Asyncio & Related Concurrency Concepts

ProducersingressBounded QueuecomputeWorker PoolstorageShared Memorycontroloffer(task)dispatchCAS update
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

An `async def` FastAPI endpoint calls `requests.get()` and `time.sleep(2)`, causing all other concurrent requests to stall. What is the correct fix?

Recommended Learning Flow