Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

System Design (High-Level Design)  Module 3 – Performance and reliability fundamentals

Load shedding, backpressure and degradation

Reject excess work early and by priority, bound every queue and tell senders to slow down, and degrade features so goodput holds under overload.

  • Advanced
  • 25 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Explain why goodput collapses when a server accepts more work than it can finish in time
  • Design admission control that rejects excess work early, cheaply, by priority and by deadline
  • Use bounded queues and explicit signals such as 429, 503 and Retry-After to apply backpressure
  • Plan graceful degradation that drops optional features before the journeys users pay for

Before you start

What you’ll learn · Before you start

What you will learn

  • Explain why goodput collapses when a server accepts more work than it can finish in time
  • Design admission control that rejects excess work early, cheaply, by priority and by deadline
  • Use bounded queues and explicit signals such as 429, 503 and Retry-After to apply backpressure
  • Plan graceful degradation that drops optional features before the journeys users pay for

Before you start

On this page

When more work arrives than a service can finish, say 1,500 requests a second for a server that finishes 1,000, something has to give, and these three techniques decide what. load shedding: Refusing excess work quickly and cheaply when a server nears its capacity, ideally the least important work first, so that the requests it does accept are still answered in time. rejects the excess quickly and cheaply, so that the requests the service does accept are still answered in time. backpressure: Sending an overload back to where the work comes from: a full queue tells its producer to wait, or a server answers 429 or 503 with Retry-After, instead of letting work pile up. sends the problem back to where the work comes from: queues have limits, and a full queue tells its producer to slow down instead of growing until memory runs out. graceful degradation: Making requests cheaper under load by dropping optional features and serving cached, stale or partial answers in a planned order, so that the journeys users depend on keep working. makes each request cheaper by dropping optional features and serving cached or partial answers, so that the important journeys keep working. All three rest on one fact that surprises many engineers: a server that accepts everything during an overload ends up serving almost nobody, because every request waits behind the others until it is too late to matter.

The sections below show that collapse with numbers, then shed by priority and by deadline, bound the queues, and order features for degradation.

Accepting everything serves almost no one

Throughput counts every request a server handles. goodput: The requests a server answers without an error and soon enough for the caller to use the answer. Throughput counts all of its work; an overloaded server can stay busy and still have almost no goodput. counts only the useful ones: answers without an error that arrive soon enough for the caller to use them (Builders’ Library). The difference is all that matters during an overload. Suppose a server can finish 1,000 requests a second and is offered 1,500: its queue grows by 500 requests every second. By Little’s law, a new request then waits the queue length divided by the rate at which the server works through it: after two seconds, 1,000 requests stand ahead of it, one second of waiting, and a client that gives up after one second never sees its answer. The server stays fully busy, but from then on it works only for callers who have left.

The simulation offers 1,500 requests a second for a minute to a server with 50 workers and calls of 50 ms on average, which finishes about 1,000 a second. Its clients give up after 1 second. Requests are checkout (15 %), browsing (55 %) and prefetching (30 %), and the same seeded traffic meets four policies.

150 % load, four ways to handle it Python · overload-sim/overload_sim.py
# A server with 50 workers and calls of 50 ms on average can finish about 1,000 requests a second. For 60 seconds it is
# offered 1,500 a second, 150 % of what it can do. Clients give up after 1 second, so an answer that comes later is
# wasted work. Four ways to handle the excess, the same seeded traffic for each.
import heapq
import random
from collections import deque

WORKERS, SERVICE_MS = 50, 50.0
RATE_PER_MS, SECONDS, DEADLINE_MS = 1.5, 60, 1_000
CLASSES = [("checkout", 0.15), ("browse", 0.55), ("prefetch", 0.30)]  # share of the requests, most important first
# Priority admission: a request may join the queue only while fewer than this many requests are waiting.
PRIORITY_LIMIT = {"checkout": 300, "browse": 150, "prefetch": 20}


def traffic(seed=3):
    rng = random.Random(seed)
    t, out = 0.0, []
    while True:
        t += rng.expovariate(RATE_PER_MS)
        if t >= SECONDS * 1_000:
            return out
        kind = rng.choices([name for name, _ in CLASSES], weights=[share for _, share in CLASSES])[0]
        out.append((t, kind, rng.expovariate(1 / SERVICE_MS)))


def simulate(policy):
    queues = {name: deque() for name, _ in CLASSES}
    busy_until = []  # heap of times when each busy worker becomes free
    free = WORKERS
    good = {name: 0 for name, _ in CLASSES}
    total = {name: 0 for name, _ in CLASSES}
    latencies = []

    def waiting():
        return sum(len(q) for q in queues.values())

    def next_request(now):
        order = [name for name, _ in CLASSES] if policy == "priority" else None
        while True:
            if order:
                q = next((queues[name] for name in order if queues[name]), None)
            else:  # one FIFO queue: take the oldest request of any class
                q = min((q for q in queues.values() if q), key=lambda q: q[0][0], default=None)
            if q is None:
                return None
            req = q.popleft()
            if policy == "accept all" or DEADLINE_MS - (now - req[0]) > SERVICE_MS:
                return req
            # Too little time left for an average call: drop it rather than work for nobody.

    def start_work(now):
        nonlocal free
        while free:
            req = next_request(now)
            if req is None:
                return
            arrived, kind, work = req
            finish = now + work
            free -= 1
            heapq.heappush(busy_until, finish)
            if finish - arrived <= DEADLINE_MS:
                good[kind] += 1
                latencies.append(finish - arrived)

    for arrived, kind, work in traffic():
        while busy_until and busy_until[0] <= arrived:
            now = heapq.heappop(busy_until)
            free += 1
            start_work(now)
        total[kind] += 1
        if policy == "queue limit 100" and waiting() >= 100:
            continue  # rejected at once with a 503: costs almost nothing
        if policy == "priority" and waiting() >= PRIORITY_LIMIT[kind]:
            continue
        queues[kind].append((arrived, kind, work))
        start_work(arrived)
    latencies.sort()
    p99 = latencies[int(len(latencies) * 0.99)] if latencies else float("nan")
    return sum(good.values()) / SECONDS, p99, {name: good[name] / total[name] for name in good}


print("Offered 1,500 requests a second for 60 s to a server that finishes about 1,000 a second")
print(f"{'policy':<26}{'goodput/s':>10}{'p99 of good':>13}{'checkout':>10}{'browse':>8}{'prefetch':>10}")
for label, policy in [
    ("accept everything", "accept all"),
    ("drop doomed work", "drop expired"),
    ("queue limit of 100", "queue limit 100"),
    ("priority admission", "priority"),
]:
    goodput, p99, ok = simulate(policy)
    print(f"{label:<26}{goodput:>10,.0f}{p99:>10,.0f} ms{ok['checkout']:>10.1%}{ok['browse']:>8.1%}{ok['prefetch']:>10.1%}")

Output

Offered 1,500 requests a second for 60 s to a server that finishes about 1,000 a second
policy                     goodput/s  p99 of good  checkout  browse  prefetch
accept everything                 53       985 ms      3.5%    3.6%      3.6%
drop doomed work                 668       999 ms     45.4%   45.0%     44.8%
queue limit of 100             1,004       329 ms     67.4%   67.7%     67.7%
priority admission             1,007       356 ms    100.0%   95.9%      0.3%

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 overload_sim.py

Accepting everything yields a goodput of 53 requests a second, about 5 % of what the server can do: after the first seconds, every answer comes too late. Dropping doomed work, requests with too little time left to finish, helps (668 a second), but the queue still grows, so every request that is served waits nearly the whole second; the p99 is 999 ms. A queue limit of 100 restores full goodput, 1,004 a second with a p99 of 329 ms, by refusing a third of the requests at once. It refuses them blindly, though: checkout loses as much as prefetching. Priority admission gives each kind of request a different share of the queue, 300 places for checkout, 150 for browsing and 20 for prefetching, and its workers take the most important waiting request first; the server then serves every checkout, 95.9 % of browsing and almost no prefetching. Same server, same traffic; only the policy changed.

