Concurrency, Asyncio Event Loop, Multiprocessing & Free-Threaded Parallelism
- β Use asyncio for high-fanout network I/O (1,000+ concurrent LLM streams, HTTP requests, or WebSockets on a single OS thread with ~2 KiB overhead per Task).
- β Never call blocking synchronous code (time.sleep, requests.get, heavy CPU loops) directly inside an async def coroutineβit freezes the entire event loop! Offload blocking calls with await asyncio.to_thread(fn, *args).
- β Prefer Python 3.11+ asyncio.TaskGroup over asyncio.gather(): if any child task raises an exception, TaskGroup automatically cancels sibling tasks and raises a structured ExceptionGroup (handled via except*).
- β For CPU-bound workloads on GIL-enabled Python, use concurrent.futures.ProcessPoolExecutor (with multiprocessing.shared_memory for zero-copy buffers), or run on Python 3.13t/3.14t Free-Threaded builds (--disable-gil).
01. The Python Concurrency & Parallelism Decision Matrix
Choosing the wrong concurrency model in Python is one of the most common sources of production outages (such as running CPU-heavy PDF/JSON parsing on the asyncio event loop, or spawning 2,000 OS threads for HTTP polling). Use this decision matrix:
| Execution Model | Scheduling & Memory | Bypasses GIL? | Ideal Workload | Primary Hazard / Anti-Pattern |
|---|---|---|---|---|
| asyncio (Event Loop) | Cooperative single OS thread (~2 KiB per Task; 10,000+ tasks easily) |
No (Single thread) | High-fanout network I/O: LLM streaming, MCP servers, FastAPI, WebSockets | Calling blocking sync I/O or CPU loops stalls every concurrent request on the loop. |
| threading / ThreadPoolExecutor | Preemptive OS threads (~1β8 MiB stack per thread; 10β200 threads) | Only inside C extensions that release GIL (or 3.13t No-GIL) | Legacy sync DB drivers, blocking file I/O, NumPy/PyTorch C kernels releasing GIL | Race conditions on shared mutable state; GIL thrashing on pure-Python CPU code. |
| multiprocessing / ProcessPoolExecutor | Isolated OS processes (~30β80 MiB RSS per worker; N = CPU cores) | Yes (1 GIL per process) | Pure-Python CPU-bound data crunching, AST compilation, cryptographic hashing | pickle IPC serialization overheadβsolve with multiprocessing.shared_memory. |
PEP 703 Free-Threaded (python3.13t) |
Preemptive OS threads sharing one address space without a GIL | Yes (No GIL!) | Multi-core parallel Python threads sharing large in-memory graphs/models zero-copy | Requires thread-safe C extensions (PEP 703 Py_MOD_GIL_NOT_USED slot). |
02.
Inside the asyncio Event Loop, TaskGroup & ContextVar
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β ASYNCIO EVENT LOOP TICK (Single Thread: BaseEventLoop._run_once) β β β β 1. Poll Min-Heap of Scheduled Timers (_scheduled: call_later / asyncio.sleep) β β 2. Poll OS I/O Multiplexer (selectors.EpollSelector / KqueueSelector) β β βββ Moves ready socket Future callbacks into the FIFO _ready deque β β 3. Drain _ready Deque: Execute handle._run() βββΆ Task._step() β β βββ Resumes coroutine until next 'await' yields an incomplete Future β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π» Hands-On WebAssembly Python Labs (Module 9)
Click Run & Edit Live (Wasm) on any lab below to execute and modify the code in our browser Pyodide runtime.
Lab 9.1: Structured Concurrency with asyncio.TaskGroup, Semaphore Backpressure & ContextVars
Run a live asyncio pipeline in WebAssembly demonstrating bounded concurrency (Semaphore), task-isolated request tracing (ContextVar), and automatic TaskGroup orchestration.
import asyncio
from contextvars import ContextVar
import time
# Task-isolated context variable (safe across concurrent async tasks!)
request_trace_id: ContextVar[str] = ContextVar("request_trace_id", default="no-trace")
async def call_model_shard(shard_id: int, sem: asyncio.Semaphore) -> dict:
# Semaphore ensures at most 3 shards execute concurrently (backpressure)
async with sem:
trace = request_trace_id.get()
await asyncio.sleep(0.02) # Non-blocking event loop yield
return {"shard": shard_id, "trace": trace, "tokens": shard_id * 40}
async def handle_tenant_batch(tenant_trace: str, shard_ids: list[int]) -> list[dict]:
token = request_trace_id.set(tenant_trace)
sem = asyncio.Semaphore(3)
try:
# Python 3.11+ Structured Concurrency: TaskGroup awaits all or cancels all on error
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(call_model_shard(sid, sem)) for sid in shard_ids]
return [t.result() for t in tasks]
finally:
request_trace_id.reset(token)
async def main():
t0 = time.perf_counter()
# Run two tenant batches concurrently on the same event loop
batch_a, batch_b = await asyncio.gather(
handle_tenant_batch("trace-alpha-01", [1, 2, 3, 4]),
handle_tenant_batch("trace-beta-99", [5, 6]),
)
elapsed_ms = (time.perf_counter() - t0) * 1000
print(f"[1] Completed 6 concurrent async shard calls in {elapsed_ms:.1f} ms")
print(" Tenant A Results (Notice isolated ContextVar trace!):", batch_a[:2])
print(" Tenant B Results (Zero cross-task leakage!): ", batch_b)
await main()
Lab 9.2: Handling Concurrent Failures with ExceptionGroup (except*) & asyncio.timeout
Test Python 3.11+ except* (PEP 654) selective exception group handling and deadline enforcement with asyncio.timeout.
import asyncio
async def unreliable_tool(name: str, mode: str) -> str:
await asyncio.sleep(0.01)
if mode == "rate_limit":
raise ConnectionRefusedError(f"{name}: 429 Too Many Requests")
if mode == "bad_schema":
raise ValueError(f"{name}: Invalid JSON tool arguments")
return f"{name}: 200 OK"
async def run_resilient_fanout():
print("[1] Demonstrating Structured ExceptionGroup (except*) Handling:")
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(unreliable_tool("weather_api", "ok"))
tg.create_task(unreliable_tool("billing_api", "rate_limit"))
tg.create_task(unreliable_tool("sql_tool", "bad_schema"))
except* ConnectionRefusedError as conn_eg:
for err in conn_eg.exceptions:
print(f" [Retryable Network Sub-Group] -> {err}")
except* ValueError as val_eg:
for err in val_eg.exceptions:
print(f" [Schema Validation Sub-Group] -> {err}")
print("\n[2] Demonstrating Deterministic Deadline Enforcement (asyncio.timeout):")
try:
async with asyncio.timeout(0.02):
await asyncio.sleep(0.10) # Exceeds 20ms budget
except TimeoutError:
print(" [Deadline Guard] Task cleanly cancelled after exceeding 20ms SLA budget!")
await run_resilient_fanout()
Frequently Asked Staff Interview Questions (Module 9)
What happens under the hood when an async function executes await asyncio.sleep(1) or await socket.recv()? βΈ
The coroutine yields an incomplete asyncio.Future (or awaits a future-like object) up to its wrapping asyncio.Task. The Task registers a wakeup callback on that Future (future.add_done_callback(task._step)) and suspends. Control returns to the Event Loop, which polls the OS selector (epoll/kqueue) for ready sockets or expired timer heap entries, and calls task._step() to resume the coroutine at its exact suspension instruction.
Why is asyncio.TaskGroup safer than asyncio.gather() in production systems? βΈ
By default, if one coroutine in asyncio.gather(a(), b(), c()) raises an exception, gather() immediately propagates the error to the caller while leaving the remaining background tasks running as orphaned "zombie tasks" that continue consuming sockets or mutating state. asyncio.TaskGroup enforces structured concurrency: exiting the async with block is impossible until every spawned child task has either completed or been cancelled and awaited.
How do you prevent an asyncio service from OOMing or overwhelming downstream APIs when given 50,000 items? βΈ
Apply bounded backpressure using an asyncio.Semaphore(max_concurrency) (e.g., max 50 in-flight requests) or a fixed-worker pool pulling from a bounded asyncio.Queue(maxsize=200).