Sub topic 3
Why Unbounded Queues Make Things Worse
This chapter assumes you can read short Python examples and know what request latency and HTTP status codes are. It also assumes you have a basic idea of worker pools or async tasks. It builds on Little's law from the previous chapter: the average number of items in a system equals the arrival rate times the average time each item spends there.
The tempting default
When a service receives work faster than it can finish it, the easiest fix is a queue with no size limit. Python's queue.Queue() and asyncio.Queue() both default to unbounded. Many job libraries and thread pool executors do the same. The reasoning sounds sensible: nothing is dropped, and a burst gets absorbed.
That reasoning holds only when the overload is short. A queue smooths a burst that ends. It does nothing when the arrival rate stays above the service rate. In that case the queue grows for as long as the overload lasts, and every item added makes the wait longer for the items behind it.
What happens during sustained overload
Suppose a service has a single worker that handles 100 requests per second. Clients send 120 per second.
- The queue grows by 20 items every second.
- After 10 seconds, 200 items are waiting.
- A request that arrives then waits behind 200 others, about 2 seconds at 100 per second, before work on it starts.
- After 60 seconds, 1,200 items are waiting, and the wait is about 12 seconds.
Little's law gives the same picture. The number of items in the system is L = λ × W. If L keeps rising while λ stays fixed, then the time in the system W must rise too. The queue never reaches a steady state, because a steady state needs the service rate to be at least the arrival rate.
Failure mode 1: latency grows without bound
The first symptom is latency. Every request still succeeds in principle, but each one waits behind everything that came before it. Because the queue is first in, first out (FIFO), the newest request always waits the longest.
Average latency can look acceptable on a dashboard while the tail is already bad. Watch the 99th percentile and the age of the oldest queued item. Chapter material on observability covers these later.
Failure mode 2: work nobody is waiting for
A client usually has a timeout. If the client waits 5 seconds and the queue wait is 12 seconds, the client gives up at second 5. The request is still in the queue. The server does not know the client left, so it eventually picks the request up and does the full work. It then writes a response to a closed connection.
This is wasted work. Once queue wait exceeds the typical client timeout, most of what the server completes is useless. The server is busy at 100% capacity and delivers almost no value. The next chapters on deadlines show how to avoid this.
Failure mode 3: memory exhaustion
Each queued item takes memory. It holds the request body, headers, a connection object, and often a callback or coroutine. A small item of 5 KB, at 20 extra items per second, adds about 100 KB per second. That is slow. A service that queues 50 KB payloads under 2,000 extra arrivals per second adds 100 MB per second, so a 4 GB container is full in about 40 seconds.
When memory runs out, one of two things happens:
- The operating system's out-of-memory (OOM) killer ends the process. All queued work is lost, along with all in-flight work.
- The runtime spends most of its time in garbage collection or swapping, and throughput drops further. This makes the overload worse.
Either way, the system fails abruptly after a long period of looking merely slow.
Failure mode 4: retry amplification
Clients that time out often retry. Each retry is a new arrival, and the original request may still be sitting in the queue. Now the queue holds the original and the retry. The arrival rate rises exactly when the service is already behind.
This feedback loop can keep a service down after the original cause is gone. If a traffic spike ends but the queue holds 10 minutes of stale work and clients keep retrying, the service may never catch up. This pattern is often called a metastable failure: the system stays in a bad state even after the trigger is removed. Chapter on retries covers the fix in detail.
Failure mode 5: slow recovery
Even without retries, a long queue takes time to drain. The drain rate is the service rate minus the arrival rate. If the service handles 100 per second and arrivals fall back to 90 per second, the drain rate is only 10 per second. A queue of 1,200 items takes 120 seconds to clear. Users keep seeing high latency for two minutes after the load has returned to normal.
Seeing it happen
The following program simulates the example above. It uses a single worker that takes 10 ms per item and a producer that sends 120 items per second for 5 seconds. It reports how long each item waited in the queue.
import asyncio
import time
async def producer(queue: asyncio.Queue, rate: float, seconds: float) -> None:
interval = 1.0 / rate
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
queue.put_nowait(time.monotonic()) # never blocks: queue is unbounded
await asyncio.sleep(interval)
queue.put_nowait(None) # sentinel: no more work
async def consumer(queue: asyncio.Queue) -> list[float]:
waits = []
while True:
enqueued_at = await queue.get()
if enqueued_at is None:
return waits
waits.append(time.monotonic() - enqueued_at)
await asyncio.sleep(0.01) # 10 ms of work: capacity is 100 per second
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue() # no maxsize: unbounded
_, waits = await asyncio.gather(producer(queue, 120, 5), consumer(queue))
for i in (0, len(waits) // 2, len(waits) - 1):
print(f"item {i}: waited {waits[i]:.2f}s")
asyncio.run(main())The first item waits close to zero. Items in the middle and at the end wait noticeably longer, and the wait keeps rising with the position in the queue. Exact numbers depend on your machine, because asyncio.sleep is not a precise timer, but the upward trend is the point.
Why a bigger machine does not fix it
Adding capacity moves the point where overload starts, but it does not remove it. Any finite system has a service rate. A queue with no limit has no mechanism that responds when arrivals exceed that rate. It converts the excess into delay and memory. The only way out is to make the system say no, or ask the producer to slow down. That requires a limit, which the next chapter introduces.
Summary of failure modes
| Failure mode | What you observe | Root cause |
|---|---|---|
| Growing latency | Rising p99 and queue age | Wait time grows with queue length |
| Wasted work | High CPU, few useful responses | Clients timed out before the server started |
| Memory exhaustion | Rising memory, then OOM kill | Each queued item uses memory |
| Retry amplification | Arrival rate rises during an incident | Timeouts trigger retries of queued work |
| Slow recovery | Latency stays high after load drops | Drain rate is only the spare capacity |
Exercise
A service handles 200 requests per second. Traffic rises to 260 requests per second for 30 seconds, then returns to 150 per second. Assume an unbounded FIFO queue and no retries. How many items are queued when the spike ends, how long does a request arriving at that moment wait, and how long does the queue take to drain?
Show answer
The queue grows by 260 - 200 = 60 items per second, so after 30 seconds it holds 1,800 items. A request arriving then waits about 1,800 / 200 = 9 seconds. After the spike, the drain rate is 200 - 150 = 50 items per second, so draining 1,800 items takes 1,800 / 50 = 36 seconds. Latency stays elevated for about 36 seconds after the spike has ended.
Exercise
In the simulation program, every request has a client timeout of 2 seconds. Using the 120-per-second arrival rate and 100-per-second service rate, after roughly how many seconds of overload does the queue wait first exceed the timeout, and why does this mean most later work is wasted?
Show answer
The queue grows by 20 items per second and each item takes 10 ms to serve. Wait is queue length times 0.01 s, so a 2 second wait needs 200 items, which is reached after 200 / 20 = 10 seconds. After that point every new request waits longer than its client will, so the client has already given up when the worker reaches the item. The worker still does the full work, which produces no useful response.