The simplest model of a queue shows why waiting explodes near capacity. It has a single server that finishes 100 requests a second, the lesson’s server at a tenth of its size, and it starts at 150 arrivals a second, the same 150 %. Drag the arrivals down to 99, then to 95 and 90, and read the mean time a request spends in the system:

Interactive · change it and see How waiting grows as arrivals near what one server finishes Requests arrive at random at an average rate and one server handles them one at a time. Raise the arrival rate towards the service rate and watch the time in the system.
Mean time in the system by utilisation: mean time in the system (ms) against utilisation ρ = λ/μ (%).0204060801000200400600utilisation ρ = λ/μ (%)mean time in the system (ms)time in systemservice alone 10 msnow 150 %

Requests arrive at 150 a second but are served at only 100: the queue grows without limit and waiting times with it.

Mean time in the system (W) grows without limit
Utilisation (ρ) 150 %
Mean wait before service —
Mean number in the system (L = λW) —
The numbers as a table
Mean time in the system with μ = 100 a second
UtilisationMean time in the system
50 %20 ms
70 %33.3 ms
80 %50 ms
90 %100 ms
95 %200 ms
99 %1,000 ms

At 150 the queue grows without limit. At 99, 99 % of capacity, a request spends 1,000 ms on average, as long as the clients’ whole timeout; at 95 it spends 200 ms and at 90 it spends 100 ms. Below capacity a queue drains; above it, the waiting grows until every answer is too late.

Key idea

Goodput, not throughput, is what an overloaded server must protect: work accepted beyond capacity only waits until its callers have gone.

Checkpoint

Check: Goodput under overload

  1. Question 1 of 2 A server finishes 1,000 requests a second and is offered 1,500 a second, and it queues everything. How many seconds of waiting does a new request face after 10 seconds?

    Type a number.

    A hint

    The queue grows by the difference every second, and the server works through it at 1,000 a second.

    Show the answer: Question 1 of 2

    Answer: 5 seconds (anything from 4.8 to 5.2 counts)

    The queue grows by 500 requests a second, so after 10 seconds 5,000 are waiting. At 1,000 a second the server needs 5 seconds to reach a new request, far past a typical 1-second client timeout, which is why goodput collapses when nothing is shed.

  2. Question 2 of 2 What does goodput count?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Requests answered without an error and soon enough for the caller to use the answer

    Throughput counts everything the server does. Goodput counts only the useful part: answers that are correct and arrive before the caller gives up. An overloaded server can be busy all the time and still have almost no goodput.

Shed early, cheaply and by priority

A rejected request still costs something: reading it, deciding, answering. If that cost is close to the cost of serving it, the server is overloaded by its refusals alone. Google’s SRE book warns that a backend can end up spending most of its processor time just rejecting requests (SRE book, chapter 21), and the Azure throttling pattern says to make a rejection cheaper than the work it prevents, by rejecting as early in the pipeline as possible (Azure throttling pattern). So every layer can refuse work, and the earlier one is the cheaper:

Requests pass clients, a load balancer, admission control and a bounded queue; excess is refused with 429 or 503 and Retry-After.Clientsback off, keep a retry budget,throttle themselvesLoad balancerconnection limits; rejectsexcess instead of queueing itServer: admission controlby priority and by deadlineBounded queuefull means reject or waitWorkersa fixed number at a timerequestsrequests within the limitsadmitted worknext item429 or 503 with Retry-After

Every layer can refuse work, and earlier is cheaper

Text description of the diagram

The diagram shows the path of a request from top to bottom, and what each layer does when there is too much work.

  1. Clients send requests. They back off, keep a retry budget and throttle themselves when they are refused.
  2. The load balancer passes on requests within its connection limits and rejects the excess instead of queueing it.
  3. The server's admission control decides, by priority and by the request's deadline, which requests to accept.
  4. Accepted work waits in a bounded queue; when the queue is full, a new item is rejected or its sender waits.
  5. Workers take the next item from the queue, a fixed number at a time.

A dashed arrow goes from admission control back to the clients: refused requests get a 429 or 503 response with a Retry-After header, which tells the clients to slow down.

  • Clients can refuse their own requests. In the SRE book’s adaptive throttling, each client counts its requests and the backend’s accepts over the last two minutes, and once requests exceed K times the accepts it starts failing new requests locally, with a probability that grows with the gap. The book prefers K = 2.
P(reject locally)=max⁡(0, requests−K×acceptsrequests+1)P(\text{reject locally}) = \max\left(0,\ \frac{\text{requests} - K \times \text{accepts}}{\text{requests} + 1}\right)
  • Load balancers and proxies should reject the excess rather than queue it. A queue in a load balancer hides how long a request has already waited; the Builders’ Library calls a configuration that fails fast instead of queueing a safe default.
  • Servers run admission control: A limit on the work a server has in progress, checked before any expensive work starts, that decides by priority and by deadline which new requests may join the queue.: a limit on work in progress, checked before any expensive work starts.

Which requests to refuse is a business decision written into code. The SRE book gives every request a criticality, from the most critical down to work that may be shed freely, and a backend under load rejects lower criticalities first. The Builders’ Library adds three priorities that are easy to miss. Health checks from the load balancer come first, because a server that misses them is taken out of service and its load lands on the others. Work that has already started comes before new work, because failing step 9 of 10 wastes the first eight. And requests whose deadline has passed, or will pass before the work could finish, are dropped rather than served late.

Queues need the same attention to time. Measure how long items have waited, not only how many there are: CoDel, an algorithm for network queues described in RFC 8289, starts dropping when the time packets spend in a queue stays above a target of 5 ms for an interval of 100 ms (RFC 8289). A request queue can apply the same idea with its own target. Fixed limits also go stale as fleets grow or shrink, so some services adapt them. Netflix’s concurrency-limits library treats a service’s limit like a TCP congestion window, starts from Little’s law (the limit is the request rate times the latency) and adjusts it as latency changes, rejecting what is over the limit with HTTP 429 or gRPC’s UNAVAILABLE (concurrency-limits). Whatever sets the limit, keep the latency of refused requests out of the latency graphs, and alarm on how many are refused; a tiny rejection time mixed into the average can make an overloaded service look fast.

Step through the priority admission of the simulation, for three requests that arrive while 120 wait:

Interactive · stage by stage Three requests at a server offered 150 % of its capacity Step through a checkout, a page view and a prefetch arriving while 120 requests wait, and one request whose client has given up.
Three requests at a server offered 150 % of its capacity, step 6 of 6. Showing A request arrives, Room in its class's share? (prefetch: 120 of 20), Bounded queue, Still worth doing?, One of 50 workers, Refused at once. In focus: Bounded queue.share fulldropped, too lateA request arrives120 requests are waitingRoom in its class's share?prefetch: 120 of 20Bounded queuewaits for a workerStill worth doing?time left for the workOne of 50 workersabout 50 ms of workRefused at once503, cheap to send

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. A checkout. A checkout arrives while 120 requests wait. Checkout may use up to 300 places of the queue, so it is admitted.
  2. A page view. A request to browse arrives too. Browsing may use 150 places, and 120 are taken, so it is admitted as well.
  3. A prefetch. A prefetch may use at most 20 places. With 120 waiting it is refused at once with a 503, which costs the server almost nothing.
  4. Before the work starts. When a worker is free, it takes the most important waiting request first, checkout before browsing and browsing before prefetching. A request with too little time left before its client gives up is dropped instead of served.
  5. The work. A request with time left goes to one of the 50 workers. In the simulation this policy kept goodput at about 1,000 a second and served every checkout.
  6. Same server, other policy. Accepting everything instead let the queue grow by 500 requests a second, and goodput fell to 53 a second. The order of the checks is what changed.

Checkpoint

Check: Shedding early, cheaply and by priority

  1. Question 1 of 2 Why must rejecting a request cost far less than serving it?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Otherwise the server spends its capacity on rejections and still serves nobody

    During an overload most requests may be refused. If each refusal costs nearly as much as an answer, the server is overloaded by the refusals alone, which is why rejection belongs as early, and as cheap, as possible.

  2. Question 2 of 2 In the simulation's priority admission, checkout may join while fewer than 300 requests wait, browsing while fewer than 150 and prefetching while fewer than 20. With 160 waiting, which requests are admitted? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 2 of 2

    Answer:

    • A checkout

    Each kind of request gets its own share of the queue, the most important the largest. With that policy the simulation served every checkout, 95.9 % of browsing and almost no prefetching, at the same goodput as a plain queue limit.

Backpressure: bound every queue, and say “slow down”

A queue without a limit does not remove an overload; it stores it. The work waits, memory grows, and every item behind the backlog waits longer, until the process runs out of memory or the waiting outlasts every client. The SRE book suggests queues of at most about half the size of the thread pool for steady traffic, and works an example: with a queue ten times the number of threads and 100 ms of work per request, a request that joins a full queue takes about 1.1 seconds, almost all of it waiting (SRE book, chapter 22).

A bounded queue has to do something when it is full, and there are two choices. It can shed, dropping or refusing the new item. Or it can push back, telling the producer to wait until there is room, which slows the producer to the consumer’s pace. The example connects a producer of 1,200 items a second to a consumer of 1,000 a second through three queues. The pushing-back one works like a Node.js writable stream, whose write() returns false when its buffer is full and emits drain when there is room again (Node.js backpressure guide). The same minute runs in each of the 14 tabs, and each printed the rows under them:

One program · 14 languages One producer, one consumer and three kinds of queue

Python 3.14 · main.py

from collections import deque

CAPACITY = 100  # the limit of the bounded queues


def run(mode: str) -> None:
    queue: deque[int] = deque()  # when each waiting item was made, in ms
    owed = 0.0
    made = dropped = done = paused_ms = 0
    paused = False
    for now in range(1, 60_001):  # one minute, a millisecond at a time
        if paused:
            paused_ms += 1
        else:
            owed += 1.2  # the producer makes 1.2 items a millisecond
        while owed >= 1 and not paused:
            if mode != "no limit" and len(queue) >= CAPACITY:
                if mode == "push back":
                    paused = True  # keep the item and wait for room
                    break
                dropped += 1  # drop: the item is shed
            else:
                queue.append(now)
            owed -= 1
            made += 1
        if queue:  # the consumer handles 1 item a millisecond
            queue.popleft()
            done += 1
            if paused and len(queue) <= CAPACITY // 2:
                paused = False  # drained: the producer may go on
    oldest = 60_000 - queue[0] if queue else 0
    print(
        f"{mode:<10}{made:>7}{done:>9}{len(queue):>9}{oldest:>8} ms"
        f"{dropped:>9}{paused_ms:>8} ms"
    )


print("queue        made  handled  waiting     oldest  dropped     paused")
for mode in ("no limit", "drop", "push back"):
    run(mode)

In Python: collections.deque makes popleft as cheap as append, and each item is the millisecond it was made at, so the oldest item's wait is one subtraction.

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

const CAPACITY = 100; // the limit of the bounded queues
const pad = (n, width) => String(n).padStart(width);

function run(mode) {
  const queue = []; // when each waiting item was made, in ms
  let [owed, made, dropped, done, pausedMs, paused] = [0, 0, 0, 0, 0, false];
  for (let now = 1; now <= 60000; now++) {
    // one minute, a millisecond at a time
    if (paused) pausedMs++;
    else owed += 1.2; // the producer makes 1.2 items a millisecond
    while (owed >= 1 && !paused) {
      if (mode !== "no limit" && queue.length >= CAPACITY) {
        if (mode === "push back") {
          paused = true; // keep the item and wait for room
          break;
        }
        dropped++; // drop: the item is shed
      } else queue.push(now);
      owed -= 1;
      made++;
    }
    if (queue.length) {
      // the consumer handles 1 item a millisecond
      queue.shift();
      done++;
      if (paused && queue.length <= CAPACITY / 2) paused = false; // drained: the producer may go on
    }
  }
  const oldest = queue.length ? 60000 - queue[0] : 0;
  console.log(
    `${mode.padEnd(10)}${pad(made, 7)}${pad(done, 9)}${pad(queue.length, 9)}` +
      `${pad(oldest, 8)} ms${pad(dropped, 9)}${pad(pausedMs, 8)} ms`,
  );
}

console.log("queue        made  handled  waiting     oldest  dropped     paused");
for (const mode of ["no limit", "drop", "push back"]) run(mode);

In JavaScript: An array is the queue, push adds an item and shift takes the oldest, and the six counters of a run are destructured from one array.

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

import java.util.ArrayDeque;
import java.util.Locale;

public class Main {
  static final int CAPACITY = 100; // the limit of the bounded queues

  static void run(String mode) {
    ArrayDeque<Integer> queue = new ArrayDeque<>(); // when each waiting item was made, in ms
    double owed = 0;
    int made = 0;
    int dropped = 0;
    int done = 0;
    int pausedMs = 0;
    boolean paused = false;
    for (int now = 1; now <= 60_000; now++) { // one minute, a millisecond at a time
      if (paused) {
        pausedMs++;
      } else {
        owed += 1.2; // the producer makes 1.2 items a millisecond
      }
      while (owed >= 1 && !paused) {
        if (!mode.equals("no limit") && queue.size() >= CAPACITY) {
          if (mode.equals("push back")) {
            paused = true; // keep the item and wait for room
            break;
          }
          dropped++; // drop: the item is shed
        } else {
          queue.addLast(now);
        }
        owed -= 1;
        made++;
      }
      if (!queue.isEmpty()) { // the consumer handles 1 item a millisecond
        queue.removeFirst();
        done++;
        if (paused && queue.size() <= CAPACITY / 2) {
          paused = false; // drained: the producer may go on
        }
      }
    }
    int oldest = queue.isEmpty() ? 0 : 60_000 - queue.peekFirst();
    System.out.printf(
        "%-10s%7d%9d%9d%8d ms%9d%8d ms%n",
        mode, made, done, queue.size(), oldest, dropped, pausedMs);
  }

  public static void main(String[] args) {
    Locale.setDefault(Locale.ROOT);
    System.out.println("queue        made  handled  waiting     oldest  dropped     paused");
    for (String mode : new String[] {"no limit", "drop", "push back"}) {
      run(mode);
    }
  }
}

In Java: ArrayDeque is the queue, with addLast, removeFirst and peekFirst; the times are boxed as Integer, since a generic deque holds objects.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <deque>
#include <print>
#include <string>

constexpr std::size_t CAPACITY = 100; // the limit of the bounded queues

void run(const std::string &mode) {
  std::deque<int> queue; // when each waiting item was made, in ms
  double owed = 0;
  int made = 0, dropped = 0, done = 0, pausedMs = 0;
  bool paused = false;
  // One minute, a millisecond at a time.
  for (int now = 1; now <= 60'000; now++) {
    if (paused) {
      pausedMs++;
    } else {
      owed += 1.2; // the producer makes 1.2 items a millisecond
    }
    while (owed >= 1 && !paused) {
      if (mode != "no limit" && queue.size() >= CAPACITY) {
        if (mode == "push back") {
          paused = true; // keep the item and wait for room
          break;
        }
        dropped++; // drop: the item is shed
      } else {
        queue.push_back(now);
      }
      owed -= 1;
      made++;
    }
    if (!queue.empty()) { // the consumer handles 1 item a millisecond
      queue.pop_front();
      done++;
      if (paused && queue.size() <= CAPACITY / 2) {
        paused = false; // drained: the producer may go on
      }
    }
  }
  const int oldest = queue.empty() ? 0 : 60'000 - queue.front();
  std::println("{:<10}{:>7}{:>9}{:>9}{:>8} ms{:>9}{:>8} ms", mode, made, done,
               queue.size(), oldest, dropped, pausedMs);
}

int main() {
  std::println(
      "queue        made  handled  waiting     oldest  dropped     paused");
  for (const std::string mode : {"no limit", "drop", "push back"}) {
    run(mode);
  }
}

In C++: std::deque adds at the back and takes from the front in constant time, and CAPACITY is a std::size_t like queue.size(), so the comparisons stay unsigned.

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

const int Capacity = 100; // the limit of the bounded queues

Console.WriteLine("queue        made  handled  waiting     oldest  dropped     paused");
foreach (string mode in new[] { "no limit", "drop", "push back" })
{
    Run(mode);
}

static void Run(string mode)
{
    var queue = new Queue<int>(); // when each waiting item was made, in ms
    double owed = 0;
    int made = 0, dropped = 0, done = 0, pausedMs = 0;
    bool paused = false;
    for (int now = 1; now <= 60_000; now++) // one minute, a millisecond at a time
    {
        if (paused)
        {
            pausedMs++;
        }
        else
        {
            owed += 1.2; // the producer makes 1.2 items a millisecond
        }
        while (owed >= 1 && !paused)
        {
            if (mode != "no limit" && queue.Count >= Capacity)
            {
                if (mode == "push back")
                {
                    paused = true; // keep the item and wait for room
                    break;
                }
                dropped++; // drop: the item is shed
            }
            else
            {
                queue.Enqueue(now);
            }
            owed -= 1;
            made++;
        }
        if (queue.Count > 0) // the consumer handles 1 item a millisecond
        {
            queue.Dequeue();
            done++;
            if (paused && queue.Count <= Capacity / 2)
            {
                paused = false; // drained: the producer may go on
            }
        }
    }
    int oldest = queue.Count > 0 ? 60_000 - queue.Peek() : 0;
    Console.WriteLine(
        $"{mode,-10}{made,7}{done,9}{queue.Count,9}{oldest,8} ms{dropped,9}{pausedMs,8} ms");
}

In C#: Queue<int> is the queue, with Enqueue, Dequeue and Peek, and each number of a row is padded by an alignment in the interpolated string.

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

#include <stdio.h>
#include <string.h>

enum { CAPACITY = 100, MINUTE = 60000 };

static void run(const char *mode) {
  static int queue[MINUTE * 2]; // when each waiting item was made, in ms
  int head = 0, tail = 0;       // the waiting items are queue[head..tail)
  double owed = 0;
  int made = 0, dropped = 0, done = 0, paused_ms = 0;
  bool paused = false;
  const bool limited = strcmp(mode, "no limit") != 0;
  // One minute, a millisecond at a time.
  for (int now = 1; now <= MINUTE; now++) {
    if (paused) {
      paused_ms++;
    } else {
      owed += 1.2; // the producer makes 1.2 items a millisecond
    }
    while (owed >= 1 && !paused) {
      if (limited && tail - head >= CAPACITY) {
        if (strcmp(mode, "push back") == 0) {
          paused = true; // keep the item and wait for room
          break;
        }
        dropped++; // drop: the item is shed
      } else {
        queue[tail++] = now;
      }
      owed -= 1;
      made++;
    }
    if (tail > head) { // the consumer handles 1 item a millisecond
      head++;
      done++;
      if (paused && tail - head <= CAPACITY / 2) {
        paused = false; // drained: the producer may go on
      }
    }
  }
  const int oldest = tail > head ? MINUTE - queue[head] : 0;
  printf("%-10s%7d%9d%9d%8d ms%9d%8d ms\n", mode, made, done, tail - head,
         oldest, dropped, paused_ms);
}

int main(void) {
  puts("queue        made  handled  waiting     oldest  dropped     paused");
  run("no limit");
  run("drop");
  run("push back");
  return 0;
}

In C: A static array with a head and a tail index is the queue; it never needs more than one slot per item made in the minute, at most 72,000.

Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main

PHP 8.5 · main.php

<?php

declare(strict_types=1);

const CAPACITY = 100; // the limit of the bounded queues

function run(string $mode): void
{
    $queue = new SplQueue(); // when each waiting item was made, in ms
    $owed = 0.0;
    $made = $dropped = $done = $pausedMs = 0;
    $paused = false;
    for ($now = 1; $now <= 60_000; $now++) { // one minute, a millisecond at a time
        if ($paused) {
            $pausedMs++;
        } else {
            $owed += 1.2; // the producer makes 1.2 items a millisecond
        }
        while ($owed >= 1 && !$paused) {
            if ($mode !== 'no limit' && count($queue) >= CAPACITY) {
                if ($mode === 'push back') {
                    $paused = true; // keep the item and wait for room
                    break;
                }
                $dropped++; // drop: the item is shed
            } else {
                $queue->enqueue($now);
            }
            $owed -= 1;
            $made++;
        }
        if (!$queue->isEmpty()) { // the consumer handles 1 item a millisecond
            $queue->dequeue();
            $done++;
            if ($paused && count($queue) <= intdiv(CAPACITY, 2)) {
                $paused = false; // drained: the producer may go on
            }
        }
    }
    $oldest = $queue->isEmpty() ? 0 : 60_000 - $queue->bottom();
    $waiting = count($queue);
    printf(
        "%-10s%7d%9d%9d%8d ms%9d%8d ms\n",
        $mode,
        $made,
        $done,
        $waiting,
        $oldest,
        $dropped,
        $pausedMs,
    );
}

echo "queue        made  handled  waiting     oldest  dropped     paused\n";
foreach (['no limit', 'drop', 'push back'] as $mode) {
    run($mode);
}

In PHP: SplQueue from the standard SPL is the queue, because array_shift on a plain array moves every item at each step; bottom() reads the oldest.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php

Rust 1.99 · main.rs

use std::collections::VecDeque;

const CAPACITY: usize = 100; // the limit of the bounded queues

fn run(mode: &str) {
    let mut queue: VecDeque<u32> = VecDeque::new(); // when each waiting item was made, in ms
    let mut owed = 0.0;
    let (mut made, mut dropped, mut done, mut paused_ms) = (0, 0, 0, 0);
    let mut paused = false;
    for now in 1..=60_000 {
        // one minute, a millisecond at a time
        if paused {
            paused_ms += 1;
        } else {
            owed += 1.2; // the producer makes 1.2 items a millisecond
        }
        while owed >= 1.0 && !paused {
            if mode != "no limit" && queue.len() >= CAPACITY {
                if mode == "push back" {
                    paused = true; // keep the item and wait for room
                    break;
                }
                dropped += 1; // drop: the item is shed
            } else {
                queue.push_back(now);
            }
            owed -= 1.0;
            made += 1;
        }
        if queue.pop_front().is_some() {
            // the consumer handles 1 item a millisecond
            done += 1;
            if paused && queue.len() <= CAPACITY / 2 {
                paused = false; // drained: the producer may go on
            }
        }
    }
    let oldest = queue.front().map_or(0, |&made_at| 60_000 - made_at);
    println!(
        "{mode:<10}{made:>7}{done:>9}{:>9}{oldest:>8} ms{dropped:>9}{paused_ms:>8} ms",
        queue.len()
    );
}

fn main() {
    println!("queue        made  handled  waiting     oldest  dropped     paused");
    for mode in ["no limit", "drop", "push back"] {
        run(mode);
    }
}

In Rust: VecDeque is the queue; pop_front returns an Option, so is_some() takes an item and says whether there was one, and map_or reads the oldest.

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

const CAPACITY = 100; // the limit of the bounded queues
const pad = (n: number, width: number): string => String(n).padStart(width);

function run(mode: string): void {
  const queue: number[] = []; // when each waiting item was made, in ms
  let [owed, made, dropped, done, pausedMs, paused] = [0, 0, 0, 0, 0, false];
  for (let now = 1; now <= 60000; now++) {
    // one minute, a millisecond at a time
    if (paused) pausedMs++;
    else owed += 1.2; // the producer makes 1.2 items a millisecond
    while (owed >= 1 && !paused) {
      if (mode !== "no limit" && queue.length >= CAPACITY) {
        if (mode === "push back") {
          paused = true; // keep the item and wait for room
          break;
        }
        dropped++; // drop: the item is shed
      } else queue.push(now);
      owed -= 1;
      made++;
    }
    if (queue.length) {
      // the consumer handles 1 item a millisecond
      queue.shift();
      done++;
      if (paused && queue.length <= CAPACITY / 2) paused = false; // drained: the producer may go on
    }
  }
  const oldest = queue.length ? 60000 - queue[0] : 0;
  console.log(
    `${mode.padEnd(10)}${pad(made, 7)}${pad(done, 9)}${pad(queue.length, 9)}` +
      `${pad(oldest, 8)} ms${pad(dropped, 9)}${pad(pausedMs, 8)} ms`,
  );
}

console.log("queue        made  handled  waiting     oldest  dropped     paused");
for (const mode of ["no limit", "drop", "push back"]) run(mode);

In TypeScript: The queue is a number[] and the helpers are typed; the rest is the JavaScript program.

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import "fmt"

const capacity = 100 // the limit of the bounded queues

func run(mode string) {
	var queue []int // when each waiting item was made, in ms
	owed := 0.0
	made, dropped, done, pausedMs := 0, 0, 0, 0
	paused := false
	for now := 1; now <= 60_000; now++ { // one minute, a millisecond at a time
		if paused {
			pausedMs++
		} else {
			owed += 1.2 // the producer makes 1.2 items a millisecond
		}
		for owed >= 1 && !paused {
			if mode != "no limit" && len(queue) >= capacity {
				if mode == "push back" {
					paused = true // keep the item and wait for room
					break
				}
				dropped++ // drop: the item is shed
			} else {
				queue = append(queue, now)
			}
			owed--
			made++
		}
		if len(queue) > 0 { // the consumer handles 1 item a millisecond
			queue = queue[1:]
			done++
			if paused && len(queue) <= capacity/2 {
				paused = false // drained: the producer may go on
			}
		}
	}
	oldest := 0
	if len(queue) > 0 {
		oldest = 60_000 - queue[0]
	}
	fmt.Printf("%-10s%7d%9d%9d%8d ms%9d%8d ms\n",
		mode, made, done, len(queue), oldest, dropped, pausedMs)
}

func main() {
	fmt.Println("queue        made  handled  waiting     oldest  dropped     paused")
	for _, mode := range []string{"no limit", "drop", "push back"} {
		run(mode)
	}
}

In Go: A slice is the queue, append adds an item and queue[1:] drops the oldest, and the garbage collector reclaims what the slice no longer reaches.

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

let capacity = 100  // the limit of the bounded queues

func pad(_ value: Int, _ width: Int) -> String {
  let text = String(value)
  return String(repeating: " ", count: max(0, width - text.count)) + text
}

func run(_ mode: String) {
  var queue: [Int] = []  // when each waiting item was made, in ms
  var head = 0  // the waiting items are queue[head...]
  var owed = 0.0
  var (made, dropped, done, pausedMs) = (0, 0, 0, 0)
  var paused = false
  for now in 1...60_000 {  // one minute, a millisecond at a time
    if paused {
      pausedMs += 1
    } else {
      owed += 1.2  // the producer makes 1.2 items a millisecond
    }
    while owed >= 1 && !paused {
      if mode != "no limit" && queue.count - head >= capacity {
        if mode == "push back" {
          paused = true  // keep the item and wait for room
          break
        }
        dropped += 1  // drop: the item is shed
      } else {
        queue.append(now)
      }
      owed -= 1
      made += 1
    }
    if head < queue.count {  // the consumer handles 1 item a millisecond
      head += 1
      done += 1
      if paused && queue.count - head <= capacity / 2 {
        paused = false  // drained: the producer may go on
      }
    }
  }
  let waiting = queue.count - head
  let oldest = waiting > 0 ? 60_000 - queue[head] : 0
  let name = mode + String(repeating: " ", count: 10 - mode.count)
  print(
    name + pad(made, 7) + pad(done, 9) + pad(waiting, 9) + pad(oldest, 8) + " ms"
      + pad(dropped, 9) + pad(pausedMs, 8) + " ms")
}

print("queue        made  handled  waiting     oldest  dropped     paused")
for mode in ["no limit", "drop", "push back"] {
  run(mode)
}

In Swift: An array and a head index are the queue, because removeFirst on an array moves every item; without Foundation, pad lines the columns up.

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

CAPACITY = 100 # the limit of the bounded queues

# One minute of a producer and a consumer joined by one kind of queue.
class Run
  def initialize(mode)
    @mode = mode
    @queue = [] # when each waiting item was made, in ms
    @owed = 0.0
    @made = @dropped = @done = @paused_ms = 0
    @paused = false
  end

  def minute
    (1..60_000).each do |now| # one minute, a millisecond at a time
      if @paused
        @paused_ms += 1
      else
        @owed += 1.2 # the producer makes 1.2 items a millisecond
      end
      produce(now) until @paused || @owed < 1
      consume
    end
    self
  end

  def to_s
    oldest = @queue.empty? ? 0 : 60_000 - @queue.first
    format('%<mode>-10s%<made>7d%<done>9d%<waiting>9d%<oldest>8d ms%<dropped>9d%<paused>8d ms',
           mode: @mode, made: @made, done: @done, waiting: @queue.size, oldest: oldest,
           dropped: @dropped, paused: @paused_ms)
  end

  private

  def produce(now)
    if @mode == 'no limit' || @queue.size < CAPACITY
      @queue << now
    elsif @mode == 'push back'
      return @paused = true # keep the item and wait for room
    else
      @dropped += 1 # drop: the item is shed
    end
    @owed -= 1
    @made += 1
  end

  def consume
    return if @queue.empty? # the consumer handles 1 item a millisecond

    @queue.shift
    @done += 1
    @paused = false if @queue.size <= CAPACITY / 2 # drained: the producer may go on
  end
end

puts 'queue        made  handled  waiting     oldest  dropped     paused'
['no limit', 'drop', 'push back'].each { |mode| puts Run.new(mode).minute }

In Ruby: Each run is an object with short methods, the style RuboCop expects; produce stops the producer when the queue pushes back, and Array#shift takes the oldest item.

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

const val CAPACITY = 100 // the limit of the bounded queues

