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.
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.
# 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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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:
Requests arrive at 150 a second but are served at only 100: the queue grows without limit and waiting times with it.
The numbers as a table
| Utilisation | Mean 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
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:
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.
- Clients send requests. They back off, keep a retry budget and throttle themselves when they are refused.
- The load balancer passes on requests within its connection limits and rejects the excess instead of queueing it.
- The server's admission control decides, by priority and by the request's deadline, which requests to accept.
- Accepted work waits in a bounded queue; when the queue is full, a new item is rejected or its sender waits.
- 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.
- 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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- A checkout. A checkout arrives while 120 requests wait. Checkout may use up to 300 places of the queue, so it is admitted.
- A page view. A request to browse arrives too. Browsing may use 150 places, and 120 are taken, so it is admitted as well.
- 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.
- 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.
- 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.
- 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
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 65 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 152 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 2 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 8 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 20 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 716 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 185 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 11 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- Half empty. When only 50 items are left, the queue says it has room again, as a drain event does.
- 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.
- 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
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:
- Prefetching and analytics events: stop them, and let the app keep events and send them later. Nobody notices for a while.
- Recommendations: serve a cached list of popular items. They are useful, not essential.
- Reviews and ratings: serve a slightly stale copy, or hide them. Users can still decide.
- Search: return fewer results, rank them more cheaply and serve cached queries. It is a core journey, but a cheaper answer still helps.
- Checkout and payment: keep them in full. They are the journey users pay through.
Step through the same order on one product page:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- First to go. Prefetching stops, and the app keeps its analytics events to send later. Nobody notices for a while.
- Second. Recommendations come from a cached list of popular items. They are useful, not essential.
- Third. Reviews and ratings come from a slightly stale copy, or are hidden. Users can still decide.
- Fourth. Search returns fewer results, ranked more cheaply, and serves cached queries. It is a core journey, but a cheaper answer still helps.
- 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
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 thanlimitrequests wait; - a
"normal"request (browsing) only while fewer than 80 % oflimitwait; - a
"sheddable"request (prefetching, analytics) only while fewer than 50 % oflimitwait.
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.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
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.
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
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
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.
-
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?
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
- Using load shedding to avoid overload (Amazon Builders' Library) (Amazon Web Services)
- Site Reliability Engineering, chapter 21: Handling Overload (Google (O'Reilly Media))
- Site Reliability Engineering, chapter 22: Addressing Cascading Failures (Google (O'Reilly Media))
- Throttling pattern (Azure Architecture Center) (Microsoft)
- RFC 6585: Additional HTTP Status Codes (429 Too Many Requests) (IETF)
- RFC 9110: HTTP Semantics (503 Service Unavailable, Retry-After) (IETF)
- RFC 8289: Controlled Delay Active Queue Management (IETF)
- Backpressuring in streams (Node.js documentation) (OpenJS Foundation (Node.js))
- Reactive Streams (Reactive Streams initiative)
- concurrency-limits (README) (Netflix (open source, Apache-2.0))
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress