Concurrency

5 concepts · 10 practice questions

Threads vs async I/O

A thread-per-request server parks a whole thread on every blocking call, and threads cost memory and scheduling. An async server runs an event loop that switches between tasks whenever one waits on I/O, so a single thread can hold thousands of open connections. The catch is that tasks yield only at await points: a blocking call or heavy CPU work inside a handler stalls every request on that loop. I/O-bound work suits async; CPU-bound work belongs in separate processes or workers.

import asyncio
import httpx

async def fetch_all(urls):
    async with httpx.AsyncClient(timeout=2.0) as client:
        # 100 requests wait on the network together, on one thread
        return await asyncio.gather(*(client.get(u) for u in urls))

async def handler(request):
    # Wrong: time.sleep(1) or a blocking DB driver here freezes every request
    await asyncio.sleep(1)             # right: yields to the event loop
    loop = asyncio.get_running_loop()
    # CPU-heavy work: hand it to a process pool, do not run it on the loop
    return await loop.run_in_executor(process_pool, resize, request.image)

Also covered

Race conditions and atomic operations
Optimistic vs pessimistic locking
Connection pools
Backpressure

Sign in to read the rest and take the 10-question test.

Sign in to continue