fun run(mode: String) {
    val queue = ArrayDeque<Int>() // when each waiting item was made, in ms
    var owed = 0.0
    var made = 0
    var dropped = 0
    var done = 0
    var pausedMs = 0
    var paused = false
    for (now in 1..60_000) { // one minute, a millisecond at a time
        if (paused) pausedMs++ else owed += 1.2 // the producer makes 1.2 items a millisecond
        while (owed >= 1 && !paused) {
            if (mode != "no limit" && queue.size >= CAPACITY) {
                if (mode == "push back") {
                    paused = true // keep the item and wait for room
                    break
                }
                dropped++ // drop: the item is shed
            } else {
                queue.addLast(now)
            }
            owed -= 1
            made++
        }
        if (queue.isNotEmpty()) { // the consumer handles 1 item a millisecond
            queue.removeFirst()
            done++
            if (paused && queue.size <= CAPACITY / 2) paused = false // drained
        }
    }
    val oldest = queue.firstOrNull()?.let { 60_000 - it } ?: 0

    fun pad(
        value: Int,
        width: Int,
    ) = "$value".padStart(width)
    println(
        mode.padEnd(10) + pad(made, 7) + pad(done, 9) + pad(queue.size, 9) +
            pad(oldest, 8) + " ms" +
            pad(dropped, 9) + pad(pausedMs, 8) + " ms",
    )
}

fun main() {
    println("queue        made  handled  waiting     oldest  dropped     paused")
    for (mode in listOf("no limit", "drop", "push back")) run(mode)
}

In Kotlin: kotlin.collections.ArrayDeque is the queue, and if (paused) ... else ... decides on one line whether the producer works this millisecond.

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

import 'dart:collection';

const capacity = 100; // the limit of the bounded queues

String pad(int value, int width) => '$value'.padLeft(width);

void run(String mode) {
  final queue = ListQueue<int>(); // when each waiting item was made, in ms
  var owed = 0.0;
  var (made, dropped, done, pausedMs) = (0, 0, 0, 0);
  var paused = false;
  for (var now = 1; now <= 60000; now++) {
    // one minute, a millisecond at a time
    if (paused) {
      pausedMs++;
    } else {
      owed += 1.2; // the producer makes 1.2 items a millisecond
    }
    while (owed >= 1 && !paused) {
      if (mode != 'no limit' && queue.length >= capacity) {
        if (mode == 'push back') {
          paused = true; // keep the item and wait for room
          break;
        }
        dropped++; // drop: the item is shed
      } else {
        queue.addLast(now);
      }
      owed -= 1;
      made++;
    }
    if (queue.isNotEmpty) {
      // the consumer handles 1 item a millisecond
      queue.removeFirst();
      done++;
      if (paused && queue.length <= capacity ~/ 2) paused = false; // drained
    }
  }
  final oldest = queue.isEmpty ? 0 : 60000 - queue.first;
  print(
    '${mode.padRight(10)}${pad(made, 7)}${pad(done, 9)}${pad(queue.length, 9)}'
    '${pad(oldest, 8)} ms${pad(dropped, 9)}${pad(pausedMs, 8)} ms',
  );
}

void main() {
  print('queue        made  handled  waiting     oldest  dropped     paused');
  for (final mode in ['no limit', 'drop', 'push back']) {
    run(mode);
  }
}

In Dart: ListQueue from dart:collection is the queue, with addLast and removeFirst, and ~/ divides the capacity as integers.

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

queue        made  handled  waiting     oldest  dropped     paused
no limit    71999    60000    11999    9999 ms        0       0 ms
drop        71999    60000       99      98 ms    11900       0 ms
push back   60063    60000       63      52 ms        0    9947 ms

Without a limit, 11,999 items wait after a minute and the oldest has waited 10 seconds. Dropping keeps the queue at 99 items and every wait under 100 ms, at the cost of 11,900 lost items. Pushing back loses nothing: the producer spends 10 of the 60 seconds paused, so it runs at exactly the consumer’s pace, and items wait about 50 ms. The Node.js guide measured what ignoring the signal costs in a real stream: about 88 MB of memory with backpressure and about 1.5 GB without it. Step through the moment the pushing-back queue fills, and the moment it lets the producer go on:

Interactive · message by message A producer, a full queue and a drain signal Step through the pushing-back queue of the program below, from the moment it fills to the moment the producer goes on.
A producer, a full queue and a drain signal, step 6 of 6. Messages so far: Producer to Queue: item, item, item; Queue to Producer: no room; Queue to Consumer: oldest item; Queue to Producer: drain; Producer to Queue: item, item, item.Producer1.2 items a msQueue50 of 100Consumer1 item a msitem, item, itemno roomoldest itemdrainitem, item, item

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Filling up. The producer makes 1.2 items a millisecond and the consumer takes 1, so the queue grows by about one item every 5 milliseconds.
  2. Full. The queue reaches its limit of 100. The next offer is refused, which tells the producer that there is no room, as write() returning false tells a Node.js writer.
  3. The producer waits. The producer keeps the item and pauses. Nothing is lost and nothing more piles up, while the consumer goes on taking one item a millisecond.
  4. Half empty. When only 50 items are left, the queue says it has room again, as a drain event does.
  5. The producer goes on. The producer resumes and fills the queue again. Over the minute it was paused for 9,947 ms, about 10 seconds, so it ran at exactly the consumer's pace.
  6. What it bought. No item was dropped, and the oldest waiting item had waited 52 ms at the end of the minute, against 9,999 ms for the queue with no limit.

Push back when the producer can wait: a batch job, a pipeline stage, a service that reads from a durable log. Shed when it cannot: users, devices and sensors keep producing whatever you do, so tell them clearly. Between services, the signals are HTTP status codes. 429 Too Many Requests says a client has sent too many requests in a given time (RFC 6585); 503 Service Unavailable says the server is temporarily overloaded; and either may carry Retry-After, the number of seconds to wait or a date (RFC 9110). Asynchronous libraries carry the same idea inside programs: Reactive Streams exists so that the receiving side is never forced to buffer an unlimited amount of data (Reactive Streams).

One rule ties the layers together: pass overload signals on. The Azure throttling pattern warns that a service which hides a 429 or 503 returned by its own dependency, by retrying silently or by answering 500, keeps its callers from slowing down, and the overload travels back up the chain.

Key idea

A queue without a limit stores an overload instead of removing it: bound every queue, push back when the producer can wait, shed when it cannot, and pass the signal on.

Checkpoint

Check: Bounded queues and backpressure

  1. Question 1 of 2 Which of these tell a sender to slow down instead of letting work pile up? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 1 of 2

    Answer:

    • A 503 response with a Retry-After header
    • A Node.js writable stream whose write() returns false until it emits drain
    • A 429 Too Many Requests response

    The first three are explicit signals: the server, or the stream, says it has no room and when to come back. A queue without a limit says nothing until memory runs out, and instant retries add load instead of removing it.

  2. Question 2 of 2 A mobile app sends analytics events to a collector whose queue is full. The app cannot make its users slow down. Should the collector's queue push back or shed?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Shed, and say so clearly, because the producer cannot wait

    Push back when the producer can wait: a batch job, a pipeline stage, a reader of a durable log. Shed when it cannot, and tell it clearly with 429 or 503 and Retry-After.

HTTP Status Codes Reference Check what 429 and 503 promise before you choose which one your service sends when it sheds load.

Degrade gracefully, by priority

Shedding refuses whole requests; degradation makes requests cheaper. The SRE book describes degraded answers that are less accurate or hold less data but are easier to compute (chapter 21), such as searching only the data held in memory or ranking results with a cheaper method (chapter 22), and the Azure pattern’s example is a video service that drops to a lower resolution. Plan the order before the overload, feature by feature, from the first to go to the last:

  1. Prefetching and analytics events: stop them, and let the app keep events and send them later. Nobody notices for a while.
  2. Recommendations: serve a cached list of popular items. They are useful, not essential.
  3. Reviews and ratings: serve a slightly stale copy, or hide them. Users can still decide.
  4. Search: return fewer results, rank them more cheaply and serve cached queries. It is a core journey, but a cheaper answer still helps.
  5. Checkout and payment: keep them in full. They are the journey users pay through.

