Your country

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

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

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

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.

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

What you will learn

  • 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.

A remote call can fail on the way in, inside the server, or on the way back, and a timeout cannot tell which.Client sends'charge order 7'Networkthe request may be lost or lateServermay crash before or aftercharging the cardNetworkthe reply may be lost or lateClientreply, or a timeout:was the card charged?

One remote call, and the places it can fail

Text description of the diagram

The diagram follows one call from top to bottom.

  1. The client sends a request to charge order 7.
  2. The network carries it, and may lose or delay it.
  3. The server may crash before charging the card, or after charging it but before replying.
  4. The network carries the reply, and may lose or delay it.
  5. 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:

Interactive · message by message Three ways a call to charge order 7 ends in silence Step through the same call three times. Each time the client sees only a timeout; watch what really happened.
Three ways a call to charge order 7 ends in silence, step 6 of 6. Messages so far: Client to Network: charge order 7; Network to Payment server: charge order 7; Payment server to Network: charged: ch-1.Clientoutcome unknownNetworkPayment servercharges cardscharge order 7charge order 7charged: ch-1

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

Every step as text
  1. 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.
  2. The timer runs out. No reply arrives before the timer runs out, so the client sees a timeout. Here nothing happened at all.
  3. 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.
  4. A lost reply. Third world. The server charges the card and replies, but the network loses the reply on its way back.
  5. 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.
  6. 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

  1. Question 1 of 2 A call to charge order 7 times out. Which of these may have happened? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 1 of 2

    Answer:

    • The server crashed before it charged the card
    • The request never reached the server
    • The server charged the card, and the reply was lost

    A timeout means only that no reply arrived in time. The request may have been lost, the server may have crashed before acting, or it may have acted and lost its reply, and from the client's side the three look the same. That is why the outcome of a call that timed out is unknown.

  2. Question 2 of 2 A client charges cards over a network that loses 2 % of requests on the way in and 3 % of the replies of the requests that arrive. Of the calls that time out, about what share charged a card?

    Type a number.

    A hint

    Of 100 calls, count those lost on the way in, and those that arrived but lost their reply.

    Show the answer: Question 2 of 2

    Answer: 59.5 % (anything from 57.5 to 61.5 counts)

    Of 100 calls, 2 are lost on the way in and charge nothing. Of the 98 that arrive, 3 % lose their reply: about 2.94 calls that did charge a card. So about 2.94 of the 4.94 timeouts, roughly 60 %, charged a card. In the 10,000-order program below, 305 of the 503 unconfirmed orders had been charged, 61 %.

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:

Interactive · message by message What the caller sees under each fault model Step through one normal call, then the same call under a crash, an omission, a timing fault and a Byzantine fault.
What the caller sees under each fault model, step 6 of 6. Messages so far: Server to Client: balance 120; Client to Network: balance?; Server to Client: balance 120, 3 s late; Server to Client: balance 0.Clientwaits 2 s at mostNetworkServerfour ways to failbalance 120balance?balance 120, 3 s latebalance 0

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

Every step as text
  1. 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.
  2. 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.
  3. Omission. A congested switch drops the request. The server keeps working and would have answered correctly, but the client again hears nothing.
  4. 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.
  5. 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.
  6. 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

  1. Question 1 of 2 A cache node runs out of memory, is killed by the operating system and restarts a minute later with an empty cache. Which kind of fault is this?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A crash fault, in the crash-recovery model

    The node stopped and came back, losing what it held in memory, which is the crash-recovery model. Anything that depended on its memory, such as the cached data, has to be rebuilt.

  2. Question 2 of 2 A replica answers every query correctly, but long garbage-collection pauses make some replies arrive after the client's 2-second timeout. Which kind of fault is this?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A timing fault, because correct answers arrive too late

    The answers are right but late. The client cannot tell a paused node from a dead one, so its timeout treats the call as failed even though the replica will reply, and may already have acted.

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:

Paying for 10,000 orders over a lossy network, three ways Python · unknown-outcome/unknown_outcome.py
"""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

  • 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.

Interactive · message by message Order 1, a lost reply and a retry with the same key Step through order 1 of the program below, from the first attempt to the confirmed charge, and see what the key changes.
Order 1, a lost reply and a retry with the same key, step 6 of 6. Messages so far: Client to Payment server: charge, key-order-1; Payment server to Network: charged: ch-1; Client to Payment server: charge, key-order-1; Payment server to Client: charged: ch-1.Clientconfirmed ch-1, onceNetworkPayment serverkey-order-1: ch-1charge, key-order-1charged: ch-1charge, key-order-1charged: ch-1

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

Every step as text
  1. Attempt 1. The client chose the key key-order-1 once, when the order was placed, and sends it with the first attempt.
  2. 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.
  3. 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.
  4. 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.
  5. The stored answer. The server finds key-order-1 among its keys and returns the stored ch-1 without charging the card again.
  6. 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:

One program · 14 languages Two payments with lost replies, three clients

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

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

  1. Question 1 of 2 A client creates a new idempotency key for every attempt of the same payment. The first reply is lost, and the client retries. What happens?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The retry looks like a new payment, so the card is charged twice

    The key belongs to the operation, not to the attempt: it is chosen once, when the order is placed, and sent with every attempt. A fresh key per attempt turns the client back into the plain retrier of the program, which charged order 1 twice.

  2. Question 2 of 2 In the two-order program, order 2 got no reply in four attempts, under the client that retries with a key. What should the client do next?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Look the payment up by its key, which finds ch-2, and confirm the order

    When the retries run out, the outcome is still unknown to the client, but not to the server. Because every attempt carried the same key, one lookup by that key settles it: the server holds ch-2, so the order is paid, once.

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 checkout service whose health checks stay green while it fails JavaScript · gray-failure/gray_failure.mjs
// 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

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:

Interactive · step by step Minute 4 of the checkout service, as each check sees it Step through minute 4 of the program above. Compare what the two health checks report with what the users and the alarm see.
Minute 4 of the checkout service, as each check sees it, step 7 of 7. Showing Health checker, Users (67.3 % succeed), Success-rate alarm (FIRING: 67.3 %), Checkout service, Database, Pricing shard 3 (unreachable). In focus: Health checker, Users.GET /healthcheckoutswhat users getHealth checkershallow and deepUsers67.3 % succeedSuccess-rate alarmFIRING: 67.3 %Checkout serviceprocess upDatabaseanswers SELECT 1Pricing shard 3unreachable

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

Every step as text
  1. 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.
  2. 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.
  3. The shallow check. The shallow check only asks whether the process answers. It does, so the check reports 200 ok.
  4. 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.
  5. 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.
  6. 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 %.
  7. 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

  1. Question 1 of 2 Every host passes its health check, but 20% of users' uploads fail because one storage path is broken. What is this called?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A gray failure, because the failure detector sees health while users see failure

    The health check and the users observe different things, which the gray-failure paper calls differential observability. Measuring the success rate of real uploads, or a check that exercises the broken path, would have caught it.

  2. Question 2 of 2 In the checkout program, one of the three pricing shards becomes unreachable at minute 4, and customers are spread evenly over the shards. About what share of checkouts fail from then on?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 33.3 % (anything from 31.3 to 35.3 counts)

    Customers on one shard of three cannot pay, about a third of them, so roughly 33 % of checkouts fail. The run printed success rates between 65.5 % and 69.5 % from minute 4, while both health checks stayed at 200 ok, because neither of them touches the pricing shards.

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:

Interactive · stage by stage How retries keep a database down after the network recovers Step through the paper's retry example. Watch the branch that turns back on itself; it is the sustaining effect.
How retries keep a database down after the network recovers, step 6 of 6. Showing Vulnerable: 280 q/s, Trigger: 10 s outage, The database slows, Every query is retried, A strong push. In focus: A strong push.keeps it slowVulnerable: 280 q/sfast below 300 a secondTrigger: 10 s outagerequests and retries queueThe database slowsqueries pass 1 secondEvery query is retried560 queries a secondA strong pushcut the load or the retries

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

Every step as text
  1. 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.
  2. The trigger. A 10-second network outage holds requests back. When the network returns, the queued requests and their retries arrive in a surge.
  3. 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.
  4. 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.
  5. 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.
  6. 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

  1. Question 1 of 2 A 10-second network blip makes clients retry. The retries keep the database overloaded for an hour after the network recovered, until retries are switched off. What is this?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A metastable failure, because a feedback loop keeps the system down after the trigger is gone

    The trigger, the blip, lasted seconds; the sustaining effect, the extra load from retries, kept the database overloaded. A metastable failure ends only with a strong push, such as cutting the load or the retries.

  2. Question 2 of 2 An application sends 280 queries a second to a database that is fast below 300 a second, and retries once every query not answered within a second. After an outage slows the database, every query times out and is retried. How many queries a second does the database receive?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 560 queries a second

    Each of the 280 queries a second is sent twice, 560 in all: twice the real demand and far above the 300 the database handles quickly. So it stays slow, the queries keep timing out, and the retries continue. That loop is the sustaining effect.

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

  1. Question 1 of 2 Every server's load-balancer health check runs a query on the shared database. The database slows down for a minute. What happens?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Every server fails its check at once, and the balancer removes all of them, so a partial failure becomes a total one

    The lesson's rule is to keep the action a check triggers proportionate. A check that removes every server when a shared dependency fails turns a partial failure, a slow database, into a total one, with no server left to answer even the requests that never needed the database.

  2. Question 2 of 2 Your company's inventory service replicates its data across servers it owns and operates. Which fault model should its replication protocol be designed for?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Crash-recovery nodes, with lost, duplicated and late messages

    Services inside one organisation assume crash-recovery faults on a fair-loss network: nodes stop and restart, messages are lost, duplicated, reordered or late. Byzantine tolerance is for systems shared between parties who do not trust each other.

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 key makes a charge: it appends amount to self.charges and 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 key with the same amount is a retry: it makes no new charge and returns the id of the original charge.
  • A request that repeats a key with a different amount is a client bug, not a retry: raise ValueError and 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.

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.

  1. Question 1 of 13 A call to charge a card times out. What does the client know?

    Choose one answer.

    Show the answer: Question 1 of 13

    Answer: Nothing certain: the charge may have failed, succeeded with a lost reply, or still be running

    A timeout means no reply arrived in time, not that nothing happened. The safe response is to retry with the same idempotency key, or to look up the payment's status by that key, so the customer is charged once.

  2. Question 2 of 13 A client's call to create an order times out, and the client sends the same request again at once, without a key. The first request had in fact been processed. What is the result?

    Choose one answer.

    Show the answer: Question 2 of 13

    Answer: Two orders, because the server treats the second request as new

    Treating a timeout as a failure and simply sending again is how double charges and duplicate orders happen. The first request's work was done; only its reply was lost.

  3. Question 3 of 13 A switch between two racks drops about 1% of packets. Some calls never get a reply and time out; retried, they succeed. Which kind of fault is this?

    Choose one answer.

    Show the answer: Question 3 of 13

    Answer: An omission fault, because messages are lost

    Messages that should arrive do not. The switch keeps working, so nothing crashed, and what does arrive is correct, so nothing is arbitrary. Retries with idempotent requests turn such lossy links into reliable ones.

  4. Question 4 of 13 A server with a faulty memory chip returns corrupted account balances while reporting success. Which kind of fault is this?

    Choose one answer.

    Show the answer: Question 4 of 13

    Answer: An arbitrary (Byzantine) fault, because the server gives wrong answers that look right

    The node does not stop or go silent: it says something false as if it were true. Systems that assume only crashes do not defend against this, which is why storage systems add checksums to detect corruption.

  5. Question 5 of 13 In a ledger shared by several companies, one participant sends different lists of transactions to different peers. Which fault model must the protocol tolerate?

    Choose one answer.

    Show the answer: Question 5 of 13

    Answer: Byzantine faults, because a participant may deviate from the protocol on purpose

    When participants do not trust each other, one may lie, and differently to different peers. Lamport, Shostak and Pease showed that with plain messages, agreement then needs more than two thirds of the participants to be honest. Services inside one company usually assume crash-recovery faults instead.

  6. Question 6 of 13 In the two-order program, how many times was order 1 charged by the client that never retries, by the one that retries without a key, and by the one with a key?

    Choose one answer.

    Show the answer: Question 6 of 13

    Answer: 1, 2 and 1

    Order 1's first reply is lost. The client that never retries has charged it once but reports a timeout; the plain retrier charges it twice; the client with a key charges it once and gets ch-1 confirmed.

  7. Question 7 of 13 A payment server receives a request whose idempotency key it has already stored, but with a different amount from the first request. What should it do?

    Choose one answer.

    Show the answer: Question 7 of 13

    Answer: Refuse it as a client error and make no charge

    The key names one operation with one request. A repeat with the same request gets the stored result; the same key with different content is refused, which is also what the lesson's exercise asks for.

  8. Question 8 of 13 A server's request-handling module is stuck, but its heartbeat module still runs. What does a failure detector that relies on heartbeats report?

    Choose one answer.

    Show the answer: Question 8 of 13

    Answer: That the server is healthy

    This is the gray-failure paper's own example: the detector watches one signal, heartbeats, while users depend on another, request handling, so the detector sees health while users see failure.

  9. Question 9 of 13 Which signal would have caught the checkout program's failure at minute 4 soonest, with no change to the health checks?

    Choose one answer.

    Show the answer: Question 9 of 13

    Answer: The success rate of real checkouts, measured where the users' requests arrive

    A gray failure is caught by measuring what users get: the share of successful checkouts dropped from about 100 % to 67.3 % and the alarm on it fired at once. The paper's advice is several health signals, measured from where the applications stand.

  10. Question 10 of 13 After an outage like the paper's retry example, the postmortem names the 10-second network blip as the root cause. What does it miss?

    Choose one answer.

    Show the answer: Question 10 of 13

    Answer: That the retries sustained the overload after the blip ended, so they are the real root cause

    The paper notes that metastable outages are often blamed on the trigger, when the root cause is the sustaining effect. Fixing the network does nothing for the next trigger; budgeting the retries does.

  11. Question 11 of 13 The database of the paper's example is stuck at 560 queries a second long after the network recovered. Which action ends the failure?

    Choose one answer.

    Show the answer: Question 11 of 13

    Answer: Switch the retries off, or cut the load sharply, until the database is fast again

    Leaving a metastable state takes a strong push, such as cutting the load sharply or changing the policy that feeds the loop. Once the database is fast again, queries stop timing out, and normal load stays below its limit.

  12. Question 12 of 13 What should a service's main alarm measure, by the lesson's rules?

    Choose one answer.

    Show the answer: Question 12 of 13

    Answer: What users get, such as success rates and latency at the edge

    Alert on what users get, the success rate and latency of their requests measured as close to them as you can, and keep health checks for routing decisions.

  13. Question 13 of 13 Why should retries, failovers and other recovery actions get a budget?

    Choose one answer.

    Show the answer: Question 13 of 13

    Answer: So that they cannot become the sustaining effect that keeps a system overloaded

    Features added for reliability, such as retries and failover, are the usual feedback loops of metastable failures. A budget, a cap on how much extra work they may add, keeps them helpful for blips and harmless during long faults.

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

  1. Question 1 of 2 Design brief: a mobile app's Pay call times out after 5 seconds, and the product team wants the app to send the charge again at once. What is your first decision?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Give each payment an idempotency key, created once and sent with every attempt, so a second send returns the first result

    The resend is the right idea only once it is safe. A key chosen once per payment makes the server answer a repeat with the first result, and it gives the app a way to look up a payment whose replies were all lost.

  2. Question 2 of 2 Design brief: every health check of an upload service is green, but support reports that one upload in five fails. Where do you look first?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: At what users get, the success rate of real uploads, split until the failing part shows itself

    A gray failure is found from the users' side: the error rate of the failing journey, split by host, zone, dependency and customer group until the failing slice shows. The health checks are the part that cannot see it.

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

  1. 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?

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

  2. Mid to senior

    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?

    Model answer, Pro. First step and follow-ups

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

Related tools

Report a problem with this lesson

Quick answers and tool search

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