System Design (High-Level Design) Module 3 – Performance and reliability fundamentals
How distributed systems fail
Classify crash, omission, timing and Byzantine faults, spot partial, gray and metastable failures, and handle the unknown outcome of a call that timed out.
What you will learn
- Classify crash, omission, timing and Byzantine faults by what a caller sees
- Recognise partial, gray and metastable failures from their symptoms
- Implement safe retries with an idempotency key, and reconcile a call that timed out
- Design for the failure modes that actually occur in production, starting with unknown outcomes
Before you start
What you’ll learn · Before you start
What you will learn
- Classify crash, omission, timing and Byzantine faults by what a caller sees
- Recognise partial, gray and metastable failures from their symptoms
- Implement safe retries with an idempotency key, and reconcile a call that timed out
- Design for the failure modes that actually occur in production, starting with unknown outcomes
Before you start
On this page
On one computer, a program mostly either works or stops. A distributed system can do something worse: fail partially, as when a payment service loses 3 % of its replies and every one of those customers is charged and told that the payment failed. Some machines work, some have crashed, some messages arrive and some are lost, and a call can end without any answer at all. That last case is the hardest to design for, because a call that timed out may have succeeded, failed, or still be running.
The sections below name the kinds of faults that distributed systems are designed against (crash, omission, timing and Byzantine fault: A fault in which a node does anything at all: wrong answers that look valid, lies, different stories to different peers. With unsigned messages, agreement then needs more than two thirds of the nodes to be honest.), show how a timeout leaves an unknown outcome and how idempotency key: A unique id that a client chooses once for an operation and sends with every attempt of it. The server stores the result under the key, so a repeat gets the stored result instead of a second charge or write. handle it, and describe two failure patterns that health checks and retries make worse rather than better: gray failure: A failure that users see while the system's own failure detectors see a healthy component, such as a server whose request handling is stuck while its heartbeat still runs. and metastable failure: A bad state that lasts after its trigger has gone, because a feedback loop such as retries keeps the load high. Leaving it takes a strong push, such as cutting the load sharply or changing the retry policy..
One call has eight steps, and each can fail
Amazon’s Builders’ Library takes one request and reply between a client and a server and lists eight steps that can each go wrong independently: sending the request, delivering it, the server validating it, the server updating its state, the server sending the reply, delivering the reply, the client validating it, and the client updating its own state. Client, server and network fail independently of each other, and most of these failures look identical from the client’s side: nothing comes back.
One remote call, and the places it can fail
Text description of the diagram
The diagram follows one call from top to bottom.
- The client sends a request to charge order 7.
- The network carries it, and may lose or delay it.
- The server may crash before charging the card, or after charging it but before replying.
- The network carries the reply, and may lose or delay it.
- The client receives the reply or, if nothing arrives in time, a timeout.
A timeout looks the same whether the request was lost, the server crashed before acting, or the card was charged and the reply was lost. The client cannot tell which, so it has to handle an unknown outcome.
The diagram shows where one call can fail. The figure below plays three of those places out on the same call to charge order 7, and each of them ends in the same timeout:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- Lost on the way in. The client sends "charge order 7" and starts its timer. The network loses the request, so the server never sees it and no card is charged.
- The timer runs out. No reply arrives before the timer runs out, so the client sees a timeout. Here nothing happened at all.
- A crash before acting. Second try at the same moment in another world. The request arrives, but the server crashes before it charges the card. Again the client sees only a timeout.
- A lost reply. Third world. The server charges the card and replies, but the network loses the reply on its way back.
- The same silence. The client sees exactly the same timeout as before, yet this time the customer has paid. From the client's side the three cases cannot be told apart.
- An unknown outcome. A timeout means the outcome is unknown, so the client must handle all three cases at once. Retrying blindly can charge twice; giving up can tell a paying customer the payment failed.
The article’s conclusion is the rule this lesson is built around: when a call times out, its result is unknown. The request may never have arrived, the server may have crashed before acting, or it may have acted and lost its reply. The client has to handle all three at once. This is not a rare corner: the same article warns that bugs in how a service handles these cases can stay hidden in production for months before a rare combination of failures sets them off.
Key idea
A timeout says only that no reply came in time: the request may have been lost, the server may have crashed before acting, or it may have acted and lost its reply, so the outcome of the call is unknown.
Checkpoint
Check: What a timeout tells you
Four fault models, from a crash to a lie
Designs and protocols state which faults they tolerate, in the terms of a system model. Martin Kleppmann’s Cambridge lecture notes describe a system model in three parts, network, nodes and timing, and the four classic kinds of fault map onto them. From the easiest to tolerate to the hardest:
- Crash. A node stops, and may restart with only what it saved to disk. From outside it looks like silence, then a node that has forgotten its memory; a process killed for using too much memory is the everyday case. Defences: replicas, durable writes and restarts.
- Omission. A message is lost on the way in or on the way out, for example by a congested switch. From outside it looks like silence. Defences: timeouts, retries and deduplication.
- Timing. A correct answer arrives too late, after a garbage-collection pause or behind a slow disk: silence, then a late reply. Defences: timeouts, hedging, and protocols that stay correct when delays have no bound.
- Byzantine, or arbitrary. A node does anything at all: wrong answers, lies, different stories to different peers, because of corrupted memory, a compromised machine or a participant who cheats. Its answers look valid. Defences: signatures, checksums and protocols that tolerate a minority of liars.
Step through the same call under each of the four, as the client sees it:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- A normal call. The client asks for an account balance, the server answers 120 within a few milliseconds, and the reply arrives well before the 2-second timeout.
- Crash. The server process is killed for using too much memory. The client hears nothing; a minute later the server restarts with what it saved to disk and none of its memory.
- Omission. A congested switch drops the request. The server keeps working and would have answered correctly, but the client again hears nothing.
- Timing. The server answers correctly, but a garbage-collection pause holds the reply for 3 seconds. It arrives after the client has given up, so a correct answer is treated as a failure.
- Byzantine. A faulty memory chip corrupts the balance, and the server answers 0 as if it were right. The reply arrives in time and looks valid, which is what makes this fault the hardest.
- Four faults, three signs. From the client's side, a crash and an omission look like silence, a timing fault like a late reply, and a Byzantine fault like a normal answer. Each needs a different defence.
The notes distinguish crash-stop nodes, which never come back, from crash-recovery: A fault model in which a node may stop and later restart with what it saved to disk but none of its memory. Most real services are crash-recovery; crash-stop nodes never come back. nodes, which may restart having lost their memory but kept their disk; most real services are crash-recovery. On the network side, a “fair-loss” link may lose, duplicate or reorder messages, but a message retried often enough eventually gets through, which is why retries plus deduplication can turn it into a reliable link. For timing, the notes explain why real systems are only partially synchronous: networks and nodes are usually predictable, then occasionally pause for garbage collection, page faults, congestion or rerouting, and no timeout can tell a slow node from a dead one.
Byzantine faults are the general case, named after Lamport, Shostak and Pease’s paper on generals who must agree on a plan while some of them are traitors. Their result is that with ordinary messages, agreement is possible only if more than two thirds of the generals are loyal; with unforgeable signed messages it is possible for any number. Kleppmann notes that a bug shared by every node cannot be outvoted by such a protocol, because every node has it, so the term is usually kept for deliberate deviation. Services inside one organisation assume crash-recovery faults; blockchains and other systems shared between parties who do not trust each other must tolerate Byzantine ones.
Checkpoint
Check: The four fault models
A timeout does not tell you what happened
The program below pays for 10,000 orders through a fake payment server. The network loses 2% of requests before they reach the server and 3% of replies after the server has charged the card; the client sees the same timeout in both cases. Three clients face the same network luck:
"""A payment call that times out has an unknown outcome: the charge may or may not have happened.
A fake payment server charges a card when a request reaches it. The network loses 2% of requests on the way in
and 3% of replies on the way out; in both cases the client only sees a timeout. Three client strategies pay
for the same 10,000 orders with the same network luck. The rates are assumptions for the sketch.
"""
import random
class PaymentServer:
def __init__(self, deduplicate):
self.deduplicate = deduplicate
self.charges = [] # every charge made: the order it was for
self.done = {} # idempotency key -> charge id, when deduplicating
def charge(self, order, key):
if self.deduplicate and key in self.done:
return self.done[key] # a retry: the same answer, no new charge
self.charges.append(order)
charge_id = f"ch-{len(self.charges)}"
if self.deduplicate:
self.done[key] = charge_id
return charge_id
def pay(server, order, network, retries):
"""Try up to 1 + retries times; return True when a reply confirmed the payment."""
key = f"order-{order}" # the client picks one key per order and reuses it on every retry
for _ in range(1 + retries):
if network.random() < 0.02: # the request is lost: the server never sees it
continue
server.charge(order, key)
if network.random() < 0.03: # the charge happened, but the reply is lost
continue
return True
return False
print(f"{'strategy':28}{'charges':>8}{'charged 2+ times':>18}{'unconfirmed':>13}{'charged, but told no':>22}")
for name, retries, deduplicate in [
("no retry", 0, False),
("retry up to 3 times", 3, False),
("retry with idempotency key", 3, True),
]:
server, network = PaymentServer(deduplicate), random.Random(9)
confirmed = {order: pay(server, order, network, retries) for order in range(10_000)}
per_order = {}
for order in server.charges:
per_order[order] = per_order.get(order, 0) + 1
twice = sum(1 for n in per_order.values() if n > 1)
unconfirmed = sum(1 for ok in confirmed.values() if not ok)
charged_unconfirmed = sum(1 for order, ok in confirmed.items() if not ok and order in per_order)
print(f"{name:28}{len(server.charges):>8,}{twice:>18,}{unconfirmed:>13,}{charged_unconfirmed:>22,}") Output
strategy charges charged 2+ times unconfirmed charged, but told no no retry 9,802 0 503 305 retry up to 3 times 10,325 308 0 0 retry with idempotency key 10,000 0 0 0
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 unknown_outcome.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
- No retry leaves 503 orders unconfirmed. Of those, 305 were in fact charged: their replies were lost. Those customers paid and were told the payment failed.
- Retry up to 3 times confirms every order, but charges 308 customers twice or more, because a retry after a lost reply makes a second charge.
- Retry with an idempotency key makes exactly 10,000 charges. The client picks one key per order and sends it with every attempt; the server records the result under the key, and a repeat gets the stored result instead of a new charge.
An idempotency key turns “do this” into “do this once”, which is what makes retries safe. When even the retries run out, the key still lets a later process look the payment up and settle it, which is called reconciliation: Settling an operation whose outcome is unknown, such as a payment that timed out, by asking the system that did the work what happened to it, by its key, instead of guessing.: the client, or a background job, asks the server what happened to order 7 rather than guessing. The next lessons of this module build retries, timeouts and backoff on top of this.
Follow one of those retries: order 1 of the next program, whose first reply is lost.
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- Attempt 1. The client chose the key key-order-1 once, when the order was placed, and sends it with the first attempt.
- A new key. The server has never seen this key, so it charges the card as ch-1 and stores the result under the key before it replies.
- The reply is lost. The reply carrying ch-1 is lost on the way back. The customer has paid, but the client sees only a timeout.
- Attempt 2, same key. The client retries with the same key. A new key for each attempt would turn this retry into a second payment.
- The stored answer. The server finds key-order-1 among its keys and returns the stored ch-1 without charging the card again.
- Confirmed once. This time the reply arrives, and the order is confirmed as ch-1 with one charge. A retry without the key would have charged the card a second time, as ch-2.
The next program is the same server without the randomness. Two orders meet the same lost replies under each of the three clients, and the client with keys reconciles the order whose every reply was lost. Each tab holds the program in another language, and every one of the 14 printed the lines below the tabs:
Python 3.14 · main.py
class PaymentServer:
def __init__(self) -> None:
self.charges: list[str] = []
self.done: dict[str, str] = {} # idempotency key -> charge id
def charge(self, order: str, key: str | None) -> str:
if key is not None and key in self.done:
return self.done[key] # a repeat: the stored answer, no new charge
self.charges.append(order)
charge_id = f"ch-{len(self.charges)}"
if key is not None:
self.done[key] = charge_id
return charge_id
FATES = {"order-1": ["reply lost", "ok"], "order-2": ["reply lost"] * 4}
def pay(server: PaymentServer, order: str, attempts: int, keyed: bool) -> str:
key = f"key-{order}" if keyed else None # chosen once, sent with every attempt
for fate in FATES[order][:attempts]:
charge_id = server.charge(order, key)
if fate == "ok":
return f"confirmed {charge_id}"
return "timed out"
for name, attempts, keyed in [
("no retry", 1, False),
("retry 3 times", 4, False),
("retry with a key", 4, True),
]:
print(name)
server = PaymentServer()
for order in FATES:
outcome = pay(server, order, attempts, keyed)
print(f" {order} charges {server.charges.count(order)} {outcome}")
if keyed:
print(f" reconcile order-2 by its key: {server.done['key-order-2']}") In Python: The key is None when a client sends none, so the server stores and checks keys only for requests that carry one; list.count counts the charges of one order.
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
class PaymentServer {
charges = [];
done = new Map(); // idempotency key -> charge id
charge(order, key) {
if (key !== null && this.done.has(key)) {
return this.done.get(key); // a repeat: the stored answer, no new charge
}
this.charges.push(order);
const chargeId = `ch-${this.charges.length}`;
if (key !== null) this.done.set(key, chargeId);
return chargeId;
}
}
const FATES = new Map([
["order-1", ["reply lost", "ok"]],
["order-2", Array(4).fill("reply lost")],
]);
function pay(server, order, attempts, keyed) {
const key = keyed ? `key-${order}` : null; // chosen once, sent with every attempt
for (const fate of FATES.get(order).slice(0, attempts)) {
const chargeId = server.charge(order, key);
if (fate === "ok") return `confirmed ${chargeId}`;
}
return "timed out";
}
for (const [name, attempts, keyed] of [
["no retry", 1, false],
["retry 3 times", 4, false],
["retry with a key", 4, true],
]) {
console.log(name);
const server = new PaymentServer();
for (const order of FATES.keys()) {
const outcome = pay(server, order, attempts, keyed);
const charges = server.charges.filter((charged) => charged === order).length;
console.log(` ${order} charges ${charges} ${outcome}`);
}
if (keyed) console.log(` reconcile order-2 by its key: ${server.done.get("key-order-2")}`);
} In JavaScript: A Map holds the keys, and null stands for a request without a key; filter counts the charges of one order.
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.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
static final class PaymentServer {
final List<String> charges = new ArrayList<>();
final Map<String, String> done = new HashMap<>(); // idempotency key -> charge id
String charge(String order, String key) {
if (key != null && done.containsKey(key)) {
return done.get(key); // a repeat: the stored answer, no new charge
}
charges.add(order);
String chargeId = "ch-" + charges.size();
if (key != null) {
done.put(key, chargeId);
}
return chargeId;
}
}
static final Map<String, List<String>> FATES = new LinkedHashMap<>();
static {
FATES.put("order-1", List.of("reply lost", "ok"));
FATES.put("order-2", Collections.nCopies(4, "reply lost"));
}
static String pay(PaymentServer server, String order, int attempts, boolean keyed) {
String key = keyed ? "key-" + order : null; // chosen once, sent with every attempt
List<String> fates = FATES.get(order);
for (String fate : fates.subList(0, Math.min(attempts, fates.size()))) {
String chargeId = server.charge(order, key);
if (fate.equals("ok")) {
return "confirmed " + chargeId;
}
}
return "timed out";
}
record Strategy(String name, int attempts, boolean keyed) {}
public static void main(String[] args) {
List<Strategy> strategies =
List.of(
new Strategy("no retry", 1, false),
new Strategy("retry 3 times", 4, false),
new Strategy("retry with a key", 4, true));
for (Strategy strategy : strategies) {
System.out.println(strategy.name());
PaymentServer server = new PaymentServer();
for (String order : FATES.keySet()) {
String outcome = pay(server, order, strategy.attempts(), strategy.keyed());
int charges = Collections.frequency(server.charges, order);
System.out.println(" " + order + " charges " + charges + " " + outcome);
}
if (strategy.keyed()) {
System.out.println(" reconcile order-2 by its key: " + server.done.get("key-order-2"));
}
}
}
} In Java: A request without a key passes null, Collections.frequency counts the charges of one order, and the LinkedHashMap keeps the orders in the order they were added.
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 <algorithm>
#include <map>
#include <optional>
#include <print>
#include <ranges>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
struct PaymentServer {
std::vector<std::string> charges{};
std::map<std::string, std::string> done{}; // idempotency key -> charge id
std::string charge(const std::string &order,
const std::optional<std::string> &key) {
if (key && done.contains(*key)) {
return done.at(*key); // a repeat: the stored answer, no new charge
}
charges.push_back(order);
const std::string chargeId = "ch-" + std::to_string(charges.size());
if (key) {
done[*key] = chargeId;
}
return chargeId;
}
};
const std::vector<std::pair<std::string, std::vector<std::string>>> FATES = {
{"order-1", {"reply lost", "ok"}},
{"order-2", std::vector<std::string>(4, "reply lost")},
};
std::string pay(PaymentServer &server, const std::string &order,
const std::vector<std::string> &fates, int attempts,
bool keyed) {
// The key is chosen once and sent with every attempt.
const auto key = keyed ? std::optional("key-" + order) : std::nullopt;
for (const auto &fate : fates | std::views::take(attempts)) {
const std::string chargeId = server.charge(order, key);
if (fate == "ok") {
return "confirmed " + chargeId;
}
}
return "timed out";
}
int main() {
const std::vector<std::tuple<std::string, int, bool>> strategies = {
{"no retry", 1, false},
{"retry 3 times", 4, false},
{"retry with a key", 4, true},
};
for (const auto &[name, attempts, keyed] : strategies) {
std::println("{}", name);
PaymentServer server;
for (const auto &[order, fates] : FATES) {
const std::string outcome = pay(server, order, fates, attempts, keyed);
std::println(" {} charges {} {}", order,
std::ranges::count(server.charges, order), outcome);
}
if (keyed) {
std::println(" reconcile order-2 by its key: {}",
server.done.at("key-order-2"));
}
}
} In C++: std::optional<std::string> is the key a request may carry, views::take(attempts) stops the loop after the client's attempts, and std::ranges::count counts one order's charges.
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
(string Order, string[] Fates)[] fates =
[
("order-1", ["reply lost", "ok"]),
("order-2", Enumerable.Repeat("reply lost", 4).ToArray()),
];
(string Name, int Attempts, bool Keyed)[] strategies =
[
("no retry", 1, false),
("retry 3 times", 4, false),
("retry with a key", 4, true),
];
foreach (var (name, attempts, keyed) in strategies)
{
Console.WriteLine(name);
var server = new PaymentServer();
foreach (var (order, orderFates) in fates)
{
string outcome = Pay(server, order, orderFates, attempts, keyed);
int charges = server.Charges.Count(charged => charged == order);
Console.WriteLine($" {order} charges {charges} {outcome}");
}
if (keyed)
{
Console.WriteLine($" reconcile order-2 by its key: {server.Done["key-order-2"]}");
}
}
static string Pay(PaymentServer server, string order, string[] fates, int attempts, bool keyed)
{
string? key = keyed ? $"key-{order}" : null; // chosen once, sent with every attempt
foreach (string fate in fates.Take(attempts))
{
string chargeId = server.Charge(order, key);
if (fate == "ok")
{
return $"confirmed {chargeId}";
}
}
return "timed out";
}
sealed class PaymentServer
{
public List<string> Charges { get; } = [];
public Dictionary<string, string> Done { get; } = new(); // idempotency key -> charge id
public string Charge(string order, string? key)
{
if (key is not null && Done.TryGetValue(key, out string? stored))
{
return stored; // a repeat: the stored answer, no new charge
}
Charges.Add(order);
string chargeId = $"ch-{Charges.Count}";
if (key is not null)
{
Done[key] = chargeId;
}
return chargeId;
}
} In C#: string? is a key that may be missing, TryGetValue looks it up once, and Take(attempts) stops the loop after the client's attempts.
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 { ORDERS = 2, NO_KEY = 0 };
typedef struct {
int made; // charges made in all
int charged[ORDERS + 1]; // charges made for each order
int done[ORDERS + 1]; // idempotency key -> charge id (0: none)
} PaymentServer;
static int charge(PaymentServer *server, int order, int key) {
if (key != NO_KEY && server->done[key] != 0) {
return server->done[key]; // a repeat: the stored answer, no new charge
}
server->charged[order]++;
if (key != NO_KEY) {
server->done[key] = server->made + 1;
}
return ++server->made;
}
static const char *const FATES[ORDERS + 1][5] = {
[1] = {"reply lost", "ok"},
[2] = {"reply lost", "reply lost", "reply lost", "reply lost"},
};
static int pay(PaymentServer *server, int order, int attempts, bool keyed) {
const int key =
keyed ? order : NO_KEY; // chosen once, sent with every attempt
for (int i = 0; i < attempts && FATES[order][i] != nullptr; i++) {
const int charge_id = charge(server, order, key);
if (strcmp(FATES[order][i], "ok") == 0) {
return charge_id;
}
}
return 0;
}
int main(void) {
static const struct {
const char *name;
int attempts;
bool keyed;
} strategies[] = {{"no retry", 1, false},
{"retry 3 times", 4, false},
{"retry with a key", 4, true}};
for (size_t s = 0; s < sizeof strategies / sizeof strategies[0]; s++) {
puts(strategies[s].name);
PaymentServer server = {};
for (int order = 1; order <= ORDERS; order++) {
const int confirmed =
pay(&server, order, strategies[s].attempts, strategies[s].keyed);
printf(" order-%d charges %d ", order, server.charged[order]);
if (confirmed != 0) {
printf("confirmed ch-%d\n", confirmed);
} else {
puts("timed out");
}
}
if (strategies[s].keyed) {
printf(" reconcile order-2 by its key: ch-%d\n", server.done[2]);
}
}
return 0;
} In C: C has no map or growing list in its standard library, so the key of order n is the number n (0 for none), an array indexed by it holds the charge ids, and the server counts charges per order.
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);
final class PaymentServer
{
/** @var list<string> */
public array $charges = [];
/** @var array<string, string> idempotency key -> charge id */
public array $done = [];
public function charge(string $order, ?string $key): string
{
if ($key !== null && isset($this->done[$key])) {
return $this->done[$key]; // a repeat: the stored answer, no new charge
}
$this->charges[] = $order;
$chargeId = 'ch-' . count($this->charges);
if ($key !== null) {
$this->done[$key] = $chargeId;
}
return $chargeId;
}
}
const FATES = [
'order-1' => ['reply lost', 'ok'],
'order-2' => ['reply lost', 'reply lost', 'reply lost', 'reply lost'],
];
function pay(PaymentServer $server, string $order, int $attempts, bool $keyed): string
{
$key = $keyed ? "key-{$order}" : null; // chosen once, sent with every attempt
foreach (array_slice(FATES[$order], 0, $attempts) as $fate) {
$chargeId = $server->charge($order, $key);
if ($fate === 'ok') {
return "confirmed {$chargeId}";
}
}
return 'timed out';
}
$strategies = [
['no retry', 1, false],
['retry 3 times', 4, false],
['retry with a key', 4, true],
];
foreach ($strategies as [$name, $attempts, $keyed]) {
echo "{$name}\n";
$server = new PaymentServer();
foreach (array_keys(FATES) as $order) {
$outcome = pay($server, $order, $attempts, $keyed);
$charges = count(array_keys($server->charges, $order, true));
echo " {$order} charges {$charges} {$outcome}\n";
}
if ($keyed) {
echo " reconcile order-2 by its key: {$server->done['key-order-2']}\n";
}
} In PHP: ?string is a key that may be null, isset tests whether it was stored, and array_keys with strict comparison finds the charges of one order.
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::HashMap;
#[derive(Default)]
struct PaymentServer {
charges: Vec<String>,
done: HashMap<String, String>, // idempotency key -> charge id
}
impl PaymentServer {
fn charge(&mut self, order: &str, key: Option<&str>) -> String {
if let Some(stored) = key.and_then(|k| self.done.get(k)) {
return stored.clone(); // a repeat: the stored answer, no new charge
}
self.charges.push(order.to_string());
let charge_id = format!("ch-{}", self.charges.len());
if let Some(k) = key {
self.done.insert(k.to_string(), charge_id.clone());
}
charge_id
}
}
const FATES: [(&str, &[&str]); 2] = [
("order-1", &["reply lost", "ok"]),
("order-2", &["reply lost"; 4]),
];
fn pay(
server: &mut PaymentServer,
order: &str,
fates: &[&str],
attempts: usize,
keyed: bool,
) -> String {
let key = keyed.then(|| format!("key-{order}")); // chosen once, sent with every attempt
for &fate in fates.iter().take(attempts) {
let charge_id = server.charge(order, key.as_deref());
if fate == "ok" {
return format!("confirmed {charge_id}");
}
}
"timed out".to_string()
}
fn main() {
let strategies = [
("no retry", 1, false),
("retry 3 times", 4, false),
("retry with a key", 4, true),
];
for (name, attempts, keyed) in strategies {
println!("{name}");
let mut server = PaymentServer::default();
for (order, fates) in FATES {
let outcome = pay(&mut server, order, fates, attempts, keyed);
let charges = server.charges.iter().filter(|c| *c == order).count();
println!(" {order} charges {charges} {outcome}");
}
if keyed {
println!(
" reconcile order-2 by its key: {}",
server.done["key-order-2"]
);
}
}
} In Rust: Option<&str> is the key a request may carry, and and_then looks it up only when there is one; keyed.then(...) builds the key only for the client that sends it.
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
class PaymentServer {
readonly charges: string[] = [];
readonly done = new Map<string, string>(); // idempotency key -> charge id
charge(order: string, key: string | null): string {
const stored = key === null ? undefined : this.done.get(key);
if (stored !== undefined) return stored; // a repeat: the stored answer, no new charge
this.charges.push(order);
const chargeId = `ch-${this.charges.length}`;
if (key !== null) this.done.set(key, chargeId);
return chargeId;
}
}
type Fate = "ok" | "reply lost";
const FATES = new Map<string, Fate[]>([
["order-1", ["reply lost", "ok"]],
["order-2", Array<Fate>(4).fill("reply lost")],
]);
function pay(server: PaymentServer, order: string, attempts: number, keyed: boolean): string {
const key = keyed ? `key-${order}` : null; // chosen once, sent with every attempt
for (const fate of (FATES.get(order) ?? []).slice(0, attempts)) {
const chargeId = server.charge(order, key);
if (fate === "ok") return `confirmed ${chargeId}`;
}
return "timed out";
}
const STRATEGIES: [string, number, boolean][] = [
["no retry", 1, false],
["retry 3 times", 4, false],
["retry with a key", 4, true],
];
for (const [name, attempts, keyed] of STRATEGIES) {
console.log(name);
const server = new PaymentServer();
for (const order of FATES.keys()) {
const outcome = pay(server, order, attempts, keyed);
const charges = server.charges.filter((charged) => charged === order).length;
console.log(` ${order} charges ${charges} ${outcome}`);
}
if (keyed) console.log(` reconcile order-2 by its key: ${server.done.get("key-order-2")}`);
} In TypeScript: The key is string | null and the fates are a union type, so a misspelt fate is a compile error; 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"
type PaymentServer struct {
made int // charges made in all
charged map[string]int // charges made for each order
done map[string]string // idempotency key -> charge id
}
func (s *PaymentServer) charge(order string, key *string) string {
if key != nil {
if stored, ok := s.done[*key]; ok {
return stored // a repeat: the stored answer, no new charge
}
}
s.made++
s.charged[order]++
chargeID := fmt.Sprintf("ch-%d", s.made)
if key != nil {
s.done[*key] = chargeID
}
return chargeID
}
var orders = []string{"order-1", "order-2"}
var fates = map[string][]string{
"order-1": {"reply lost", "ok"},
"order-2": {"reply lost", "reply lost", "reply lost", "reply lost"},
}
func pay(server *PaymentServer, order string, attempts int, keyed bool) string {
var key *string // chosen once, sent with every attempt
if keyed {
k := "key-" + order
key = &k
}
for _, fate := range fates[order][:min(attempts, len(fates[order]))] {
chargeID := server.charge(order, key)
if fate == "ok" {
return "confirmed " + chargeID
}
}
return "timed out"
}
func main() {
strategies := []struct {
name string
attempts int
keyed bool
}{{"no retry", 1, false}, {"retry 3 times", 4, false}, {"retry with a key", 4, true}}
for _, s := range strategies {
fmt.Println(s.name)
server := &PaymentServer{charged: map[string]int{}, done: map[string]string{}}
for _, order := range orders {
outcome := pay(server, order, s.attempts, s.keyed)
fmt.Printf(" %s charges %d %s\n", order, server.charged[order], outcome)
}
if s.keyed {
fmt.Println(" reconcile order-2 by its key:", server.done["key-order-2"])
}
}
} In Go: A nil *string is a request without a key, and the server keeps a map of charges per order, since the standard library has no function that counts a value in a slice.
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
final class PaymentServer {
private(set) var charges: [String] = []
private(set) var done: [String: String] = [:] // idempotency key -> charge id
func charge(order: String, key: String?) -> String {
if let key, let stored = done[key] {
return stored // a repeat: the stored answer, no new charge
}
charges.append(order)
let chargeID = "ch-\(charges.count)"
if let key {
done[key] = chargeID
}
return chargeID
}
}
let fates: KeyValuePairs = [
"order-1": ["reply lost", "ok"],
"order-2": Array(repeating: "reply lost", count: 4),
]
func pay(server: PaymentServer, order: String, fates: [String], attempts: Int, keyed: Bool)
-> String
{
let key = keyed ? "key-\(order)" : nil // chosen once, sent with every attempt
for fate in fates.prefix(attempts) {
let chargeID = server.charge(order: order, key: key)
if fate == "ok" {
return "confirmed \(chargeID)"
}
}
return "timed out"
}
let strategies = [
(name: "no retry", attempts: 1, keyed: false),
(name: "retry 3 times", attempts: 4, keyed: false),
(name: "retry with a key", attempts: 4, keyed: true),
]
for strategy in strategies {
print(strategy.name)
let server = PaymentServer()
for (order, orderFates) in fates {
let outcome = pay(
server: server, order: order, fates: orderFates, attempts: strategy.attempts,
keyed: strategy.keyed)
print(" \(order) charges \(server.charges.filter { $0 == order }.count) \(outcome)")
}
if strategy.keyed {
print(" reconcile order-2 by its key: \(server.done["key-order-2"] ?? "no charge")")
}
} In Swift: String? is the key a request may carry, if let key, let stored = done[key] unwraps both in one condition, and KeyValuePairs keeps the orders in order.
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
# A payment server that answers a repeated idempotency key with the stored charge.
class PaymentServer
attr_reader :charges, :done
def initialize
@charges = []
@done = {} # idempotency key -> charge id
end
def charge(order, key)
# A repeat gets the stored answer, no new charge.
return @done[key] if key && @done.key?(key)
@charges << order
charge_id = "ch-#{@charges.size}"
@done[key] = charge_id if key
charge_id
end
end
FATES = { 'order-1' => ['reply lost', 'ok'], 'order-2' => ['reply lost'] * 4 }.freeze
def pay(server, order, attempts, keyed)
key = keyed ? "key-#{order}" : nil # chosen once, sent with every attempt
FATES[order].first(attempts).each do |fate|
charge_id = server.charge(order, key)
return "confirmed #{charge_id}" if fate == 'ok'
end
'timed out'
end
[['no retry', 1, false], ['retry 3 times', 4, false],
['retry with a key', 4, true]].each do |name, attempts, keyed|
puts name
server = PaymentServer.new
FATES.each_key do |order|
outcome = pay(server, order, attempts, keyed)
puts " #{order} charges #{server.charges.count(order)} #{outcome}"
end
puts " reconcile order-2 by its key: #{server.done['key-order-2']}" if keyed
end In Ruby: nil is a request without a key, first(attempts) stops the loop after the client's attempts, and Array#count counts the charges of one order.
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
class PaymentServer {
val charges = mutableListOf<String>()
val done = mutableMapOf<String, String>() // idempotency key -> charge id
fun charge(
order: String,
key: String?,
): String {
val stored = key?.let { done[it] }
if (stored != null) {
return stored // a repeat: the stored answer, no new charge
}
charges.add(order)
val chargeId = "ch-${charges.size}"
if (key != null) {
done[key] = chargeId
}
return chargeId
}
}
val fates =
linkedMapOf(
"order-1" to listOf("reply lost", "ok"),
"order-2" to List(4) { "reply lost" },
)
fun pay(
server: PaymentServer,
order: String,
attempts: Int,
keyed: Boolean,
): String {
val key = if (keyed) "key-$order" else null // chosen once, sent with every attempt
for (fate in fates.getValue(order).take(attempts)) {
val chargeId = server.charge(order, key)
if (fate == "ok") return "confirmed $chargeId"
}
return "timed out"
}
fun main() {
val strategies =
listOf(
Triple("no retry", 1, false),
Triple("retry 3 times", 4, false),
Triple("retry with a key", 4, true),
)
for ((name, attempts, keyed) in strategies) {
println(name)
val server = PaymentServer()
for (order in fates.keys) {
val outcome = pay(server, order, attempts, keyed)
println(" $order charges ${server.charges.count { it == order }} $outcome")
}
if (keyed) println(" reconcile order-2 by its key: ${server.done["key-order-2"]}")
}
} In Kotlin: String? is a key that may be missing, key?.let looks it up only when there is one, and take(attempts) stops the loop after the client's attempts.
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
class PaymentServer {
final charges = <String>[];
final done = <String, String>{}; // idempotency key -> charge id
String charge(String order, String? key) {
final stored = key == null ? null : done[key];
if (stored != null) {
return stored; // a repeat: the stored answer, no new charge
}
charges.add(order);
final chargeId = 'ch-${charges.length}';
if (key != null) done[key] = chargeId;
return chargeId;
}
}
final fates = {
'order-1': ['reply lost', 'ok'],
'order-2': List.filled(4, 'reply lost'),
};
String pay(PaymentServer server, String order, int attempts, bool keyed) {
// The key is chosen once and sent with every attempt.
final key = keyed ? 'key-$order' : null;
for (final fate in fates[order]!.take(attempts)) {
final chargeId = server.charge(order, key);
if (fate == 'ok') return 'confirmed $chargeId';
}
return 'timed out';
}
void main() {
const strategies = [
('no retry', 1, false),
('retry 3 times', 4, false),
('retry with a key', 4, true),
];
for (final (name, attempts, keyed) in strategies) {
print(name);
final server = PaymentServer();
for (final order in fates.keys) {
final outcome = pay(server, order, attempts, keyed);
final charges = server.charges
.where((charged) => charged == order)
.length;
print(' $order charges $charges $outcome');
}
if (keyed) {
print(' reconcile order-2 by its key: ${server.done['key-order-2']}');
}
}
} In Dart: String? is a key that may be null, the ! in fates[order]! says that every order has its fates, and where(...).length counts the charges of one order.
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
no retry order-1 charges 1 timed out order-2 charges 1 timed out retry 3 times order-1 charges 2 confirmed ch-2 order-2 charges 4 timed out retry with a key order-1 charges 1 confirmed ch-1 order-2 charges 1 timed out reconcile order-2 by its key: ch-2
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 13 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 155 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 3 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 30 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 719 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 193 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 15 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
Order 1 is the double charge in miniature: its first reply is lost, the plain retry charges the card again as ch-2, and the key returns the first charge, ch-1. Order 2 never gets a reply in four attempts. Without a key it is charged four times, and the client learns of none of them; with a key it is charged once, and the lookup by its key finds ch-2. The client that never retries shows the other mistake: both of its orders were charged and both report a timeout.
UUID Generator Generate random UUIDs to use as idempotency keys, one per logical operation.Key idea
An idempotency key, chosen once per operation and sent with every attempt, turns “do this” into “do this once”: the server answers a repeat with the stored result, and the same key lets anyone look the outcome up later.
Checkpoint
Check: Idempotency keys and reconciliation
Gray failures: healthy to the checker, broken for users
A gray failure is a component that is failing for the people who use it while the system’s own failure detectors see it as healthy. Huang and colleagues, writing from experience with large cloud systems, argue that this differential observability is the defining trait of gray failures, and that subtle faults of this kind, rather than clean crashes, cause many of the worst outages: a crash is detected and handled, a half-working component is not. Their example is a server whose request-handling module is stuck while its heartbeat module still runs, so every check that relies on heartbeats reports it as healthy.
// A gray failure: the health checks stay green while users fail. A checkout service has a shallow health check
// (is the process up?) and a deep one (can it reach its database?). From minute 4, the path to one of its three
// pricing shards breaks, so checkouts for customers on that shard fail. The workload is an assumption.
function generator(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = Math.imul(a ^ (a >>> 15), a | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const random = generator(17);
const service = {
brokenShard: null, // which pricing shard is unreachable, if any
shallowHealth: () => "200 ok", // the process answers
deepHealth: () => "200 ok", // the database answers SELECT 1
checkout(customer) {
const shard = customer % 3; // customers are spread over three pricing shards
if (shard === this.brokenShard) return "503 pricing unavailable";
return random() < 0.001 ? "500 error" : "200 paid";
},
};
console.log("minute shallow check deep check checkouts succeeded alarm on success rate < 99%");
for (let minute = 1; minute <= 8; minute++) {
if (minute === 4) service.brokenShard = 2;
let ok = 0;
const requests = 600;
for (let i = 0; i < requests; i++) {
const customer = Math.floor(random() * 90000);
if (service.checkout(customer).startsWith("200")) ok += 1;
}
const rate = ok / requests;
const alarm = rate < 0.99 ? "FIRING" : "-";
console.log(
`${String(minute).padStart(6)} ${service.shallowHealth().padEnd(13)} ${service.deepHealth().padEnd(10)} ${String(requests).padStart(9)} ${(100 * rate).toFixed(1).padStart(8)}% ${alarm}`,
);
} Output
minute shallow check deep check checkouts succeeded alarm on success rate < 99%
1 200 ok 200 ok 600 100.0% -
2 200 ok 200 ok 600 100.0% -
3 200 ok 200 ok 600 99.7% -
4 200 ok 200 ok 600 67.3% FIRING
5 200 ok 200 ok 600 65.5% FIRING
6 200 ok 200 ok 600 68.8% FIRING
7 200 ok 200 ok 600 67.3% FIRING
8 200 ok 200 ok 600 69.5% FIRING
Recorded with Node.js 24.21.0 on macOS 26 arm64. To run it yourself: mise exec node@24.21.0 -- node gray_failure.mjs
Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs.
Your run, in this browser
From minute 4, one of the service’s three pricing shards is unreachable, so about a third of checkouts fail. The shallow health check only asks whether the process answers, and the deep one only asks whether the database answers, so both stay at “200 ok” while the success rate drops to between 65% and 70%. Only the measurement of what users actually get, the share of successful checkouts, raises the alarm. The paper’s advice is to move from a single failure detector, such as a heartbeat, to several signals of health, and to measure from where the applications stand; in practice that means alerting on user-facing success rates, the service level indicator (SLI): A measured quantity of a service's behaviour, such as request latency, error rate, throughput or availability. More in “Turning a vague prompt into requirements” of the previous lesson, and health checks that exercise the paths users depend on.
Step through minute 4 of the run, from the shard that breaks to the alarm that fires:
The drawing shows the whole scene; its 7 steps are listed below.
Every step as text
- Minutes 1 to 3. For three minutes the service is healthy. Between 99.7 % and 100 % of the 600 checkouts a minute succeed, and both health checks answer 200 ok.
- A shard breaks. At minute 4 the path to the third pricing shard breaks. Every checkout for a customer on that shard now fails with 503 pricing unavailable.
- The shallow check. The shallow check only asks whether the process answers. It does, so the check reports 200 ok.
- The deep check. The deep check asks whether the database answers SELECT 1. It does too, so the deeper check is green as well. Neither check touches the pricing shards.
- What users get. Customers on the broken shard, about a third of them, cannot pay. In the run, only 67.3 % of minute 4's checkouts succeed.
- The alarm fires. The alarm measures what users get, the share of successful checkouts, and it fires at once because 67.3 % is below 99 %.
- Two views. The checks say healthy and the users say broken. That gap between what the detectors see and what users see is what makes a failure gray.
Key idea
A gray failure is invisible to checks that look at the wrong thing: the process and the database answered while a third of checkouts failed, and only a measurement of what users got raised the alarm.
Checkpoint
Check: Gray failures
Metastable failures: when the fix keeps the failure going
Bronson, Aghayev, Charapko and Zhu describe a pattern behind widespread outages at large internet companies, some lasting hours: a metastable failure. A system runs in a vulnerable state, efficient and healthy, but with a hidden feedback loop. A trigger pushes it into a bad state, and a sustaining effect keeps it there even after the trigger is gone. Leaving the state takes a strong push, such as cutting the load sharply or changing the policy that feeds the loop.
Their first example is retries. A web application normally sends 280 queries a second to a database that answers quickly below 300 queries a second and much more slowly above it, and each user request retries a query that has not answered within a second. A 10-second network outage triggers a surge of queued requests and retries; the database slows, so queries time out and are retried, and the load stays at 560 queries a second, twice the real demand. The network has recovered, yet the system stays down until the load drops or the retry policy changes. The paper notes that outages like this are often blamed on the trigger, when the real root cause is the sustaining effect, and that the features creating the loop, retries, failover and caching, are often ones added for efficiency or reliability.
Step through the paper’s retry example, and watch the branch that turns back on itself:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- Vulnerable. The application sends the database 280 queries a second, and the database answers quickly below 300. The system is healthy and efficient, but each request retries a query that has not answered within a second.
- The trigger. A 10-second network outage holds requests back. When the network returns, the queued requests and their retries arrive in a surge.
- Past the edge. The surge pushes the database above 300 queries a second, where it is much slower, so queries start taking longer than a second.
- Retries double the load. Every query that has not answered within a second is retried. The database now receives 560 queries a second, twice the real demand.
- The loop. The extra load keeps the database slow, so queries keep timing out and keep being retried. The network recovered long ago, yet the system stays down.
- The way out. Only a strong push breaks the loop, such as cutting the load sharply or changing the retry policy. The root cause is the sustaining effect, the retries, not the outage that started it.
The defences are the subject of the rest of this module: retries with backoff and a budget, so that retries cannot double the load; circuit breakers that stop calling a failing dependency; load shedding, so that an overloaded service refuses work quickly instead of slowly failing all of it; and capacity tests that look for the load at which the system becomes vulnerable.
Key idea
A metastable failure outlives its trigger because the system’s own recovery work, here retries that double the load, keeps it overloaded; the fix is to break that loop, not to wait for the trigger to pass.
Checkpoint
Check: Metastable failures
Design for the failures that happen
- Put a timeout on every remote call, and treat a timeout as an unknown outcome, not a failure.
- Make every operation that changes state idempotent, with a key chosen by the caller, so retries are safe.
- Reconcile what timed out: look outcomes up by key rather than guessing.
- Alert on what users get (success rates and latency at the edge), not only on health checks.
- Make health checks exercise real dependencies, and keep the action they trigger proportionate: a check that removes every server when a shared dependency fails turns a partial failure into a total one.
- Give retries, failovers and other recovery actions a budget, so they cannot become the sustaining effect.
- Assume crash-recovery faults inside your organisation, and design for Byzantine faults only where participants do not trust each other.
The same rules, sorted by the failure each one answers and by what that failure looks like from outside:
| Failure | What you see | The first defence |
|---|---|---|
| A lost request or reply | A timeout, with the outcome unknown | Idempotency keys, retries and reconciliation |
| A slow node or a long pause | A reply after the timeout | Timeouts, and protocols that tolerate delay |
| A gray failure | Green checks while users fail | Alarms on user-facing success rates |
| A metastable failure | Overload long after the trigger | A budget for retries and other recovery |
| A shared dependency fails | Every server failing its check at once | Checks whose action stays proportionate |
| A Byzantine fault | Wrong answers that look valid | Signatures, checksums, protocols that outvote liars |
Checkpoint
Check: Designing for the failures that happen
Practise: a payment server that charges once
Complete a payment server in Python that charges once per idempotency key, returns the first charge to a retry and refuses a key reused with another amount. Its sample tests run here:
Exercise · Medium · Python
A payment server that charges once per idempotency key
Complete PaymentServer.charge(key, amount) in payments.py, so that a client may safely retry a payment whose reply it never received.
- The first request with a new idempotency
keymakes a charge: it appendsamounttoself.chargesand returns a new charge id,"ch-1"for the first charge the server ever makes,"ch-2"for the second, and so on. - A request that repeats a
keywith the sameamountis a retry: it makes no new charge and returns the id of the original charge. - A request that repeats a
keywith a differentamountis a client bug, not a retry: raiseValueErrorand make no charge.
For example, charge("order-7", 500) twice returns "ch-1" both times and leaves charges as [500].
Starter code · payments.py
class PaymentServer:
"""A payment server that charges at most once per idempotency key."""
def __init__(self):
self.charges = [] # every amount actually charged, in order
self.seen = {} # idempotency key -> (charge id, amount)
def charge(self, key, amount):
"""Charge `amount` once for `key` and return the charge id; a retry returns the same id."""
# Replace this line with your code.
return "" The sample tests · test_payments.py
from payments import PaymentServer
def test_first_charge():
"""a new key makes a charge and returns a new id"""
server = PaymentServer()
assert server.charge("order-7", 500) == "ch-1"
assert server.charge("order-8", 120) == "ch-2"
assert server.charges == [500, 120]
def test_retry_charges_once():
"""a repeated key with the same amount returns the first id and charges nothing"""
server = PaymentServer()
first = server.charge("order-7", 500)
assert server.charge("order-7", 500) == first
assert server.charge("order-7", 500) == first
assert server.charges == [500]
def test_mismatched_amount():
"""a repeated key with another amount is refused and charges nothing"""
server = PaymentServer()
server.charge("order-7", 500)
try:
server.charge("order-7", 900)
refused = False
except ValueError:
refused = True
assert refused, "a different amount for the same key must raise ValueError"
assert server.charges == [500]
def test_ids_count_real_charges():
"""ids count the charges made, so retries do not use up numbers"""
server = PaymentServer()
server.charge("a", 1)
server.charge("a", 1)
assert server.charge("b", 2) == "ch-2" A hint
Keep a dictionary from each key to what it produced, for example self.seen[key] = (charge_id, amount). Look the key up before charging: if it is there, compare the amounts and either return the stored id or raise; if it is not, make the charge, store the result and return the new id. The id can come from the number of charges made so far.
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.
Then name the failure behind short incidents, one question at a time. The session starts with the idea you have missed most and gets harder as your answers come out right:
Practice that adapts to you
Practise this lesson
13 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Design practice: payments and green checks
A failure question in a design round usually starts from an incident. Decide on each brief before you look back, then test your choice on the payment programs and the checkout run above:
Checkpoint
Your first decision
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to senior
A payment call times out and the user clicks Pay again. How do you make sure the user is charged exactly once, even if the first request actually succeeded?
-
Mid to senior
Every health check is green, but users report that one page keeps failing. What kind of failure is this, how do you find the cause, and how do you detect it automatically next time?
Interview questions
Warm-up (fresher to mid level): what is a partial failure, and why does it make distributed systems harder than one machine? A partial failure is one in which some parts of a system fail while others keep working: one node crashes, one network link drops messages, one dependency slows down. On a single machine a failure usually stops the whole program, which is easy to notice. In a distributed system the working parts must carry on around the broken ones, and a caller often cannot tell which happened: a timed-out call may have failed, succeeded with a lost reply, or still be running. So every remote call needs a timeout, and every operation that changes state needs to be safe to retry.
Key takeaways
- A remote call can fail at eight points between client and server; a timeout means its outcome is unknown.
- Crash, omission, timing and Byzantine faults are increasingly hard to tolerate; internal services assume crash-recovery, multi-party systems Byzantine.
- Idempotency keys make retries safe: without them, retries after lost replies charge customers twice; without retries, customers are charged and told it failed.
- Gray failures pass health checks while users fail: alert on user-facing success rates.
- Metastable failures persist after their trigger because a feedback loop, often retries, sustains them; budget every recovery action.
Terms in this lesson
- Byzantine fault
- A fault in which a node does anything at all: wrong answers that look valid, lies, different stories to different peers. With unsigned messages, agreement then needs more than two thirds of the nodes to be honest.
- crash-recovery
- A fault model in which a node may stop and later restart with what it saved to disk but none of its memory. Most real services are crash-recovery; crash-stop nodes never come back.
- gray failure
- A failure that users see while the system's own failure detectors see a healthy component, such as a server whose request handling is stuck while its heartbeat still runs.
- idempotency key
- A unique id that a client chooses once for an operation and sends with every attempt of it. The server stores the result under the key, so a repeat gets the stored result instead of a second charge or write.
- metastable failure
- A bad state that lasts after its trigger has gone, because a feedback loop such as retries keeps the load high. Leaving it takes a strong push, such as cutting the load sharply or changing the retry policy.
- reconciliation
- Settling an operation whose outcome is unknown, such as a payment that timed out, by asking the system that did the work what happened to it, by its key, instead of guessing.
Corrections
- The metastable-failures section now says, as the paper does, that the features creating the loop are often, not usually, ones added for efficiency or reliability.
References
- Challenges with distributed systems (Amazon Builders' Library) (Amazon Web Services)
- Distributed Systems, lecture notes: system models (Martin Kleppmann) (University of Cambridge, Department of Computer Science and Technology)
- The Byzantine Generals Problem (Lamport, Shostak and Pease) (ACM Transactions on Programming Languages and Systems (via Microsoft Research))
- Gray Failure: The Achilles' Heel of Cloud-Scale Systems (HotOS 2017 (Microsoft Research))
- Metastable Failures in Distributed Systems (HotOS 2021 (ACM SIGOPS))
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress