Sub topic 12
Limiting work in flight
This chapter assumes you can read short Python examples, know HTTP status codes, and have met Little's law and bounded queues in earlier chapters.
Why cap work in flight
Work in flight is the set of requests a service has accepted but not yet finished. Each one holds memory, a connection, and a share of CPU or a downstream call. A bounded queue limits the work that is waiting. A concurrency limit caps the work that is running or waiting together. It is the simplest form of admission control.
Without a cap, a slow dependency makes requests pile up inside the service. Latency rises, memory grows, and every request slows down together.
Choosing the number with Little's law
Little's law says in-flight work equals arrival rate times time in the system:
in_flight = rate x latencySuppose a service handles 200 requests per second and each takes 0.25 seconds. That gives 200 x 0.25 = 50 requests in flight. If latency doubles to 0.5 seconds while the rate stays at 200, 100 requests would be in flight. A cap of 50 stops that growth. The service refuses the excess instead of letting every request get slower.
Start from measured peak in-flight work under healthy load. Add some headroom for bursts, and stay below the point where the CPU, a connection pool, or a database starts to saturate.
A fixed limit in asyncio
The handler below counts requests in flight. When the count reaches the limit, it rejects the request at once with a 503 and a Retry-After hint.
import asyncio
MAX_IN_FLIGHT = 50
in_flight = 0
async def handle(request, process):
global in_flight
if in_flight >= MAX_IN_FLIGHT:
return 503, {"Retry-After": "1"}
in_flight += 1
try:
return 200, await process(request)
finally:
in_flight -= 1
async def process(request):
await asyncio.sleep(0.1) # simulate work
return f"done {request}"
async def main():
results = await asyncio.gather(*(handle(i, process) for i in range(60)))
statuses = [r[0] for r in results]
print("accepted:", statuses.count(200), "rejected:", statuses.count(503))
asyncio.run(main())This prints accepted: 50 rejected: 10. The check and the increment are safe in one event loop because no await sits between them. With threads, the same code needs a lock or an atomic counter.
Rejecting or waiting
A limit can respond to a full house in two ways.
| Behavior | Tool | Effect |
|---|---|---|
| Wait for a slot | `asyncio.Semaphore` with `async with` | Back pressure. Callers slow down, but waiting requests still use memory and time. |
| Reject at once | Counter check, as above | Load shedding. Callers get a fast answer and can retry elsewhere. |
If you wait, bound the wait with a timeout. Otherwise the semaphore becomes an unbounded queue again.
Common errors
- Limit too high. The service saturates before the cap triggers, so the cap protects nothing.
- Limit too low. The service rejects work it could have handled. Check rejection counts against CPU use.
- Forgetting
finally. If the decrement is skipped on an exception, slots leak until the service rejects everything. - One global limit for mixed work. A slow endpoint can use every slot. Give expensive routes their own limits.
- A static limit under changing conditions. Healthy capacity changes with deployments and dependencies. Adaptive schemes raise the limit while latency is stable and lower it when latency rises.
Exercise
A service handles 120 requests per second at a normal latency of 0.5 seconds. Its dependency slows down and latency rises to 2 seconds. How many requests are in flight at the new latency if nothing is rejected, and what does a limit of 80 do?
Show answer
In flight = 120 x 2 = 240 requests, three times the healthy level of 60. A limit of 80 admits at most 80 at once, so the service rejects the excess with 503 and keeps memory and queueing delay bounded for the requests it accepts.