Step through the same order on one product page:

Interactive · step by step One product page, degraded feature by feature Step through the lesson's order of degradation. Each step makes the page cheaper to serve and says what the user still gets.
One product page, degraded feature by feature, step 6 of 6. Showing Prefetch and analytics (stopped, sent later), Recommendations (cached popular list), Reviews and ratings (stale copy), Search (fewer, cheaper results), Checkout and payment. In focus: Checkout and payment.Prefetch and analyticsstopped, sent laterRecommendationscached popular listReviews and ratingsstale copySearchfewer, cheaper resultsCheckout and paymentfull service

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Full service. On a normal day every part of the page is served in full. When load nears capacity, the page sheds work in an order planned before the overload.
  2. First to go. Prefetching stops, and the app keeps its analytics events to send later. Nobody notices for a while.
  3. Second. Recommendations come from a cached list of popular items. They are useful, not essential.
  4. Third. Reviews and ratings come from a slightly stale copy, or are hidden. Users can still decide.
  5. Fourth. Search returns fewer results, ranked more cheaply, and serves cached queries. It is a core journey, but a cheaper answer still helps.
  6. Kept to the end. Checkout and payment keep their full service, because they are the journey users pay through. The page tells users what changed rather than failing silently.

Tell users what changed (“recommendations are unavailable right now”) rather than failing silently. And exercise the degraded paths: the SRE book warns that a code path you never use is often a path that does not work, and suggests running a small set of servers near overload regularly so that the degraded mode is tested. Finally, test the whole system past its capacity on purpose. The Builders’ Library’s goal for such a test is a flat line: goodput that rises to the server’s capacity and stays there as the offered load keeps growing, instead of falling to zero.

Checkpoint

Check: Graceful degradation

  1. Question 1 of 2 In the lesson's plan for an online shop, which feature is degraded first?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Prefetching and analytics events, which the app can keep and send later

    Plan the order before the overload: prefetching and analytics first, then recommendations, then reviews, then a cheaper search, and checkout last of all.

  2. Question 2 of 2 Why does the SRE book suggest running a small set of servers near overload regularly?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: So that the degraded mode is exercised, because a code path you never use is often a path that does not work

    Degraded answers are a code path like any other, and one that runs only during overloads. Exercising it on purpose, and testing the whole system past its capacity, is how teams learn that it still works.

Practise: admit by priority, and say when to return

Write the admission control of an overloaded server in Python: who may join the queue, how long a refused client should wait, and the answer that puts the two together. Its sample tests run here:

Exercise · Medium · Python

Admit by priority, and say when to come back

Write the admission control of an overloaded server in admission.py: three functions that decide, for each new request, whether it may join the queue.

admit(priority, waiting, limit) returns whether a request may join a queue that already holds waiting requests, when the queue may hold limit requests in all. Important work may use more of the queue than optional work:

  • a "critical" request (checkout, payment) is admitted while fewer than limit requests wait;
  • a "normal" request (browsing) only while fewer than 80 % of limit wait;
  • a "sheddable" request (prefetching, analytics) only while fewer than 50 % of limit wait.

retry_after(waiting, drain_per_second) returns the whole number of seconds a refused client should wait before it tries again: the time the queue needs to drain at drain_per_second requests a second, rounded up, and never less than 1.

decide(priority, waiting, limit, drain_per_second) puts the two together. It returns (200, None) when the request is admitted, and (503, seconds) when it is refused, with seconds from retry_after, ready for a Retry-After header.

For example, with a limit of 100, a normal request is admitted while 79 requests wait but not when 80 do, and retry_after(250, 100) is 3.

Starter code · admission.py

import math

# The share of the queue each priority may fill.
SHARE = {"critical": 1.0, "normal": 0.8, "sheddable": 0.5}


def admit(priority, waiting, limit):
    """Whether a request of this priority may join a queue that already holds `waiting` of at most `limit`."""
    # Replace this line with your code.
    return True


def retry_after(waiting, drain_per_second):
    """Seconds a refused client should wait: the time the queue needs to drain, rounded up, at least 1."""
    # Replace this line with your code.
    return 0


def decide(priority, waiting, limit, drain_per_second):
    """(200, None) for an admitted request, (503, seconds to wait) for a refused one."""
    # Replace this line with your code.
    return (200, None)
The sample tests · test_admission.py
from admission import admit, decide, retry_after


def test_critical_uses_the_whole_queue():
    """a critical request is admitted until the queue is full"""
    assert admit("critical", 0, 100) is True
    assert admit("critical", 99, 100) is True
    assert admit("critical", 100, 100) is False


def test_normal_keeps_room_for_critical():
    """a normal request may use 80 % of the queue"""
    assert admit("normal", 79, 100) is True
    assert admit("normal", 80, 100) is False
    assert admit("normal", 159, 200) is True
    assert admit("normal", 160, 200) is False


def test_sheddable_goes_first():
    """a sheddable request may use only half of the queue"""
    assert admit("sheddable", 49, 100) is True
    assert admit("sheddable", 50, 100) is False
    assert admit("sheddable", 0, 2) is True
    assert admit("sheddable", 1, 2) is False


def test_retry_after_rounds_up():
    """the wait is the time the queue needs to drain, rounded up"""
    assert retry_after(250, 100) == 3
    assert retry_after(200, 100) == 2
    assert retry_after(201, 100) == 3


def test_retry_after_is_at_least_one_second():
    """even a nearly empty queue asks for at least a second"""
    assert retry_after(0, 100) == 1
    assert retry_after(30, 100) == 1


def test_decide():
    """admitted requests get 200; refused ones get 503 and the seconds for Retry-After"""
    assert decide("critical", 99, 100, 50) == (200, None)
    assert decide("sheddable", 60, 100, 50) == (503, 2)
    assert decide("normal", 90, 100, 20) == (503, 5)
A hint

Compare waiting with a share of the limit: limit, 0.8 * limit or 0.5 * limit, with < so that the boundary itself is refused. A dictionary from priority to share keeps admit short. For retry_after, math.ceil rounds up and max(1, …) keeps the answer at least 1.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

After that, test yourself on overload, one question at a time. Your weakest idea is asked about first, and the next question gets harder after each right answer and easier after a slip:

Practice that adapts to you

Practise this lesson

12 questions about 4 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 12 In the simulation, a server that finishes about 1,000 requests a second was offered 1,500 a second and accepted everything. What goodput did it reach, in requests a second?

    Type a number.

    Show the answer: Question 1 of 12

    Answer: 53 requests a second

    About 5 % of what the server can do: after the first seconds every answer came after its client had given up waiting, at 1 second. A queue limit of 100 brought goodput back to 1,004 a second.

  2. Question 2 of 12 The queue limit of 100 restored full goodput in the simulation. What was still wrong with it?

    Choose one answer.

    Show the answer: Question 2 of 12

    Answer: It refused requests blindly, so checkout lost as much as prefetching

    A plain limit protects goodput but not the business: every kind of request lost the same third. Giving each kind its own share of the queue keeps the same goodput and spends it on the journeys that matter.

  3. Question 3 of 12 A server finishes 2,000 requests a second and is offered 2,500, and it queues everything. Clients give up after 2 seconds. After how many seconds of overload does a new request's wait reach the clients' timeout?

    Type a number.

    A hint

    The wait is the queue length divided by the rate the server works through it.

    Show the answer: Question 3 of 12

    Answer: 8 seconds (anything from 7.8 to 8.2 counts)

    The queue grows by 500 requests a second, and a new request waits the queue length ÷ 2,000 seconds. The wait reaches 2 seconds when 4,000 are queued, after 4,000 ÷ 500 = 8 seconds; from then on the server works only for clients who have left.

  4. Question 4 of 12 In the SRE book's adaptive throttling with K = 2, a client sent 1,000 requests in the last two minutes and the backend accepted 300 of them. With what probability, in per cent, does the client now reject a new request locally?

    Type a number.

    A hint

    Compare the requests with K times the accepts, as the formula in the lesson does.

    Show the answer: Question 4 of 12

    Answer: 40 % (anything from 39 to 41 counts)

    (1,000 − 2 × 300) ÷ (1,000 + 1) = 400 ÷ 1,001 ≈ 40 %. The client refuses that share of its own new requests, so the backend no longer spends work rejecting them.

  5. Question 5 of 12 Under load, which requests should a server keep serving first, by the Builders' Library's priorities?

    Choose one answer.

    Show the answer: Question 5 of 12

    Answer: The load balancer's health checks

    Three priorities are easy to miss: health checks first, work already started before new work, and expired requests dropped instead of served late.

  6. Question 6 of 12 What does CoDel, the network queue algorithm of RFC 8289, watch to decide when to start dropping?

    Choose one answer.

    Show the answer: Question 6 of 12

    Answer: How long packets have spent in the queue, against a target of 5 ms over an interval of 100 ms

    Measure how long items have waited, not only how many there are. CoDel drops when the time in the queue stays above 5 ms for 100 ms, and a request queue can apply the same idea with its own target.

  7. Question 7 of 12 In the three-queue program, how long had the oldest waiting item waited after one minute in the queue with no limit, in milliseconds?

    Type a number.

    Show the answer: Question 7 of 12

    Answer: 9999 ms

    With 1.2 items made and 1 handled each millisecond, 11,999 items wait at the end and the oldest of them has waited 9,999 ms, about 10 seconds. The bounded queues kept every wait under 100 ms.

  8. Question 8 of 12 In the SRE book's example, a queue holds ten times as many requests as there are threads, and each request takes 100 ms of work. About how long does a request that joins a full queue take, in seconds?

    Type a number.

    Show the answer: Question 8 of 12

    Answer: 1.1 seconds (anything from 1.05 to 1.15 counts)

    Ten requests per thread wait ahead of it, 10 × 100 ms = 1 second, plus its own 100 ms of work: about 1.1 seconds, almost all of it waiting. That is why the book suggests queues of at most about half the thread pool.

  9. Question 9 of 12 During an overload, a service retries silently when its dependency answers 503, and answers its own callers with 500. What goes wrong?

    Choose one answer.

    Show the answer: Question 9 of 12

    Answer: Its callers cannot tell that they should slow down, so the overload travels back up the chain

    Pass overload signals on. A service that hides a 429 or 503 from its dependency behind silent retries or a 500 keeps its callers from slowing down, which is how an overload spreads back up the chain.

  10. Question 10 of 12 An online shop is overloaded. Put these kinds of work in the order they should be shed, the first to go at the top.

    Give each item its position, from 1 (first).

    Show the answer: Question 10 of 12

    Answer:

    1. Prefetching the next page and sending analytics events
    2. Personalised recommendations
    3. Search results
    4. Checkout and payment

    Shed what users notice least and what can be retried or skipped: prefetches and analytics first, then optional features such as recommendations (a cached popular list will do), then degrade search, and keep checkout, the journey that earns money, for last.

  11. Question 11 of 12 Recommendations are switched to a cached list during an overload. What should the page do about it?

    Choose one answer.

    Show the answer: Question 11 of 12

    Answer: Tell users what changed, for example that recommendations are unavailable right now

    Degradation makes requests cheaper while the important journeys keep working, and the page says what changed rather than failing silently.

  12. Question 12 of 12 What should a test that offers a system more load than it can handle show, by the Builders' Library's goal?

    Choose one answer.

    Show the answer: Question 12 of 12

    Answer: Goodput that rises to the server's capacity and stays there as the offered load keeps growing

    Test past capacity on purpose. The goal is a flat line: goodput climbs to capacity and stays there, because the excess is refused early and the remaining work is served in time.

JavaScript & TypeScript Online Compiler Change the producer's rate or the queue's capacity in the backpressure example and run it again. Python Online Compiler Try other queue limits and priority shares in the overload simulation.

Design practice: overloads to survive

Overload questions in a design round come with a traffic spike and a deadline. Settle your opening move on each brief, then compare it with the four policies of the simulation and the three queues above:

Checkpoint

Your first decision

  1. Question 1 of 2 Design brief: a sale will send about 4,500 checkouts a second to a service that sustains 2,000 within its latency objective. Last time it queued everything and fell over. What do you decide first?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Admit about what the service sustains and refuse the rest early and cheaply, by priority, so that what is accepted is served in time

    The last sale failed because every request waited until its client gave up, so goodput fell while the servers stayed busy. Admission control sized to what the service sustains keeps goodput near capacity; priority decides which requests get the room.

  2. Question 2 of 2 Design brief: an event pipeline falls behind every evening, and the producer's memory grows until it crashes. What is your first step?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Find where the events pile up and measure each stage's rate, because a growing producer buffers what the next stage will not take

    A producer whose memory grows is sending faster than the next stage accepts. If 12,000 events a second arrive and the consumers handle 10,000, the backlog grows by 7.2 million an hour, so the fix starts from those rates and a bounded buffer.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to staff

    A sale sends three times the usual traffic to your checkout service. Last time, its p99 rose from 300 ms to 30 seconds and then the service fell over. Design the overload protection for the next sale, with numbers.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    An event pipeline falls hours behind every evening, and the producer service's memory grows until it crashes. How do you add backpressure from end to end, and what happens to the events that cannot be processed in time?

    Model answer, Pro. First step and follow-ups

Interview questions

Warm-up (fresher to mid level): what is the difference between load shedding and rate limiting? Rate limiting enforces a quota per client, such as 100 requests a minute, whatever the server’s state; it is about fairness and abuse, and it answers with 429 Too Many Requests. Load shedding reacts to the server’s own state: when it is near its capacity it refuses work from anyone, ideally the least important work first, and answers with 503 and a Retry-After. They complement each other. A rate limit stops one client from taking more than its share; load shedding protects the server when the fair shares of all clients together are still more than it can finish.

Key takeaways

  • Goodput is the work that is correct and on time. Offered 150 % of its capacity, a server that queued everything kept only about 5 % of its possible goodput in the simulation.
  • Reject the excess early and cheaply: clients can throttle themselves, load balancers should refuse rather than queue, and servers admit work by priority and by deadline.
  • Give the most important work the largest share of capacity: with priority admission every checkout succeeded at 150 % load while prefetching was shed.
  • Bound every queue. When one is full, push back if the producer can wait and shed if it cannot, and signal clearly with 429 or 503 and Retry-After.
  • Pass overload signals on instead of hiding them behind retries or a 500.
  • Plan degradation feature by feature, tell users, and exercise the degraded paths and the overload itself in tests.

Terms in this lesson

admission control
A limit on the work a server has in progress, checked before any expensive work starts, that decides by priority and by deadline which new requests may join the queue.
backpressure
Sending an overload back to where the work comes from: a full queue tells its producer to wait, or a server answers 429 or 503 with Retry-After, instead of letting work pile up.
goodput
The requests a server answers without an error and soon enough for the caller to use the answer. Throughput counts all of its work; an overloaded server can stay busy and still have almost no goodput.
graceful degradation
Making requests cheaper under load by dropping optional features and serving cached, stale or partial answers in a planned order, so that the journeys users depend on keep working.
load shedding
Refusing excess work quickly and cheaply when a server nears its capacity, ideally the least important work first, so that the requests it does accept are still answered in time.

Corrections

  • Priority admission is now described in full, as the simulation runs it: besides its share of the queue for each kind of request, its workers take the most important waiting request first.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.