Lesson 4 of 9 · 23m
Backpressure: Semaphores, Queues, and Saying No
Why unbounded concurrency collapses services, how semaphores and queues shape load, and how to expose overload instead of hiding it until the process dies.
Most async services do not fall over because async is slow. They fall over because concurrency is effectively infinite. A traffic spike creates ten thousand tasks, each holding memory and waiting on sockets. The database pool saturates, latency rises, retries multiply the load, and the process becomes a distributed denial-of-service attack against its own dependencies.
The core production skill is backpressure: deliberately limiting how much work enters the system and what happens when capacity is full.
A semaphore bounds simultaneous work
fetch_sem = asyncio.Semaphore(50)
async def bounded_fetch(client, url):
async with fetch_sem:
return await client.get(url)This allows at most fifty outbound HTTP requests at once. The rest wait at the semaphore. That waiting is the point: work is visible and ordered rather than all hammering the dependency simultaneously.
Choose limits from the scarce resource, not vibes. If the downstream can handle 200 requests per second and each request lasts about 100ms, roughly 20 concurrent requests keep it busy. Add headroom and measure.
A queue turns bursts into shaped work
queue = asyncio.Queue(maxsize=1_000)
async def producer(item):
await queue.put(item) # suspends when full
async def worker():
while True:
item = await queue.get()
try:
await process(item)
finally:
queue.task_done()maxsize is the load-shedding boundary. put() suspends producers when the queue is full, which slows upstream work naturally. For user-facing APIs, sometimes put_nowait() plus a 503 is better than unbounded waiting. Either behavior is acceptable; pretending capacity is infinite is not.
Know the difference between timeout, concurrency, and rate
These controls solve different problems:
async with asyncio.timeout(2): # how long one operation may take
async with semaphore: # how many operations may overlap
await client.get(url) # client may also rate-limit per secondRate limiting controls work per time period. Concurrency controls overlap. Timeouts control tail latency. Real systems usually need all three, especially when calling third-party APIs.
Unbounded gather is a footgun
await asyncio.gather(*(fetch(u) for u in urls)) # every URL at onceThis is fine for five URLs and catastrophic for fifty thousand. Batch or use a worker-pool pattern:
async def pump(urls):
queue = asyncio.Queue(maxsize=200)
for url in urls:
await queue.put(url)The shape matters more than the exact helper. You need a finite number of workers and a bounded buffer.
Shed load deliberately
When overloaded, the best response is often fast failure: HTTP 503 with Retry-After, a dropped low-priority metric, or a queue-full metric and alert. Slow failure is worse because every waiting request consumes memory and keeps clients retrying.
Field notes
asyncio.Queueis not thread-safe; usequeue.Queueor a broker boundary when communicating with threads.- Always pair
queue.get()withqueue.task_done()if anything callsqueue.join(). - Measure queue depth, oldest-item age, active workers, and rejection count. Raw throughput alone hides overload.
- Client-side deadlines should be shorter than server-side work deadlines, or retries can stack behind useless work.
Was this lesson helpful?