Learning center

A queue holds 1.2 million messages. Wait for it to drain, or scale?

Read the arrival rate and the completion rate separately. If completion is higher, the backlog drains in backlog ÷ (completion − arrival); if it is not, waiting never ends, and if a downstream limit holds completion down, more consumers will not raise it. The common shortcut, backlog ÷ completion rate, gives the wait a newly arrived message faces, not the time until the queue is empty.

The symptom and three explanations#

The example is fictional. The invoice-render queue feeds workers that render invoices and write them to a database. From 09:00 to 09:40 UTC the PDF library the workers call was slow, and the queue grew to 1.2 million messages. At 09:40 the library's owners reported it fixed, the six workers were running, and the oldest message was 40 minutes old. Customers wait for these invoices, so the on-call engineer has to decide whether to wait or to add workers, and three readings of the same backlog lead to different answers:

  • Already draining. The workers are back to full speed and complete more than producers send. Waiting works; the only question is how long.
  • Balanced. The workers are still slower than usual and complete about what producers send. The backlog will stay where it is.
  • Held by a downstream limit. The workers could go faster, but the database accepts only so many writes. Adding workers changes nothing, or adds load to the part that is already full.

The backlog count is the number on the alarm, and it is the same 1.2 million under all three.

The arithmetic#

Write λ for the arrival rate and μ for the completion rate, both in messages per second, and B for the backlog.

  • Drain time is B ÷ (μ − λ) when μ > λ. When μ ≤ λ it is undefined: the backlog never empties.
  • The wait a new message faces, with first-in-first-out delivery, is about B ÷ μ: everything ahead of it has to be completed first.
  • Little's law relates the averages of a queue in a steady state: the average number waiting equals the arrival rate times the average time each waits. A backlog that holds steady at B therefore delays every message by about B ÷ λ on average.

With B = 1.2 million, λ = 1,500 and μ = 1,800, the shortcut B ÷ μ gives 11 minutes and the drain time is 1.2 million ÷ 300, about 67 minutes. The difference is the arrivals that keep landing while the old messages are worked off. The AWS Builders' Library puts the same arithmetic in terms of an outage: a system that was down for an hour needs double its capacity for another hour to catch up. Avoiding insurmountable queue backlogs

The net rate μ − λ is often small next to either rate, which makes the projection fragile. At λ = 1,500 and μ = 1,600, an error of 1% in either rate moves the drain time by about 15%. Measure both rates over the same window, and recompute as they change.

What each explanation predicts#

ObservationAlready drainingBalancedHeld by a downstream limit
Backlogfallingflatfalling slowly or flat
Arrival ratenormalnormalnormal
Completion rateabove arrivalequal to arrivalat the downstream limit
Oldest message agefalling toward zeroflat, at about B ÷ λfalling slowly
Completion rate after adding consumersrisesrisesunchanged
Downstream utilizationbelow its limitbelow its limitat its limit

The backlog row cannot choose between draining and a downstream limit when both are falling, and it gives no time. The completion and arrival rates, read as two numbers, give the time. The response of completion to added consumers, or the downstream's utilization when you cannot experiment, decides whether scaling the consumers can help.

The lab: three queues with the same backlog#

The script starts each world with 1.2 million messages left by a 40-minute slowdown, and producers that keep sending about 1,500 messages a second. Each consumer completes 300 messages a second in recovered and capped and 250 in slow; in capped the database accepts at most 1,600 writes a second. It runs each world with 6 and with 12 consumers, prints the shortcut, the projection from the formula and the simulated drain time, and the age of the oldest message an hour later. It needs Python 3.8 or later.

import collections, random, sys

ARRIVE = 1500          # messages per second producers send, on average
PER_CONSUMER = {"recovered": 300, "slow": 250, "capped": 300}   # messages/s one consumer completes
CAP = {"recovered": 10**9, "slow": 10**9, "capped": 1600}       # what the downstream database accepts

def run(world, consumers, seed=5, horizon=6 * 3600):
    rng = random.Random(seed)
    queue = collections.deque((t, 500) for t in range(-2400, 0))   # 1.2M left by a 40-minute slowdown
    capacity = min(consumers * PER_CONSUMER[world], CAP[world])
    oldest_at_1h = None
    for now in range(horizon):
        a = max(0, round(rng.gauss(ARRIVE, 150)))
        queue.append((now, a))
        budget = capacity
        while budget and queue:
            t, n = queue[0]
            take = min(n, budget)
            budget -= take
            queue[0] = (t, n - take)
            if take == n:
                queue.popleft()
        left = sum(n for _, n in queue) if now % 60 == 0 or not queue else None
        if now == 3600:
            oldest_at_1h = now - queue[0][0] if queue else 0
        if left is not None and left < ARRIVE:          # back to about one second of work
            return capacity, f"{now / 60:.0f} min", oldest_at_1h
    return capacity, f"none in {horizon // 3600} h", oldest_at_1h

if len(sys.argv) < 2 or sys.argv[1] not in ("recovered", "slow", "capped"):
    sys.exit("usage: python3 drain.py recovered|slow|capped [seed]")
world, backlog = sys.argv[1], 1_200_000
seed = int(sys.argv[2]) if len(sys.argv) > 2 else 5
for consumers in (6, 12):
    capacity, outcome, oldest = run(world, consumers, seed)
    naive = backlog / capacity / 60
    net = capacity - ARRIVE
    proj = f"{backlog / net / 60:.0f} min" if net > 0 else "never"
    print(f"{world:9s} {consumers:2d} consumers, {capacity}/s: naive {naive:2.0f} min | "
          f"projected {proj} | simulated drain {outcome} | oldest at +1h "
          + (f"{oldest / 60:.0f} min" if oldest is not None else "-"))

