Sub topic 12
Limiting Work in Flight
What this chapter assumes
You know what a queue is and how Little's law relates arrival rate, latency, and the number of items in a system. You can read short Python asyncio examples. You know what HTTP 503 and Retry-After mean. Earlier chapters covered bounded queues, back pressure, and load shedding. This chapter covers the third control: a cap on how many requests a service works on at the same time.
What "in flight" means
A request is in flight from the moment you start processing it until you send the response or give up. It occupies a worker, a connection, memory, and often a slot in a downstream service.
A bounded queue limits how much work is waiting. A concurrency limit limits how much work is running. They are different, and a service usually needs both:
- The queue absorbs short bursts so that workers stay busy.
- The in-flight limit stops the service from starting more work than its resources can handle.
Without an in-flight limit, a service that accepts every request starts them all. CPU, memory, database connections, and file descriptors are shared among all running requests, so each one slows down. Little's law says that when latency W rises and arrivals λ stay constant, the in-flight count L = λW rises too. That makes latency rise again. The service slows down until it fails.
A fixed in-flight limit
The simplest limiter is a counter. If the counter is at the limit, reject the request immediately. Otherwise increment it, do the work, and decrement it in a finally block.
import asyncio
from collections import Counter
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(80)))
print(Counter(status for status, _ in results))
asyncio.run(main())Running this prints Counter({200: 50, 503: 30}). All 80 requests arrive at once. The first 50 start working and the other 30 are rejected at once, so the rejected requests cost almost nothing.
This is safe in one asyncio event loop because nothing awaits between the check and the increment. Only one task runs at a time, so no other task can slip in between them. Threaded servers do not have this guarantee. With threads, the check and the increment must happen under a lock, or you must use a threading.BoundedSemaphore. Otherwise two threads can both see 49 and both proceed, which exceeds the limit.
Choosing the limit with Little's law
Apply L = λW to the healthy service. Suppose it handles 200 requests per second and the typical latency is 50 ms. The typical in-flight count is 200 × 0.05 = 10.
Do not set the limit to exactly 10. Traffic is bursty and latency varies, so a limit equal to the average would reject healthy traffic. A common starting point is 2 to 4 times the typical value, then adjust from load test results. Here that gives 20 to 40.
The limit also caps throughput when things go wrong. Maximum throughput is the limit divided by latency. With a limit of 50:
| Latency | Max throughput | What happens to extra load |
|---|---|---|
| 50 ms | 1000 req/s | Rejected only above 1000 req/s |
| 200 ms | 250 req/s | Rejected above 250 req/s |
| 1 s | 50 req/s | Most traffic is rejected, but accepted requests stay fast |
If the database slows down, the service does not pile up thousands of slow requests. It keeps serving 50 at a time and sheds the rest.
The right limit depends on the bottleneck. A CPU-bound service gains nothing from more in-flight requests than it has cores. An I/O-bound service can hold many more. A service limited by a database pool of 20 connections should usually have a limit near 20, plus some allowance for requests that do not use the database.
Waiting briefly instead of rejecting at once
Rejecting immediately is shedding. Waiting for a free slot is back pressure. A semaphore supports both, and a short wait with a timeout sits between them. A short wait smooths out tiny bursts where a slot frees up in a few milliseconds.
import asyncio
class Overloaded(Exception):
pass
class ConcurrencyLimiter:
def __init__(self, limit: int, max_wait: float = 0.05) -> None:
# max_wait must be greater than 0 (seconds)
self._sem = asyncio.Semaphore(limit)
self._max_wait = max_wait
async def run(self, func, *args):
try:
await asyncio.wait_for(self._sem.acquire(), timeout=self._max_wait)
except asyncio.TimeoutError:
raise Overloaded("no free slot") from None
try:
return await func(*args)
finally:
self._sem.release()
async def work(i):
await asyncio.sleep(0.2)
return i
async def main():
limiter = ConcurrencyLimiter(limit=2, max_wait=0.05)
results = await asyncio.gather(
*(limiter.run(work, i) for i in range(5)),
return_exceptions=True,
)
for r in results:
print("rejected" if isinstance(r, Overloaded) else f"ok {r}")
asyncio.run(main())Two requests get slots and three wait 50 ms, time out, and are rejected. Keep max_wait small. Every millisecond of waiting adds to the latency of the request, and waiting requests are still queued work. The wait should be well below your request deadline, or the request may expire before it starts.
Separate limits for separate resources
One global limit does not protect against a single slow dependency. If calls to a recommendation service hang, they can use up all 50 slots, and requests that never touch that service are rejected as well.
The fix is a bulkhead: a separate limit for each dependency or request class. Give the recommendation client its own ConcurrencyLimiter(limit=10). When it fills up, only recommendation calls are rejected. You can degrade that feature, for example by returning a default list, while the rest of the service keeps working.
Edge cases and common errors
- Leaked slots. If the decrement or
release()is not in afinallyblock, an exception or a cancellation leaves the slot used permanently. The limit then shrinks over time until the service rejects everything. This is the most common bug with this pattern. - Counting at the wrong layer. Count a request from the moment you accept it, not when a worker picks it up. Otherwise requests waiting for a worker are invisible to the limit.
- Per-instance limits. The limit applies to one process. With 10 instances and a limit of 50 each, the fleet allows 500 in flight. A shared downstream resource, such as a database, sees the total, so size per-instance limits from the downstream capacity divided by instance count.
- Autoscaling. A hard limit with fast autoscaling can hide problems. Alert on rejections instead of letting the service quietly add instances.
- Static limits go stale. A limit tuned for one hardware size, payload mix, or dependency speed becomes wrong when any of those change. Adaptive algorithms adjust the limit from observed latency, typically raising it slowly while latency is stable and cutting it sharply when latency grows (additive increase, multiplicative decrease). They work well but are harder to reason about. Start with a static limit and measure before adopting one.
- Long requests. Streaming or long-polling requests hold slots for a long time. Give them a separate pool so they do not starve short requests.
What the limit does and does not do
A concurrency limit keeps latency for accepted requests bounded, because the amount of simultaneous work is bounded. It does not decide which requests to reject. When the limit is hit, it rejects whoever arrives next, including high-priority traffic. Combine it with a priority policy, a reserved share of slots for critical requests, as covered in the chapter on shedding policies.
It also does not control the arrival rate. A token bucket limits how fast requests start. A concurrency limit limits how many are unfinished. A request that takes ten seconds counts against the concurrency limit for ten seconds, but only once against a rate limit. Use the one that matches the resource you are protecting.
Exercise
A service handles 400 requests per second with a typical latency of 25 ms. Using Little's law, what is the typical number of in-flight requests, and what range would you pick as a starting concurrency limit? What is the maximum throughput if latency rises to 500 ms with a limit of 30?
Show answer
Typical in-flight = 400 × 0.025 = 10. A starting limit of 2 to 4 times that is 20 to 40, which you then refine with load tests. With a limit of 30 and latency of 500 ms, maximum throughput = 30 / 0.5 = 60 requests per second. Requests above that rate are rejected instead of queuing.
Exercise
Why is the simple counter in handle safe in a single asyncio event loop but unsafe with a thread pool, and what would you change for threads?
Show answer
In asyncio, a task runs without interruption until it awaits. The check and the increment have no await between them, so no other task can run in between. Threads can be preempted between the check and the increment, so two threads can both pass the check and exceed the limit. Protect the check and increment with a lock, or use a semaphore such as threading.BoundedSemaphore with a non-blocking acquire.