Sub topic 2
Queues and Little's law
This chapter assumes you can read short Python examples and know the difference between request rate and request latency. It also assumes you have a rough idea of how worker pools or async tasks handle requests. The previous chapter covered what overload is. This one gives you the arithmetic for reasoning about queues, which the later chapters on bounding, back pressure, and shedding depend on.
The queue model
Any service that accepts work faster than it can finish it at some instant needs somewhere to hold the extra work. That place is a queue. Queues are not always visible, and they take several forms:
- An
asyncio.Queueor a thread pool's task list. - The TCP accept backlog of a listening socket.
- Buffers in a load balancer or a message broker.
- Requests that have been accepted and are waiting on a database connection pool.
Each of these has the same structure, shown below. Work arrives at some rate, waits if all workers are busy, is processed, and leaves.
Three quantities describe this system:
| Symbol | Name | Unit | Example |
|---|---|---|---|
| λ (lambda) | Arrival rate, or throughput when stable | requests per second | 200 |
| W | Average time a request spends in the system, waiting plus being served | seconds | 0.25 |
| L | Average number of requests in the system | requests | 50 |
The boundary you draw is a choice. You can measure the whole service, only the queue, or only the workers. Little's law holds for any boundary as long as you use the same one for all three quantities.
Little's law
Little's law states:
L = λ × WThe average number of items in a system equals the average arrival rate multiplied by the average time each item spends there. It needs no assumption about arrival distribution, service time distribution, or scheduling order. It only requires that the system is stable over the measurement window. In a stable system, the rate at which work leaves equals the rate at which it arrives, so λ is also the throughput.
You can use the law in three directions.
- Estimate in-flight work. A service handles 200 requests per second, and the average request takes 0.25 seconds from arrival to response. Then L = 200 × 0.25 = 50 requests are in the system at any moment. That tells you how many connections, threads, or database handles you need, at minimum.
- Estimate latency from a queue length. Suppose you see an average of 400 requests in the system and a throughput of 200 per second. Then W = L / λ = 2 seconds. You can find out how slow users see the service by counting items, without timing each one.
- Size a buffer. To absorb a stall of a downstream dependency without losing work, multiply the arrival rate by the stall duration. A 5 second stall at 200 requests per second needs room for about 1000 queued requests. Whether you should provide that room is a separate question, covered in later chapters.
Here is a worked case. A worker pool has 20 workers. Each request takes 100 ms of work. The most the pool can finish is 20 / 0.1 = 200 requests per second. This follows from the same law, with L = 20 and W = 0.1 as the number of workers and the service time. If arrivals reach 200 per second, the workers are fully occupied, and any more arrivals must wait.
Checking the law with a simulation
The following program simulates a single worker with random arrivals and random service times. It measures L, λ, and W separately and prints them so you can compare L with λ × W.
import random
def simulate(arrival_rate: float, service_rate: float, n: int = 200_000, seed: int = 1):
rng = random.Random(seed)
t = 0.0 # arrival clock
server_free = 0.0 # time at which the worker becomes idle
total_time_in_system = 0.0
events = [] # (time, +1 on arrival, -1 on departure)
for _ in range(n):
t += rng.expovariate(arrival_rate)
start = max(t, server_free) # wait if the worker is still busy
done = start + rng.expovariate(service_rate)
server_free = done
total_time_in_system += done - t
events.append((t, 1))
events.append((done, -1))
events.sort()
first, last = events[0][0], events[-1][0]
area = 0.0 # integral of the number in system over time
count = 0
prev = first
for time_, delta in events:
area += count * (time_ - prev)
count += delta
prev = time_
horizon = last - first
L = area / horizon
lam = n / horizon
W = total_time_in_system / n
return L, lam, W
for arrival_rate in (50, 90, 95):
L, lam, W = simulate(arrival_rate, service_rate=100)
print(f"arrivals={arrival_rate:>3}/s L={L:6.2f} lambda*W={lam * W:6.2f} W={W * 1000:7.1f} ms")In every row, L and lambda*W agree. The simulation measures L from the count of requests over time, and W from per-request timings, so the match comes from the law and not from the code. The worker can serve 100 requests per second in all three runs, and only the arrival rate changes. Even though the arrival rate stays below capacity, W grows quickly as the arrival rate approaches 100.
Latency grows faster than load
For this model (random arrivals, random service times, one worker) there is a closed-form result: W = 1 / (μ − λ), where μ is the service rate. The table uses μ = 100 requests per second and a service time of 10 ms.
| Utilization (λ / μ) | Arrivals per second | W (average time in system) | L (average in system) |
|---|---|---|---|
| 50% | 50 | 20 ms | 1 |
| 80% | 80 | 50 ms | 4 |
| 90% | 90 | 100 ms | 9 |
| 95% | 95 | 200 ms | 19 |
| 99% | 99 | 1000 ms | 99 |
Going from 90% to 99% utilization is a 10% increase in load, and it multiplies latency by ten. This is why a service that looks healthy at 80% can fall over after a modest traffic increase. The exact numbers depend on how variable arrivals and service times are, and real traffic is usually burstier than this model. The shape of the curve, flat and then very steep, holds in practice.
Notice also that utilization measured as an average hides bursts. A service at 70% average utilization will still have moments when arrivals exceed capacity for a second or two, and it will build a queue during those moments.
What happens past capacity
When λ is larger than μ, the system has no stable state. The queue grows by roughly (λ − μ) requests every second, and W grows with it. If capacity is 100 requests per second and 120 arrive, the queue gains 20 requests per second. After a minute, there are 1200 waiting requests, and each new request waits about 12 seconds before a worker sees it.
Two details are worth knowing about this regime.
- Throughput does not rise. The workers are already saturated, so extra arrivals only lengthen the queue. Throughput stays at μ, or can even drop if the extra work causes contention or memory pressure.
- Little's law still holds for the requests that complete. If clients give up after a timeout, the work they abandoned still counts in L while it sits in the queue, and it adds to W if the server eventually processes it. The next chapter looks at why this wasted work matters.
Practical gotchas
- Averages hide tails. Little's law is about means. A mean W of 100 ms can coexist with a 99th percentile of 2 seconds. Use the law to reason about size and trends, and use percentile metrics to judge user experience.
- Mixing boundaries gives wrong answers. If you take λ at the load balancer and W from a single worker's service time, you are comparing different systems. Use the same boundary for all three values.
- Retries change λ. If clients retry on failure, the arrival rate seen by the server is higher than the rate of original user actions. Later chapters on client signals and retries return to this.
- Concurrency is a consequence. You cannot just set the thread count to match L and expect the arithmetic to hold. If the service is slow, W grows, so L grows, and then you need more concurrency, which can make the service slower still.
Where this leads
Little's law links three numbers you can measure. If W is held roughly constant, the queue length L is determined by the arrival rate. If L is limited, W is limited too. That second point is the idea behind the rest of this tutorial: you can control latency by controlling how much work you allow into the system, which is what bounded queues, back pressure, and load shedding do.
Exercise
A service receives 300 requests per second. It has an average latency of 120 ms. (a) How many requests are in flight on average? (b) During an incident, the in-flight gauge reads 900 while throughput stays at 300 requests per second. What is the average latency now?
Show answer
(a) L = λ × W = 300 × 0.12 = 36 requests in flight. (b) W = L / λ = 900 / 300 = 3 seconds. The queue holds many more requests than usual, and each one spends 3 seconds in the system.
Exercise
A worker pool has 40 workers, and each request needs 200 ms of work. (a) What is the maximum throughput of the pool? (b) If 250 requests per second arrive, how fast does the queue grow, and how long is the wait for a request that arrives after one minute?
Show answer
(a) Capacity is 40 / 0.2 = 200 requests per second. (b) The queue grows by 250 − 200 = 50 requests per second. After 60 seconds it holds about 3000 requests. A new request must wait for those to be served at 200 per second, so it waits about 3000 / 200 = 15 seconds before a worker starts it, plus 0.2 seconds of service.