30/39
Part 5 of 6 · Queueing and overloadLearn and do

A backlog drains only with spare capacity

Shedding guards a server while the load is high. After an outage, the trouble is the work that piled up.

Jobs waiting after an outage
03060060180360minutesthousand jobs waiting
backlog

The backlog builds during the hour-long outage, then drains at the spare 200 a minute, for 5 more hours.

Queues absorb bursts, and that's also their trap. While a consumer is down, work keeps arriving. When it comes back, it can spend only its spare capacity on the backlog: the gap between what it can process and what keeps arriving.

drain time=backlogcapacity−arrival rate\text{drain time} = \frac{\text{backlog}}{\text{capacity} - \text{arrival rate}}

Say jobs arrive at 1,000 a minute, and workers can do 1,200 a minute, so they run 83% busy.

  • A 60-minute outage leaves 60 × 1,000 = 60,000 jobs waiting.
  • The spare capacity is 1,200 - 1,000 = 200 a minute.
  • So the drain takes 60,000 ÷ 200 = 300 minutes.

A one-hour outage becomes five hours of stale results. Double the workers during the recovery, and the spare becomes 2,400 - 1,000 = 1,400 a minute. Then the drain takes 60,000 ÷ 1,400 ≈ 43 minutes.

If capacity only equals the arrival rate, or falls below it, there is no spare. Then the backlog never drains.

Amazon's Builders' Library gives an example from a spike. One customer's traffic spikes with no throttle, and it takes about 30 minutes for an operator to step in. By then the queued messages are 10 times what the consumers were sized for, so working through them takes 300 minutes.

Amazon's conclusion: even short load spikes can mean recovery times, and outages, of several hours.

While the backlog drains, serve fresh work first.

The new job
first in, first outwaits behind every old job
last in, first outgoes next, and the old jobs drain behind it

On what to process first, Amazon notes that real-time systems are often built with queues that are roughly first in, first out. They prefer behavior closer to last in, first out: the backlog drains behind fresh work, or expired work gets dropped.

In the editor, write drain_minutes(outage, arrivals, capacity) from the drain formula: the minutes after recovery until the backlog is gone, or math.inf when there is no spare capacity.