Save it as drain.py. Before running it, write down for each world whether the shortcut or the projection will match the simulated drain time, and whether doubling the consumers will shorten it. Then run:

for world in recovered slow capped; do python3 drain.py "$world"; done

Python 3.11 printed:

recovered  6 consumers, 1800/s: naive 11 min | projected 67 min | simulated drain 66 min | oldest at +1h 1 min
recovered 12 consumers, 3600/s: naive  6 min | projected 10 min | simulated drain 10 min | oldest at +1h -
slow       6 consumers, 1500/s: naive 13 min | projected never | simulated drain none in 6 h | oldest at +1h 13 min
slow      12 consumers, 3000/s: naive  7 min | projected 13 min | simulated drain 13 min | oldest at +1h -
capped     6 consumers, 1600/s: naive 12 min | projected 200 min | simulated drain 197 min | oldest at +1h 9 min
capped    12 consumers, 1600/s: naive 12 min | projected 200 min | simulated drain 197 min | oldest at +1h 9 min

The shortcut was short by a factor of 6 in recovered, by 16 in capped, and by an infinite factor in slow, where the queue never drained. The projection from the separate rates matched the simulation to within 3 minutes. Doubling the consumers cut the drain from 66 to 10 minutes in recovered and turned slow from never into 13 minutes, and did nothing in capped. In slow the oldest message was still 13 minutes old an hour later: a flat backlog of 1.2 million with 1,500 arrivals a second, which is Little's law at work.

The prediction fails if the shortcut ever matches the simulation while arrivals continue, or if the capped world drains faster with 12 consumers. Run python3 drain.py capped 9 to try another seed: the simulated drain moves to 203 minutes while the projection stays at 200, which is the sensitivity to small rate changes described above.

Read it on a real system#

Each queue service reports arrivals and completions under its own names. For Amazon SQS, NumberOfMessagesSent counts messages added and NumberOfMessagesDeleted counts successful deletes; the backlog is ApproximateNumberOfMessagesVisible and the age of the oldest message is ApproximateAgeOfOldestMessage. Available CloudWatch metrics for Amazon SQS These reads change nothing:

for m in NumberOfMessagesSent NumberOfMessagesDeleted; do
  aws cloudwatch get-metric-statistics --namespace AWS/SQS --metric-name "$m" \
    --dimensions Name=QueueName,Value=invoice-render \
    --start-time 2026-11-24T09:25:00Z --end-time 2026-11-24T09:40:00Z \
    --period 300 --statistics Sum --output text
done

Divide each five-minute sum by 300 for a rate per second. get-metric-statistics The SQS guide reads the same metrics to tell a stalled consumer from a slow one. Read the queue without touching it For Kafka, two snapshots of the consumer group's offsets a few minutes apart give both rates per partition. Describe the group twice Pub/Sub reports the same two rates for a subscription under its own metric names. Read the subscription and its metrics

When producers and consumers export counters to Prometheus, the two rates and the projection are three queries. deriv fits a line to a gauge, so its negative is the net drain rate; the comparison drops the result when the backlog is not falling. Prometheus functions

sum(rate(invoice_render_published_total[10m]))
sum(rate(invoice_render_completed_total[10m]))
invoice_render_backlog / (-deriv(invoice_render_backlog[15m]) > 0) / 60

To find whether a downstream limit holds completion down, read the downstream's utilization against its limit, or add consumers and watch the completion rate. Adding consumers is a change to production, and it raises the load on whatever they call. The same Builders' Library article warns that the systems a consumer calls may not be ready for the extra processing as it works through a backlog. Avoiding insurmountable queue backlogs

Limits#

The projection assumes the rates hold. Arrivals usually follow the day, so a queue that drains at 09:40 can stop draining at the 11:00 peak. Project with the arrival rate expected for the next hours, such as the same hours last week, rather than the current one.

Completion counts can include repeats. SQS counts every successful delete, including deletes of the same message after it was received again, so NumberOfMessagesDeleted can be higher than the work done. Messages that fail and return to the queue are arrivals in effect, and messages that are received again and again stop counting toward the oldest-age metric until they are processed. SQS metrics

The backlog may not cost the same per message as new work. Messages from an outage can be retries, larger batches, or work for one tenant, and the completion rate measured on today's mix can overstate the rate on the backlog.

Waiting and scaling are not the only choices. When fresh messages matter more than old ones, sending new work to a separate queue lets it flow at normal latency while the backlog drains behind it; the Builders' Library describes customers preferring fresh data first in a backlog. Avoiding insurmountable queue backlogs The method behind all of this is in Choose the observation where explanations disagree.

Questions#

How do I calculate how long a queue backlog will take to drain?

Divide the backlog by the completion rate minus the arrival rate, with both rates measured over the same recent window. If the completion rate is not above the arrival rate, the backlog will not drain at the current rates.

Why is the oldest message age flat while the backlog stays high?

With first-in-first-out delivery and a steady backlog, each message waits about the same time: the backlog divided by the arrival rate. A flat age means the queue is in balance at a long wait. An age that grows by a minute every minute means the messages at the head are not being completed at all.

Will adding consumers make the backlog drain faster?

Only if consumers are the limit. If the completion rate does not rise when consumers are added, something downstream, such as a database or an API quota, sets the rate, and more consumers add load to it without draining the queue.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading