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

Circuit breakers, bulkheads and shuffle sharding

How circuit breakers fail fast, how bulkheads stop one slow dependency from taking every thread, and how shuffle sharding contains one bad client.

  • 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

  • Explain the closed, open and half-open states of a circuit breaker and what moves a breaker between them
  • Size a bulkhead with Little's law so that one slow dependency can fill only its own share of threads
  • Calculate how shuffle sharding shrinks the share of customers that one bad client can affect
  • Choose between a breaker, a bulkhead, shuffle sharding and a retry budget for a given failure

Before you start

What you’ll learn · Before you start

What you will learn

  • Explain the closed, open and half-open states of a circuit breaker and what moves a breaker between them
  • Size a bulkhead with Little's law so that one slow dependency can fill only its own share of threads
  • Calculate how shuffle sharding shrinks the share of customers that one bad client can affect
  • Choose between a breaker, a bulkhead, shuffle sharding and a retry budget for a given failure

Before you start

On this page

A dependency that starts to hang can hold all 200 threads of a web server within two seconds. Three tools stop one failing part from taking everything around it down. A circuit breaker: A proxy around calls to a dependency that stops sending them for a while once too many fail: callers fail fast instead of waiting, and after a timer a few trial calls decide whether it closes again. watches the calls to a dependency and, once too many of them fail, stops sending them for a while: callers fail fast instead of waiting, and the dependency gets room to recover. A bulkhead: A separate, limited share of threads, connections or queue slots for one dependency or one tenant, so that a slow or broken one can use up only its own share and not everyone's. gives each dependency, or each tenant, its own limited share of threads, connections or queue slots, so a slow one can fill only its own share. shuffle sharding: Giving each customer its own small, random set of workers from a shared fleet, so that two customers rarely share all of their workers and one customer's bad requests reach few others. More in “Cells, deployment stamps and blast radius” gives every customer a small random set of servers out of a larger fleet, so a customer whose requests break servers reaches only a few of them, and almost no other customer depends on exactly those few. All three answer the same failure: a shared resource used up by one bad part.

The sections below measure that failure first, then build each tool with the numbers that size it.

One slow dependency can take every thread

Take a web server with 200 worker threads and three endpoints, each calling its own dependency: search, at 300 requests a second with calls of about 20 ms; profiles, at 200 a second and 30 ms; and recommendations, at 100 a second and 40 ms. By Little’s law, the calls in flight are the rate times the time each takes, so on a normal day they hold 6 + 6 + 4 = 16 threads, a twelfth of the pool. Now the recommendations dependency starts to hang, and every call to it waits for its 5-second timeout. The same law says it now wants 100 × 5 = 500 threads. There are 200, so within about two seconds every thread is waiting on recommendations, and requests for search and profiles, which never call that dependency, find no thread to run on.

The simulation below runs exactly this, with seeded random arrivals, for 30 seconds; the hang starts at 10 seconds. It compares the shared pool with two of this lesson’s tools.

One hanging dependency, three designs Python · bulkhead-sim/bulkhead_sim.py
# One web server with 200 worker threads serves three endpoints, each calling its own dependency. At 10 s the
# recommendations dependency starts hanging: every call waits for the 5 s timeout and then fails. What happens to the
# two endpoints that never call it? Three designs, the same seeded traffic, 30 simulated seconds in steps of 1 ms.
import heapq
import random
from collections import deque

POOL = 200
TIMEOUT_MS = 5_000
SLOW_FROM, END = 10_000, 30_000
# endpoint: requests per millisecond, mean latency of its dependency in ms
ENDPOINTS = {"search": (0.3, 20), "profile": (0.2, 30), "recommendations": (0.1, 40)}


class Breaker:
    """Opens when half of the last 20 calls failed; after 5 s it lets 3 trial calls through."""

    def __init__(self):
        self.state, self.results, self.opened_at, self.trials = "closed", deque(maxlen=20), 0, 0

    def allow(self, now):
        if self.state == "open" and now - self.opened_at >= 5_000:
            self.state, self.trials = "half-open", 0
        if self.state == "closed":
            return True
        if self.state == "half-open" and self.trials < 3:
            self.trials += 1
            return True
        return False

    def record(self, now, ok):
        if self.state == "half-open":
            if not ok:
                self.state, self.opened_at = "open", now
            elif self.trials == 3:
                self.state = "closed"
                self.results.clear()
            return
        self.results.append(ok)
        if len(self.results) == 20 and self.results.count(False) >= 10:
            self.state, self.opened_at = "open", now


def simulate(limit=None, breaker=False, seed=5):
    """limit: the most threads that recommendations calls may hold (a bulkhead); breaker: one on that dependency."""
    rng = random.Random(seed)
    busy = {name: 0 for name in ENDPOINTS}
    done = []  # heap of (finish time, sequence number, endpoint, ok)
    counts = {name: {"ok": 0, "fallback": 0, "failed": 0} for name in ENDPOINTS}
    cb = Breaker() if breaker else None
    seq = 0
    for now in range(END):
        while done and done[0][0] <= now:
            _, _, name, ok = heapq.heappop(done)
            busy[name] -= 1
            if name == "recommendations" and cb:
                cb.record(now, ok)
        arrivals = [name for name, (rate, _) in ENDPOINTS.items() if rng.random() < rate]
        rng.shuffle(arrivals)
        for name in arrivals:
            after = now >= SLOW_FROM
            tally = counts[name] if after else {"ok": 0, "fallback": 0, "failed": 0}
            if name == "recommendations" and cb and not cb.allow(now):
                tally["fallback"] += 1  # open breaker: answer at once with a cached list of popular items
                continue
            if sum(busy.values()) >= POOL or (name == "recommendations" and limit is not None and busy[name] >= limit):
                tally["failed"] += 1  # no thread for it: rejected with a 503
                continue
            hangs = name == "recommendations" and after
            took = TIMEOUT_MS if hangs else max(1, round(rng.expovariate(1 / ENDPOINTS[name][1])))
            busy[name] += 1
            seq += 1
            heapq.heappush(done, (now + took, seq, name, not hangs))
            tally["failed" if hangs else "ok"] += 1
    return counts


print("From 10 s to 30 s, while recommendations hang: share of each endpoint's requests")
print(f"{'design':<33}{'search ok':>10}{'profile ok':>11}{'recs ok':>9}{'recs fallback':>14}{'recs failed':>12}")
for label, kwargs in [
    ("one shared pool of 200 threads", {}),
    ("bulkhead: recommendations <= 20", {"limit": 20}),
    ("bulkhead and circuit breaker", {"limit": 20, "breaker": True}),
]:
    c = simulate(**kwargs)

    def share(name, key):
        return c[name][key] / sum(c[name].values())

    print(
        f"{label:<33}{share('search', 'ok'):>10.1%}{share('profile', 'ok'):>11.1%}{share('recommendations', 'ok'):>9.1%}"
        f"{share('recommendations', 'fallback'):>14.1%}{share('recommendations', 'failed'):>12.1%}"
    )

Output

From 10 s to 30 s, while recommendations hang: share of each endpoint's requests
design                            search ok profile ok  recs ok recs fallback recs failed
one shared pool of 200 threads        40.8%      41.2%     0.0%          0.0%      100.0%
bulkhead: recommendations <= 20      100.0%     100.0%     0.0%          0.0%      100.0%
bulkhead and circuit breaker         100.0%     100.0%     0.0%         73.5%       26.5%

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

With one shared pool, only about 41 % of search and profile requests succeed while recommendations hang, although those endpoints have nothing wrong with them. Limiting recommendations to 20 threads brings both back to 100 %: the bulkhead turns a failure of the whole server into a failure of one feature. Adding a circuit breaker changes what the recommendation users get. Once the breaker opens, their requests stop waiting 5 seconds for an error and get a cached list of popular items at once, which is why 73.5 % of them see a fallback: What a caller does instead of a call that failed or was refused, such as serving a cached answer or a default. It runs only during failures, so it needs regular exercise to stay working. instead of a failure. The rest are the requests from the first seconds of the hang, before enough calls had timed out for the breaker to notice.

Key idea

During a hang, a dependency’s calls in flight are its call rate times its timeout, so one slow dependency can hold every thread of a pool it shares with healthy ones.

Checkpoint

Check: One slow dependency and a shared pool

  1. Question 1 of 2 Recommendations receive 100 calls a second, and while the dependency hangs every call waits for its 5-second timeout. How many threads do these calls want at once?

    Type a number.

    A hint

    By Little's law, the calls in flight are the arrival rate times the time each one waits.

    Show the answer: Question 1 of 2

    Answer: 500 threads

    100 calls a second × 5 seconds = 500 calls in flight, more than twice the 200 threads of the pool. Within about two seconds every thread waits on recommendations, which is why search and profiles stopped working.

  2. Question 2 of 2 In the shared-pool design, why did only about 41 % of search and profile requests succeed while recommendations hung?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Every thread was waiting on recommendations, so their requests found no thread to run on

    One slow dependency held every thread of a pool that three endpoints shared. A bulkhead of 20 threads for recommendations brought search and profiles back to 100 %.

Bulkheads: a separate share for each dependency

The name comes from the walls that divide a ship’s hull into compartments: if the hull is breached, only one compartment floods (Azure bulkhead pattern). In software the compartments are pools. A caller gives each dependency its own connection pool, thread pool or semaphore, so that a dependency that stops answering can exhaust only its own. A service can partition the other way too, giving important consumers their own instances or queues so that one heavy consumer cannot starve the rest. Resilience4j, a fault-tolerance library for Java, offers both common forms: a A counter of permits: a call takes one before it starts and gives it back when it ends, so no more calls run at once than there are permits. bulkhead that caps concurrent calls, 25 by default, and a thread-pool bulkhead with a bounded queue of 100 by default (Resilience4j bulkhead).

Size a bulkhead from the same law that showed the failure. Recommendations normally have 100 × 0.04 = 4 calls in flight, so a limit of 20 leaves five times the normal need for bursts and slow spells, and caps the damage of a hang at 20 of the 200 threads. A limit far above the normal need protects little; one at the normal need rejects good calls during every burst. The cost is that reserved capacity sits idle while its dependency is quiet, and the Azure pattern names that less efficient use of resources as a reason not to use bulkheads where they are not needed.

Step through the same server before and after its bulkhead:

Interactive · step by step 200 threads, three dependencies, and one that hangs Step through a normal moment, the hang of recommendations, and the same hang behind a bulkhead of 20 threads.
200 threads, three dependencies, and one that hangs, step 6 of 6. Showing Worker threads (32 of 200 busy), Search (300/s, 20 ms: 6 busy), Profiles (200/s, 30 ms: 6 busy), Recommendations (breaker open: cached list). In focus: Recommendations.Worker threads32 of 200 busySearch300/s, 20 ms: 6 busyProfiles200/s, 30 ms: 6 busyRecommendationsbreaker open: cached list

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

Every step as text
  1. A normal moment. By Little's law each dependency holds its call rate times its call time. Search holds 6 threads, profiles 6 and recommendations 4, so 16 of the 200 are busy.
  2. Recommendations hang. The recommendations dependency stops answering, and every call to it waits for its 5-second timeout. At 100 calls a second it now wants 100 × 5 = 500 threads.
  3. The pool runs out. Within about two seconds all 200 threads wait on recommendations. Requests for search and profiles find no thread, although their own dependencies are fine.
  4. A bulkhead of 20. Give recommendations a compartment of its own, at most 20 threads, five times what it normally holds. Its calls beyond 20 are refused at once.
  5. The rest keep working. The other 180 threads stay available, so search and profiles answer 100 % of their requests in the simulation, while recommendations fail on their own.
  6. A breaker on top. Once a circuit breaker on recommendations opens, its callers stop waiting 5 seconds for an error and get a cached list of popular items at once.

Proxies enforce the same limits outside the application. Envoy’s “circuit breakers” are in fact caps on connections, pending requests, active requests and retries for each upstream cluster, 1,024 connections by default; requests over a cap fail at once and carry an x-envoy-overloaded header (Envoy circuit breaking). Its documentation states the principle behind all of these limits: failing quickly and pushing back early is nearly always better than waiting.

Checkpoint

Check: Sizing a bulkhead

  1. Question 1 of 2 Calls to a dependency arrive at 100 a second and normally take 40 ms. How many are in flight on average, the starting point for sizing its bulkhead?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 4 calls

    Little's law: 100 a second × 0.04 s = 4 calls in flight. A bulkhead of a few times that, say 20, absorbs bursts and slow spells, and still leaves the rest of the pool to the other dependencies when this one hangs.

  2. Question 2 of 2 Recommendations normally hold 4 threads of a 200-thread pool. Which bulkhead limit fits best?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 20, five times the normal need

    Size a bulkhead from Little's law with headroom: a limit far above the normal need protects little, and one at the normal need rejects good calls in every burst. The cost is reserved capacity that sits idle while the dependency is quiet.

Circuit breakers: stop calling what is broken

A bulkhead limits how much a broken dependency can hold; a circuit breaker stops calling it. The Azure pattern describes the breaker as a proxy with three states (Azure circuit breaker pattern):

A circuit breaker moves from closed to open when failures pass a threshold, to half-open when a timer ends, then closes or opens again.Closedcalls go through;failures are countedOpencalls fail at once;a timer runsHalf-opena few trial callsgo throughfailures passthe thresholdthe timerruns outthe trials succeeda trial fails:the timer restarts

Closed, open and half-open

Text description of the diagram

The diagram shows the three states of a circuit breaker and the four moves between them.

  1. Closed: calls go through to the dependency, and the breaker counts the failures. When the failures pass the threshold, the breaker moves to open.
  2. Open: calls fail at once, without reaching the dependency, while a timer runs. When the timer runs out, the breaker moves to half-open.
  3. Half-open: a few trial calls go through. If the trials succeed, the breaker moves back to closed. If a trial fails, it moves back to open and the timer starts again.
  • Closed: calls go through and the breaker counts the recent failures. When they pass a threshold within a time window, it opens and starts a timer.
  • Open: calls fail at once, with an error or a fallback, and never reach the dependency.
  • Half-open: when the timer runs out, a limited number of trial calls go through. If they succeed, the breaker closes and resets its counts; if one fails, it opens again and the timer restarts.

The half-open: The state of a circuit breaker after its open timer runs out, in which a limited number of trial calls go through: if they succeed the breaker closes, and if one fails it opens again. state exists because a service that has just recovered may cope with a trickle of requests and not with the full load at once. Libraries make the counting precise. Resilience4j keeps a sliding window of the last 100 calls by default, waits for at least 100 calls before it judges, opens at a failure rate of 50 %, can also open on the share of slow calls, stays open for 60 seconds and then allows 10 trial calls (Resilience4j circuit breaker). The example below is a smaller breaker of the same kind, with a window of 10 calls and a clock passed in, so that time can be moved by a test instead of waited for. A dependency fails from 20 to 80 seconds and is called once a second. The breaker is the same in each of the 14 tabs, and so is the run it printed:

One program · 14 languages A failure-rate circuit breaker, with the time passed in

Python 3.14 · main.py

from collections import deque

WINDOW, FAILURE_RATE, OPEN_SECONDS = 10, 0.5, 15


class CircuitBreaker:
    def __init__(self) -> None:
        self.state = "closed"
        # The last calls: True for a success.
        self.results: deque[bool] = deque(maxlen=WINDOW)
        self.opened_at = 0

    def allow(self, now: int) -> bool:
        if self.state == "open" and now - self.opened_at >= OPEN_SECONDS:
            self.move(now, "half-open")
            return True  # the one trial call
        return self.state == "closed"  # open or half-open: fail fast

    def record(self, now: int, ok: bool) -> None:
        if self.state == "half-open":
            self.move(now, "closed" if ok else "open")
        else:
            self.results.append(ok)
            if (
                len(self.results) == WINDOW
                and self.results.count(False) / WINDOW >= FAILURE_RATE
            ):
                self.move(now, "open")

    def move(self, now: int, new: str) -> None:
        print(f"{now:>5} s  {self.state:>9} -> {new}")
        if new == "open":
            self.opened_at = now
        if new == "closed":
            self.results.clear()
        self.state = new


breaker = CircuitBreaker()  # the time is passed in, so nothing waits
sent = 0
for now in range(120):  # one call a second; the dependency fails from 20 s to 80 s
    if breaker.allow(now):
        sent += 1
        breaker.record(now, not 20 <= now < 80)
print(f"\n120 calls: {sent} reached the dependency, {120 - sent} were answered at once")

In Python: deque(maxlen=WINDOW) forgets the oldest call by itself, and count(False) counts the failures in the window.

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

JavaScript Node 24 · main.mjs

const [WINDOW, FAILURE_RATE, OPEN_SECONDS] = [10, 0.5, 15];

class CircuitBreaker {
  state = "closed";
  results = []; // the last calls: true for a success
  openedAt = 0;

  allow(now) {
    if (this.state === "open" && now - this.openedAt >= OPEN_SECONDS) {
      this.move(now, "half-open");
      return true; // the one trial call
    }
    return this.state === "closed"; // open or half-open: fail fast
  }

  record(now, ok) {
    if (this.state === "half-open") {
      this.move(now, ok ? "closed" : "open");
      return;
    }
    this.results.push(ok);
    if (this.results.length > WINDOW) this.results.shift();
    const failures = this.results.filter((result) => !result).length;
    if (this.results.length === WINDOW && failures / WINDOW >= FAILURE_RATE) this.move(now, "open");
  }

  move(now, next) {
    console.log(`${String(now).padStart(5)} s  ${this.state.padStart(9)} -> ${next}`);
    if (next === "open") this.openedAt = now;
    if (next === "closed") this.results = [];
    this.state = next;
  }
}

const breaker = new CircuitBreaker(); // the time is passed in, so nothing waits
let sent = 0;
for (let now = 0; now < 120; now++) {
  // one call a second; the dependency fails from 20 s to 80 s
  if (breaker.allow(now)) {
    sent++;
    breaker.record(now, !(20 <= now && now < 80));
  }
}
console.log(`\n120 calls: ${sent} reached the dependency, ${120 - sent} were answered at once`);

In JavaScript: An array holds the window, and shift drops the oldest call once it holds more than WINDOW; class fields set the starting state.

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

Java 25 LTS · Main.java

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

public class Main {
  static final int WINDOW = 10;
  static final double FAILURE_RATE = 0.5;
  static final int OPEN_SECONDS = 15;

  static final class CircuitBreaker {
    private String state = "closed";
    private final ArrayDeque<Boolean> results = new ArrayDeque<>(); // the last calls
    private int openedAt;

    boolean allow(int now) {
      if (state.equals("open") && now - openedAt >= OPEN_SECONDS) {
        move(now, "half-open");
        return true; // the one trial call
      }
      return state.equals("closed"); // open or half-open: fail fast
    }

    void record(int now, boolean ok) {
      if (state.equals("half-open")) {
        move(now, ok ? "closed" : "open");
        return;
      }
      results.addLast(ok);
      if (results.size() > WINDOW) {
        results.removeFirst();
      }
      int failures = 0;
      for (boolean result : results) {
        failures += result ? 0 : 1;
      }
      if (results.size() == WINDOW && (double) failures / WINDOW >= FAILURE_RATE) {
        move(now, "open");
      }
    }

    private void move(int now, String next) {
      System.out.println(String.format("%5d s  %9s -> %s", now, state, next));
      if (next.equals("open")) {
        openedAt = now;
      }
      if (next.equals("closed")) {
        results.clear();
      }
      state = next;
    }
  }

  public static void main(String[] args) {
    Locale.setDefault(Locale.ROOT);
    CircuitBreaker breaker = new CircuitBreaker(); // the time is passed in, so nothing waits
    int sent = 0;
    // One call a second; the dependency fails from 20 s to 80 s.
    for (int now = 0; now < 120; now++) {
      if (breaker.allow(now)) {
        sent++;
        breaker.record(now, !(20 <= now && now < 80));
      }
    }
    System.out.printf(
        "%n120 calls: %d reached the dependency, %d were answered at once%n", sent, 120 - sent);
  }
}

In Java: ArrayDeque holds the window, addLast and removeFirst slide it, and main sets Locale.ROOT, since String.format pads the numbers.

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 <deque>
#include <print>
#include <string>

constexpr int WINDOW = 10;
constexpr double FAILURE_RATE = 0.5;
constexpr int OPEN_SECONDS = 15;

class CircuitBreaker {
public:
  bool allow(int now) {
    if (state_ == "open" && now - openedAt_ >= OPEN_SECONDS) {
      move(now, "half-open");
      return true; // the one trial call
    }
    return state_ == "closed"; // open or half-open: fail fast
  }

  void record(int now, bool ok) {
    if (state_ == "half-open") {
      move(now, ok ? "closed" : "open");
      return;
    }
    results_.push_back(ok);
    if (results_.size() > WINDOW) {
      results_.pop_front();
    }
    const auto failures = std::ranges::count(results_, false);
    if (results_.size() == WINDOW &&
        static_cast<double>(failures) / WINDOW >= FAILURE_RATE) {
      move(now, "open");
    }
  }

private:
  void move(int now, const std::string &next) {
    std::println("{:>5} s  {:>9} -> {}", now, state_, next);
    if (next == "open") {
      openedAt_ = now;
    }
    if (next == "closed") {
      results_.clear();
    }
    state_ = next;
  }

  std::string state_ = "closed";
  std::deque<bool> results_; // the last calls: true for a success
  int openedAt_ = 0;
};

int main() {
  CircuitBreaker breaker; // the time is passed in, so nothing waits
  int sent = 0;
  // One call a second; the dependency fails from 20 s to 80 s.
  for (int now = 0; now < 120; now++) {
    if (breaker.allow(now)) {
      sent++;
      breaker.record(now, !(20 <= now && now < 80));
    }
  }
  std::println(
      "\n120 calls: {} reached the dependency, {} were answered at once", sent,
      120 - sent);
}

In C++: std::deque slides the window, std::ranges::count counts the failures, and the state is a std::string to match the printed names.

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

var breaker = new CircuitBreaker(); // the time is passed in, so nothing waits
int sent = 0;
// One call a second; the dependency fails from 20 s to 80 s.
for (int now = 0; now < 120; now++)
{
    if (breaker.Allow(now))
    {
        sent++;
        breaker.Record(now, !(20 <= now && now < 80));
    }
}
Console.WriteLine(
    $"\n120 calls: {sent} reached the dependency, {120 - sent} were answered at once");

sealed class CircuitBreaker
{
    const int Window = 10;
    const double FailureRate = 0.5;
    const int OpenSeconds = 15;

    private string state = "closed";
    private readonly Queue<bool> results = new(); // the last calls: true for a success
    private int openedAt;

    public bool Allow(int now)
    {
        if (state == "open" && now - openedAt >= OpenSeconds)
        {
            Move(now, "half-open");
            return true; // the one trial call
        }
        return state == "closed"; // open or half-open: fail fast
    }

    public void Record(int now, bool ok)
    {
        if (state == "half-open")
        {
            Move(now, ok ? "closed" : "open");
            return;
        }
        results.Enqueue(ok);
        if (results.Count > Window)
        {
            results.Dequeue();
        }
        int failures = results.Count(result => !result);
        if (results.Count == Window && (double)failures / Window >= FailureRate)
        {
            Move(now, "open");
        }
    }

    private void Move(int now, string next)
    {
        Console.WriteLine($"{now,5} s  {state,9} -> {next}");
        if (next == "open")
        {
            openedAt = now;
        }
        if (next == "closed")
        {
            results.Clear();
        }
        state = next;
    }
}

In C#: Queue<bool> slides the window with Enqueue and Dequeue, and LINQ's Count(result => !result) counts the failures.

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>

enum { WINDOW = 10, OPEN_SECONDS = 15 };
static const double FAILURE_RATE = 0.5;

typedef enum { CLOSED, OPEN, HALF_OPEN } State;
static const char *const NAMES[] = {"closed", "open", "half-open"};

typedef struct {
  State state;
  bool results[WINDOW]; // a ring of the last calls: true for a success
  int count, next, opened_at;
} CircuitBreaker;

static void move(CircuitBreaker *b, int now, State next) {
  printf("%5d s  %9s -> %s\n", now, NAMES[b->state], NAMES[next]);
  if (next == OPEN) {
    b->opened_at = now;
  }
  if (next == CLOSED) {
    b->count = b->next = 0;
  }
  b->state = next;
}

static bool allow(CircuitBreaker *b, int now) {
  if (b->state == OPEN && now - b->opened_at >= OPEN_SECONDS) {
    move(b, now, HALF_OPEN);
    return true; // the one trial call
  }
  return b->state == CLOSED; // open or half-open: fail fast
}

static void record(CircuitBreaker *b, int now, bool ok) {
  if (b->state == HALF_OPEN) {
    move(b, now, ok ? CLOSED : OPEN);
    return;
  }
  b->results[b->next] = ok;
  b->next = (b->next + 1) % WINDOW;
  b->count += b->count < WINDOW;
  int failures = 0;
  for (int i = 0; i < b->count; i++) {
    failures += !b->results[i];
  }
  if (b->count == WINDOW && (double)failures / WINDOW >= FAILURE_RATE) {
    move(b, now, OPEN);
  }
}

int main(void) {
  CircuitBreaker breaker = {}; // the time is passed in, so nothing waits
  int sent = 0;
  // One call a second; the dependency fails from 20 s to 80 s.
  for (int now = 0; now < 120; now++) {
    if (allow(&breaker, now)) {
      sent++;
      record(&breaker, now, !(20 <= now && now < 80));
    }
  }
  printf("\n120 calls: %d reached the dependency, %d were answered at once\n",
         sent, 120 - sent);
  return 0;
}

In C: The window is a ring buffer of WINDOW booleans with a count and a next index, and the states are an enum whose names come from a table.

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

PHP 8.5 · main.php

<?php

declare(strict_types=1);

const WINDOW = 10;
const FAILURE_RATE = 0.5;
const OPEN_SECONDS = 15;

final class CircuitBreaker
{
    private string $state = 'closed';
    /** @var list<bool> the last calls: true for a success */
    private array $results = [];
    private int $openedAt = 0;

    public function allow(int $now): bool
    {
        if ($this->state === 'open' && $now - $this->openedAt >= OPEN_SECONDS) {
            $this->move($now, 'half-open');
            return true; // the one trial call
        }
        return $this->state === 'closed'; // open or half-open: fail fast
    }

    public function record(int $now, bool $ok): void
    {
        if ($this->state === 'half-open') {
            $this->move($now, $ok ? 'closed' : 'open');
            return;
        }
        $this->results[] = $ok;
        if (count($this->results) > WINDOW) {
            array_shift($this->results);
        }
        $failures = count(array_filter($this->results, fn(bool $result): bool => !$result));
        if (count($this->results) === WINDOW && $failures / WINDOW >= FAILURE_RATE) {
            $this->move($now, 'open');
        }
    }

    private function move(int $now, string $next): void
    {
        printf("%5d s  %9s -> %s\n", $now, $this->state, $next);
        if ($next === 'open') {
            $this->openedAt = $now;
        }
        if ($next === 'closed') {
            $this->results = [];
        }
        $this->state = $next;
    }
}

$breaker = new CircuitBreaker(); // the time is passed in, so nothing waits
$sent = 0;
// One call a second; the dependency fails from 20 s to 80 s.
for ($now = 0; $now < 120; $now++) {
    if ($breaker->allow($now)) {
        $sent++;
        $breaker->record($now, !(20 <= $now && $now < 80));
    }
}
printf("\n120 calls: %d reached the dependency, %d were answered at once\n", $sent, 120 - $sent);

In PHP: array_shift drops the oldest call, and array_filter with an arrow function keeps the failures, whose count decides.

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

Rust 1.99 · main.rs

use std::collections::VecDeque;

const WINDOW: usize = 10;
const FAILURE_RATE: f64 = 0.5;
const OPEN_SECONDS: u32 = 15;

#[derive(Clone, Copy, PartialEq, Default)]
enum State {
    #[default]
    Closed,
    Open,
    HalfOpen,
}

#[derive(Default)]
struct CircuitBreaker {
    state: State,
    results: VecDeque<bool>, // the last calls: true for a success
    opened_at: u32,
}

impl CircuitBreaker {
    fn allow(&mut self, now: u32) -> bool {
        if self.state == State::Open && now - self.opened_at >= OPEN_SECONDS {
            self.move_to(now, State::HalfOpen);
            return true; // the one trial call
        }
        self.state == State::Closed // open or half-open: fail fast
    }

    fn record(&mut self, now: u32, ok: bool) {
        if self.state == State::HalfOpen {
            self.move_to(now, if ok { State::Closed } else { State::Open });
            return;
        }
        self.results.push_back(ok);
        if self.results.len() > WINDOW {
            self.results.pop_front();
        }
        let failures = self.results.iter().filter(|&&result| !result).count();
        if self.results.len() == WINDOW && failures as f64 / WINDOW as f64 >= FAILURE_RATE {
            self.move_to(now, State::Open);
        }
    }

    fn move_to(&mut self, now: u32, next: State) {
        println!("{now:>5} s  {:>9} -> {}", name(self.state), name(next));
        match next {
            State::Open => self.opened_at = now,
            State::Closed => self.results.clear(),
            State::HalfOpen => {}
        }
        self.state = next;
    }
}

fn name(state: State) -> &'static str {
    match state {
        State::Closed => "closed",
        State::Open => "open",
        State::HalfOpen => "half-open",
    }
}

fn main() {
    let mut breaker = CircuitBreaker::default(); // the time is passed in, so nothing waits
    let mut sent = 0;
    for now in 0..120 {
        // One call a second; the dependency fails from 20 s to 80 s.
        if breaker.allow(now) {
            sent += 1;
            breaker.record(now, !(20..80).contains(&now));
        }
    }
    println!(
        "\n120 calls: {sent} reached the dependency, {} were answered at once",
        120 - sent
    );
}

In Rust: VecDeque slides the window, the states are an enum with a name function, and both types derive Default, so CircuitBreaker::default() starts closed.

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

TypeScript 6.0 · main.ts

const [WINDOW, FAILURE_RATE, OPEN_SECONDS] = [10, 0.5, 15];

type State = "closed" | "open" | "half-open";

class CircuitBreaker {
  state: State = "closed";
  results: boolean[] = []; // the last calls: true for a success
  openedAt = 0;

  allow(now: number): boolean {
    if (this.state === "open" && now - this.openedAt >= OPEN_SECONDS) {
      this.move(now, "half-open");
      return true; // the one trial call
    }
    return this.state === "closed"; // open or half-open: fail fast
  }

  record(now: number, ok: boolean): void {
    if (this.state === "half-open") {
      this.move(now, ok ? "closed" : "open");
      return;
    }
    this.results.push(ok);
    if (this.results.length > WINDOW) this.results.shift();
    const failures = this.results.filter((result) => !result).length;
    if (this.results.length === WINDOW && failures / WINDOW >= FAILURE_RATE) this.move(now, "open");
  }

  move(now: number, next: State): void {
    console.log(`${String(now).padStart(5)} s  ${this.state.padStart(9)} -> ${next}`);
    if (next === "open") this.openedAt = now;
    if (next === "closed") this.results = [];
    this.state = next;
  }
}

const breaker = new CircuitBreaker(); // the time is passed in, so nothing waits
let sent = 0;
for (let now = 0; now < 120; now++) {
  // one call a second; the dependency fails from 20 s to 80 s
  if (breaker.allow(now)) {
    sent++;
    breaker.record(now, !(20 <= now && now < 80));
  }
}
console.log(`\n120 calls: ${sent} reached the dependency, ${120 - sent} were answered at once`);

In TypeScript: The states are a union type of the three names, so a misspelt state 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"

const (
	window      = 10
	failureRate = 0.5
	openSeconds = 15
)

type CircuitBreaker struct {
	state    string
	results  []bool // the last calls: true for a success
	openedAt int
}

func (b *CircuitBreaker) allow(now int) bool {
	if b.state == "open" && now-b.openedAt >= openSeconds {
		b.move(now, "half-open")
		return true // the one trial call
	}
	return b.state == "closed" // open or half-open: fail fast
}

func (b *CircuitBreaker) record(now int, ok bool) {
	if b.state == "half-open" {
		next := "open"
		if ok {
			next = "closed"
		}
		b.move(now, next)
		return
	}
	b.results = append(b.results, ok)
	if len(b.results) > window {
		b.results = b.results[1:]
	}
	failures := 0
	for _, result := range b.results {
		if !result {
			failures++
		}
	}
	if len(b.results) == window && float64(failures)/window >= failureRate {
		b.move(now, "open")
	}
}

func (b *CircuitBreaker) move(now int, next string) {
	fmt.Printf("%5d s  %9s -> %s\n", now, b.state, next)
	switch next {
	case "open":
		b.openedAt = now
	case "closed":
		b.results = nil
	}
	b.state = next
}

func main() {
	breaker := &CircuitBreaker{state: "closed"} // the time is passed in, so nothing waits
	sent := 0
	for now := range 120 { // one call a second; the dependency fails from 20 s to 80 s
		if breaker.allow(now) {
			sent++
			breaker.record(now, !(20 <= now && now < 80))
		}
	}
	fmt.Printf("\n120 calls: %d reached the dependency, %d were answered at once\n", sent, 120-sent)
}

In Go: A slice holds the window and b.results[1:] drops the oldest call; range 120 counts the seconds, which Go allows from version 1.22.

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

Swift 6.4 · main.swift

let window = 10
let failureRate = 0.5
let openSeconds = 15

final class CircuitBreaker {
  private(set) var state = "closed"
  private var results: [Bool] = []  // the last calls: true for a success
  private var openedAt = 0

  func allow(now: Int) -> Bool {
    if state == "open" && now - openedAt >= openSeconds {
      move(now: now, to: "half-open")
      return true  // the one trial call
    }
    return state == "closed"  // open or half-open: fail fast
  }

  func record(now: Int, ok: Bool) {
    if state == "half-open" {
      move(now: now, to: ok ? "closed" : "open")
      return
    }
    results.append(ok)
    if results.count > window {
      results.removeFirst()
    }
    let failures = results.filter { !$0 }.count
    if results.count == window && Double(failures) / Double(window) >= failureRate {
      move(now: now, to: "open")
    }
  }

  private func move(now: Int, to next: String) {
    let at = String(repeating: " ", count: 5 - String(now).count) + String(now)
    let from = String(repeating: " ", count: 9 - state.count) + state
    print("\(at) s  \(from) -> \(next)")
    if next == "open" {
      openedAt = now
    }
    if next == "closed" {
      results.removeAll()
    }
    state = next
  }
}

let breaker = CircuitBreaker()  // the time is passed in, so nothing waits
var sent = 0
for now in 0..<120 {  // one call a second; the dependency fails from 20 s to 80 s
  if breaker.allow(now: now) {
    sent += 1
    breaker.record(now: now, ok: !(20..<80).contains(now))
  }
}
print("\n120 calls: \(sent) reached the dependency, \(120 - sent) were answered at once")

In Swift: removeFirst drops the oldest call, and without Foundation there is no String(format:), so move pads the numbers and names itself.

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

WINDOW = 10
FAILURE_RATE = 0.5
OPEN_SECONDS = 15

# A circuit breaker that judges the last WINDOW calls and lets one trial call through.
class CircuitBreaker
  def initialize
    @state = 'closed'
    @results = [] # the last calls: true for a success
    @opened_at = 0
  end

  def allow(now)
    if @state == 'open' && now - @opened_at >= OPEN_SECONDS
      move(now, 'half-open')
      return true # the one trial call
    end
    @state == 'closed' # open or half-open: fail fast
  end

  def record(now, success)
    return move(now, success ? 'closed' : 'open') if @state == 'half-open'

    @results << success
    @results.shift if @results.size > WINDOW
    failing = @results.count(false).fdiv(WINDOW) >= FAILURE_RATE
    move(now, 'open') if @results.size == WINDOW && failing
  end

  private

  def move(now, after)
    puts "#{now.to_s.rjust(5)} s  #{@state.rjust(9)} -> #{after}"
    @opened_at = now if after == 'open'
    @results.clear if after == 'closed'
    @state = after
  end
end

breaker = CircuitBreaker.new # the time is passed in, so nothing waits
sent = 0
120.times do |now| # one call a second; the dependency fails from 20 s to 80 s
  next unless breaker.allow(now)

  sent += 1
  breaker.record(now, !(20...80).cover?(now))
end
puts "\n120 calls: #{sent} reached the dependency, #{120 - sent} were answered at once"

In Ruby: fdiv divides the failures by the window as a float, and (20...80).cover?(now) tests the dependency's broken period.

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

Kotlin 2.4 · Main.kt

const val WINDOW = 10
const val FAILURE_RATE = 0.5
const val OPEN_SECONDS = 15

class CircuitBreaker {
    private var state = "closed"
    private val results = ArrayDeque<Boolean>() // the last calls: true for a success
    private var openedAt = 0

    fun allow(now: Int): Boolean {
        if (state == "open" && now - openedAt >= OPEN_SECONDS) {
            move(now, "half-open")
            return true // the one trial call
        }
        return state == "closed" // open or half-open: fail fast
    }

    fun record(
        now: Int,
        ok: Boolean,
    ) {
        if (state == "half-open") {
            move(now, if (ok) "closed" else "open")
            return
        }
        results.addLast(ok)
        if (results.size > WINDOW) results.removeFirst()
        val failures = results.count { !it }
        if (results.size == WINDOW && failures.toDouble() / WINDOW >= FAILURE_RATE) {
            move(now, "open")
        }
    }

    private fun move(
        now: Int,
        next: String,
    ) {
        println("${now.toString().padStart(5)} s  ${state.padStart(9)} -> $next")
        if (next == "open") openedAt = now
        if (next == "closed") results.clear()
        state = next
    }
}

fun main() {
    val breaker = CircuitBreaker() // the time is passed in, so nothing waits
    var sent = 0
    for (now in 0 until 120) { // one call a second; the dependency fails from 20 s to 80 s
        if (breaker.allow(now)) {
            sent++
            breaker.record(now, now !in 20 until 80)
        }
    }
    println("\n120 calls: $sent reached the dependency, ${120 - sent} were answered at once")
}

In Kotlin: kotlin.collections.ArrayDeque slides the window, and now !in 20 until 80 tests whether the dependency is up.

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

const window = 10;
const failureRate = 0.5;
const openSeconds = 15;

class CircuitBreaker {
  var state = 'closed';
  final results = <bool>[]; // the last calls: true for a success
  var openedAt = 0;

  bool allow(int now) {
    if (state == 'open' && now - openedAt >= openSeconds) {
      move(now, 'half-open');
      return true; // the one trial call
    }
    return state == 'closed'; // open or half-open: fail fast
  }

  void record(int now, bool ok) {
    if (state == 'half-open') {
      move(now, ok ? 'closed' : 'open');
      return;
    }
    results.add(ok);
    if (results.length > window) results.removeAt(0);
    final failures = results.where((result) => !result).length;
    if (results.length == window && failures / window >= failureRate) {
      move(now, 'open');
    }
  }

  void move(int now, String next) {
    print('${'$now'.padLeft(5)} s  ${state.padLeft(9)} -> $next');
    if (next == 'open') openedAt = now;
    if (next == 'closed') results.clear();
    state = next;
  }
}

void main() {
  final breaker = CircuitBreaker(); // the time is passed in, so nothing waits
  var sent = 0;
  // One call a second; the dependency fails from 20 s to 80 s.
  for (var now = 0; now < 120; now++) {
    if (breaker.allow(now)) {
      sent++;
      breaker.record(now, !(20 <= now && now < 80));
    }
  }
  print(
    '\n120 calls: $sent reached the dependency, ${120 - sent} were answered at once',
  );
}

In Dart: removeAt(0) drops the oldest call, where(...).length counts the failures, and / always returns a double.

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

   24 s     closed -> open
   39 s       open -> half-open
   39 s  half-open -> open
   54 s       open -> half-open
   54 s  half-open -> open
   69 s       open -> half-open
   69 s  half-open -> open
   84 s       open -> half-open
   84 s  half-open -> closed

120 calls: 64 reached the dependency, 56 were answered at once

The breaker opens at 24 seconds, when 5 of the last 10 calls have failed, and from then on answers calls itself. Every 15 seconds it lets a trial call through, finds the dependency still down and opens again. Of 120 calls, 56 were answered at once instead of waiting on a broken dependency. The timeline also shows the breaker’s cost: the dependency recovered at 80 seconds, but callers kept failing until the next trial at 84 seconds. The Amazon Builders’ Library makes this criticism of breakers, that they add modes which are hard to test and can add time to recovery, and prefers a token-bucket limit on retries (Builders’ Library). Step through the run on the breaker’s three states:

Interactive · step by step The breaker's two minutes, state by state Step through the program's run. Each step names the second, the state the breaker moves to and why.
The breaker's two minutes, state by state, step 8 of 8. Showing Closed, Open (calls fail at once), Half-open, Dependency (up again from 80 s). In focus: Closed.half the window failed15 s passedthe trial failedthe trial passedClosedcalls go throughOpencalls fail at onceHalf-openone trial callDependencyup again from 80 strial passes at 84 s

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

Every step as text
  1. 0 to 19 s. The breaker is closed, every call reaches the dependency and succeeds, and the window of the last 10 calls fills with successes.
  2. 20 s. The dependency goes down. Calls still go through, because the breaker has seen only one failure in its last 10 calls.
  3. 24 s. The fifth failure in a row makes 5 of the last 10 calls failures, the 50 % threshold, and the breaker opens.
  4. 25 to 38 s. While it is open, every call is answered at once by the breaker. No thread waits, and the dependency sees nothing.
  5. 39 s. Fifteen seconds after opening, the breaker turns half-open and lets one trial call through. It fails, so the breaker opens again and its timer restarts.
  6. 54 s and 69 s. The same happens at 54 s and at 69 s. Each trial costs one call to a dependency that is still down.
  7. 80 s. The dependency recovers, but the breaker is open until its next trial, so callers keep failing for 4 more seconds. That gap is the price of a breaker.
  8. 84 s. The trial at 84 s succeeds and the breaker closes. Of the 120 calls, 64 reached the dependency and 56 were answered at once.

Three rules keep breakers honest:

  1. One breaker per thing that fails independently. A single breaker for a store with many shards blocks the healthy shards when one fails; the Azure pattern warns about this.
  2. Make retries respect the breaker. A call refused by an open breaker is not a transient fault, so the retry logic around it should stop, not try again.
  3. Test the open path. What the caller does while the breaker is open, a cached answer, a default or an error, runs only during failures. The Builders’ Library describes a fallback that turned a partial outage into a full one: when a cache on every web server failed at about the same time, every server fell back to the database directly, and the database could not take it (Avoiding fallback). A fallback that is not exercised regularly, or that sends more load to something else, can be worse than a fast, honest error.

Key idea

A circuit breaker trades a slower return to normal for not calling what is broken: open, it fails at once, and a trial call after its timer decides whether it closes again.

Checkpoint

Check: The states of a circuit breaker

  1. Question 1 of 2 A circuit breaker is open. What happens to the next call?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: It fails at once without reaching the dependency, until the breaker's timer runs out

    Open means fail fast: the caller gets an error or a fallback in microseconds and no thread waits on the broken dependency. Only when the timer runs out does the breaker turn half-open and let a trial call through.

  2. Question 2 of 2 In the breaker's run, the dependency recovered at 80 seconds. For how many more seconds did callers keep getting failures from the open breaker?

    Type a number.

    A hint

    When was the next trial call after the one at 69 s?

    Show the answer: Question 2 of 2

    Answer: 4 seconds

    The breaker reopened at 69 s, and its 15-second timer let the next trial through at 84 s, which passed and closed it. From 80 s to 84 s callers failed although the dependency was up: the slower return to normal that a breaker trades for not calling what is broken.

Shuffle sharding: few customers share a bad customer’s servers

Bulkheads and breakers protect a caller from its dependencies. Shuffle sharding protects the customers of a service from each other. Suppose 8 workers serve many customers, and one customer sends a request that crashes any worker it reaches; its retries then crash the next worker too. With plain sharding into 4 fixed shards of 2 workers, the bad customer takes down its shard, and a quarter of all customers go down with it. With shuffle sharding, every customer gets its own pair of workers drawn from the 8, and there are 28 possible pairs, so only about 1 customer in 28 has exactly the bad customer’s pair; the Builders’ Library calls the result 7 times better than plain sharding (shuffle sharding).

The odds of sharing a bad customer's workers Python · shuffle-shard/shuffle_shard.py
# Shuffle sharding: give every customer its own random k workers out of n. How likely is another customer to share
# workers with a customer whose requests crash every worker they reach?
import random
from math import comb


def shares(n, k, j):
    """Chance that two random k-of-n shards have exactly j workers in common."""
    return comb(k, j) * comb(n - k, k - j) / comb(n, k)


print(f"{'workers':>7}{'each':>5}  {'possible shards':>15}  {'share all workers':>21}  {'share at least one':>18}")
for n, k in [(8, 2), (16, 4), (64, 4), (100, 5), (2048, 4)]:
    same = f"1 in {comb(n, k):,}"
    print(f"{n:>7}{k:>5}  {comb(n, k):>15,}  {same:>21}  {1 - shares(n, k, 0):>18.1%}")

# A simulation with 8 workers and 1,000 customers. Customer 0 sends a request that crashes any worker it reaches,
# and it retries, so both of its workers go down. Clients retry on their other worker, so a customer loses service
# only if all of its workers are down.
rng = random.Random(11)
WORKERS, CUSTOMERS = 8, 1_000

# Plain sharding: 4 fixed shards of 2 workers each, customers spread evenly.
shard_of = [c % 4 for c in range(CUSTOMERS)]
plain_lost = sum(1 for c in range(1, CUSTOMERS) if shard_of[c] == shard_of[0])

# Shuffle sharding: every customer draws its own 2 of the 8 workers.
shards = [frozenset(rng.sample(range(WORKERS), 2)) for _ in range(CUSTOMERS)]
down = shards[0]
shuffle_lost = sum(1 for c in range(1, CUSTOMERS) if shards[c] <= down)
shuffle_touched = sum(1 for c in range(1, CUSTOMERS) if shards[c] & down)
print(f"\n{CUSTOMERS - 1} other customers, 8 workers, 2 per customer; the bad customer's workers are down:")
print(f"  plain sharding:   {plain_lost} lose service ({plain_lost / (CUSTOMERS - 1):.1%})")
print(f"  shuffle sharding: {shuffle_lost} lose service ({shuffle_lost / (CUSTOMERS - 1):.1%}); "
      f"{shuffle_touched} lose one of their two workers and carry on on the other")

Output

workers each  possible shards      share all workers  share at least one
      8    2               28                1 in 28               46.4%
     16    4            1,820             1 in 1,820               72.8%
     64    4          635,376           1 in 635,376               23.3%
    100    5       75,287,520        1 in 75,287,520               23.0%
   2048    4  730,862,190,080   1 in 730,862,190,080                0.8%

999 other customers, 8 workers, 2 per customer; the bad customer's workers are down:
  plain sharding:   249 lose service (24.9%)
  shuffle sharding: 36 lose service (3.6%); 449 lose one of their two workers and carry on on the other

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

The table counts the possible shards, and the simulation plays the 8-worker case with 1,000 customers. Plain sharding loses 249 of them; shuffle sharding loses 36, because 449 customers lost one of their two workers but kept the other. That last condition matters: shuffle sharding works only if clients retry on another worker of their shard when one fails. The odds improve quickly with size. Amazon Route 53 assigns each customer domain 4 of 2,048 virtual name servers, which allows about 730 billion shards, and it chooses them so that no two domains share more than two name servers. Note what the last two columns say together: sharing some workers with the bad customer stays common, from 23 % to 73 % of customers in the four smaller fleets, but sharing all of them becomes vanishingly rare, and only that takes a customer down.

Step through the 8-worker case, with plain shards and then with shuffle shards:

Interactive · step by step Eight workers, one bad customer, two ways to shard Step through plain sharding, then shuffle sharding, and watch which other customers lose their workers.
Eight workers, one bad customer, two ways to shard, step 6 of 6. Showing Worker 1 (in many pairs), Worker 2 (in many pairs), Worker 3 (crashed), Worker 4 (in many pairs), Worker 5 (keeps a customer of 3, 5), Worker 6 (crashed), Worker 7 (in many pairs), Worker 8 (in many pairs). In focus: Worker 3, Worker 6.Worker 1in many pairsWorker 2in many pairsWorker 3crashedWorker 4in many pairsWorker 5keeps a customer of 3, 5Worker 6crashedWorker 7in many pairsWorker 8in many pairs

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

Every step as text
  1. Plain shards of 2. Plain sharding splits the 8 workers into 4 fixed shards of 2, and every customer belongs to one of them. The bad customer is on shard B.
  2. Shard B goes down. Its request crashes worker 3, and its retry crashes worker 4. Every customer of shard B, a quarter of them, loses service; in the run, 249 of 999.
  3. Shuffle shards of 2. With shuffle sharding every customer draws its own 2 of the 8 workers. There are 28 possible pairs, and the bad customer's pair is workers 3 and 6.
  4. Its two workers crash. The bad customer's requests crash workers 3 and 6, and nothing else, because its retries can only reach its own pair.
  5. One worker left. A customer with workers 3 and 5 loses worker 3 and retries on worker 5, so it keeps its service. In the run, 449 customers lost one of their two workers this way.
  6. The whole pair. Only a customer whose pair is exactly 3 and 6 loses service, about 1 in 28 of them; in the run, 36 of 999 against 249 with plain shards.

Key idea

Shuffle sharding gives each customer its own small random set of servers, so a bad customer can take down only customers who share its whole set, 1 in 28 with pairs of 8 workers, as long as clients retry on their other servers.

Checkpoint

Check: Shuffle sharding

  1. Question 1 of 2 With 8 workers and every customer given its own 2 of them at random, in how many possible ways can a customer's pair be chosen? (A customer has exactly the bad customer's workers with a chance of 1 in this number.)

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 28 pairs

    There are 8 × 7 ÷ 2 = 28 pairs. With plain sharding into 4 fixed pairs, a quarter of the customers share the bad customer's pair; with shuffle sharding only about 1 in 28 does, and the rest keep at least one healthy worker.

  2. Question 2 of 2 What must clients do for shuffle sharding to keep a customer working when one of its two workers is down?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Retry a failed call on the other worker of their shard

    Shuffle sharding works only if clients retry within their own shard. A customer then loses service only when all of its workers are down, which with pairs of 8 workers happens to about 1 customer in 28.

Which tool for which failure?

Each tool answers a different shape of failure, and real systems combine them.

The failure The tool What it does
A dependency is slow or hangs Bulkhead, with a timeout Caps the threads it can hold, so the rest keep working
A dependency is down for minutes Circuit breaker Fails fast, stops wasting calls and lets it recover
Brief, random errors Retries with backoff and a budget Turns blips into successes without multiplying load
One tenant’s requests crash or flood servers Shuffle sharding, with per-tenant limits Confines the tenant to a few servers few others share
Too much traffic overall Load shedding Rejects the excess early, the subject of the next lesson

Find the row by the shape of the failure, and expect to need more than one. In the thread simulation the hanging recommendations dependency needed the first two rows together: the bulkhead kept search and profiles at 100 %, and the breaker on top answered 73.5 % of the recommendation requests with a cached list instead of an error.

Checkpoint

Check: Choosing the tool for a failure

  1. Question 1 of 2 One tenant of a shared API sends requests that crash any server they reach. Which tool limits how many other tenants lose service?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Shuffle sharding, so that few tenants share all of their servers with the bad one

    The problem is a bad tenant reaching many servers. Shuffle sharding confines it to its own small set, and other tenants overlap that set rarely and partly. Longer timeouts and more retries make it worse, and breakers in the clients do not stop the crashing requests.

  2. Question 2 of 2 A dependency is down for ten minutes, and every call to it fails after a long wait. Which tool stops wasting calls on it?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A circuit breaker on that dependency

    Each tool answers a different shape of failure: a bulkhead caps what a slow dependency can hold, a breaker stops calling one that is down, retries with a budget turn brief errors into successes, and shuffle sharding contains a bad tenant.

Practise: the three states of a breaker

Finish a circuit breaker in Python that counts failures in a row, opens, waits and lets one trial call through, with a clock the tests move. Its sample tests run here:

Exercise · Medium · Python

The three states of a circuit breaker

Finish the class Breaker in breaker.py: a circuit breaker that counts consecutive failures. Its state is "closed", "open" or "half-open", and clock is a function that returns the current time in seconds, so that the tests can move time forward.

  • Closed: allow() returns True. on_failure() adds one to a count of failures in a row, and on_success() sets it back to 0. When the count reaches threshold, the breaker opens and remembers the time.
  • Open: allow() returns False, until cooldown seconds have passed since it opened. Then the breaker becomes half-open, and that call to allow() returns True: it is the trial call.
  • Half-open: only one trial call at a time, so allow() returns False while the trial is out. If the trial succeeds (on_success()), the breaker closes and the count starts again from 0. If it fails (on_failure()), the breaker opens again, and the cooldown starts again from that moment.

For example, with threshold=3 and cooldown=10, three failures in a row open the breaker; ten seconds later one call is allowed through, and its success closes the breaker.

Starter code · breaker.py

class Breaker:
    """A circuit breaker that opens after `threshold` failures in a row and tries again after `cooldown` seconds."""

    def __init__(self, threshold, cooldown, clock):
        self.threshold = threshold
        self.cooldown = cooldown
        self.clock = clock
        self.state = "closed"
        # Add what else the breaker needs to remember.

    def allow(self):
        """May the next call go to the dependency?"""
        # Replace this line with your code.
        return True

    def on_success(self):
        """The call that allow() let through succeeded."""
        # Replace this line with your code.
        pass

    def on_failure(self):
        """The call that allow() let through failed."""
        # Replace this line with your code.
        pass
The sample tests · test_breaker.py
from breaker import Breaker


class Clock:
    def __init__(self):
        self.now = 0.0

    def __call__(self):
        return self.now


def test_opens_after_threshold():
    """three failures in a row open the breaker, and an open breaker fails fast"""
    clock = Clock()
    b = Breaker(threshold=3, cooldown=10, clock=clock)
    for _ in range(3):
        assert b.allow() is True
        b.on_failure()
    assert b.state == "open"
    assert b.allow() is False


def test_success_resets_the_count():
    """a success between failures starts the count again"""
    b = Breaker(threshold=3, cooldown=10, clock=Clock())
    for ok in (False, False, True, False, False):
        assert b.allow() is True
        b.on_success() if ok else b.on_failure()
    assert b.state == "closed"
    b.on_failure()
    assert b.state == "open"


def test_stays_open_during_cooldown():
    """an open breaker refuses calls until the cooldown has passed"""
    clock = Clock()
    b = Breaker(threshold=2, cooldown=10, clock=clock)
    b.on_failure()
    b.on_failure()
    clock.now = 9.9
    assert b.allow() is False
    assert b.state == "open"


def test_one_trial_after_cooldown():
    """after the cooldown one trial call goes through, and only one at a time"""
    clock = Clock()
    b = Breaker(threshold=2, cooldown=10, clock=clock)
    b.on_failure()
    b.on_failure()
    clock.now = 10.0
    assert b.allow() is True
    assert b.state == "half-open"
    assert b.allow() is False


def test_trial_success_closes():
    """a successful trial closes the breaker, with the count back at zero"""
    clock = Clock()
    b = Breaker(threshold=2, cooldown=10, clock=clock)
    b.on_failure()
    b.on_failure()
    clock.now = 12.0
    assert b.allow() is True
    b.on_success()
    assert b.state == "closed"
    assert b.allow() is True
    b.on_failure()
    assert b.state == "closed"


def test_trial_failure_reopens():
    """a failed trial opens the breaker again, and the cooldown starts from that moment"""
    clock = Clock()
    b = Breaker(threshold=2, cooldown=10, clock=clock)
    b.on_failure()
    b.on_failure()
    clock.now = 10.0
    assert b.allow() is True
    b.on_failure()
    assert b.state == "open"
    clock.now = 19.0
    assert b.allow() is False
    clock.now = 20.0
    assert b.allow() is True
    assert b.state == "half-open"
A hint

Keep four things: the state, the count of failures in a row, the time the breaker opened, and whether a trial call is out. Do the "has the cooldown passed?" check at the start of allow(): that is the moment an open breaker becomes half-open. In on_failure(), a failure while half-open opens the breaker at once, whatever the count.

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 work through breakers, bulkheads and shards one question at a time; each answer decides whether the next question is easier or harder, and the ideas you miss come first:

Practice that adapts to you

Practise this lesson

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

  1. Question 1 of 11 On a normal day, search gets 300 calls a second of 20 ms, profiles 200 of 30 ms and recommendations 100 of 40 ms. How many threads do they hold together?

    Type a number.

    Show the answer: Question 1 of 11

    Answer: 16 threads

    By Little's law: 300 × 0.02 = 6, 200 × 0.03 = 6 and 100 × 0.04 = 4, so 16 threads, a twelfth of the pool. The same law turns into 500 for recommendations alone once its calls wait 5 seconds each.

  2. Question 2 of 11 A pool has 200 threads, and a hanging dependency takes 100 new threads a second, each held for 5 seconds. After about how many seconds is the pool full?

    Type a number.

    Show the answer: Question 2 of 11

    Answer: 2 seconds (anything from 1.8 to 2.2 counts)

    No thread comes back for 5 seconds, so 100 a second fill the 200 threads in about 2 seconds. From then on every request for any endpoint waits for a thread that a recommendations call holds.

  3. Question 3 of 11 What does a bulkhead cost, by the Azure pattern the lesson cites?

    Choose one answer.

    Show the answer: Question 3 of 11

    Answer: Reserved capacity that sits idle while its dependency is quiet, a less efficient use of resources

    Each compartment is reserved, so its threads or connections cannot serve other work even when its dependency is idle. That is the price of making sure one failing dependency cannot take them all.

  4. Question 4 of 11 What do Envoy's "circuit breakers" actually do?

    Choose one answer.

    Show the answer: Question 4 of 11

    Answer: They cap the connections, pending requests, active requests and retries per upstream cluster, and fail requests over a cap at once

    Envoy's caps work like bulkheads outside the application: 1,024 connections per upstream cluster by default, and requests over a cap fail at once. Its documentation's principle is that failing quickly and pushing back early is nearly always better than waiting.

  5. Question 5 of 11 Why does the half-open state let only a few trial calls through instead of closing at once?

    Choose one answer.

    Show the answer: Question 5 of 11

    Answer: A dependency that has just recovered may fall over again under the full load at once

    A recovering service may cope with a trickle and not with the full flood. A few trial calls test it gently; success closes the breaker, and a failure sends it back to open for another wait.

  6. Question 6 of 11 A data store with 16 shards sits behind a single circuit breaker, and one shard fails. What goes wrong?

    Choose one answer.

    Show the answer: Question 6 of 11

    Answer: The breaker opens on that shard's failures and blocks the 15 healthy shards as well

    Use one breaker per independent failure domain. A single breaker in front of many shards turns the failure of one into a refusal of all, which the Azure pattern warns about.

  7. Question 7 of 11 Should the retry logic around a call retry it when an open breaker refused it?

    Choose one answer.

    Show the answer: Question 7 of 11

    Answer: No, because a call the breaker refused is not a transient fault

    Make retries respect the breaker: an open breaker means stop calling for now, so the retry logic should stop too and let the caller use its fallback or report the error.

  8. Question 8 of 11 With plain sharding of 8 workers into 4 fixed shards of 2, what share of the customers shares the bad customer's shard?

    Type a number.

    Show the answer: Question 8 of 11

    Answer: 25 %

    A quarter of the customers belong to each of the 4 shards, so 25 % go down with the bad customer's shard. In the run 249 of 999 lost service, against 36 with shuffle sharding.

  9. Question 9 of 11 With 64 workers and 4 per customer, about 23 % of customers share at least one worker with a bad customer. Why do almost none of them lose service?

    Choose one answer.

    Show the answer: Question 9 of 11

    Answer: Each keeps at least one healthy worker and retries on it; only a customer who shares all 4, 1 in 635,376, loses service

    Sharing some workers is common, sharing all of them is rare, and only that takes a customer down, provided clients retry on the other workers of their shard.

  10. Question 10 of 11 A healthy dependency fails about 1 call in 200 at random, briefly. Which tool fits?

    Choose one answer.

    Show the answer: Question 10 of 11

    Answer: Retries with backoff and a budget

    Match the tool to the failure: brief, random errors call for retries with backoff and a budget; a dependency down for minutes for a breaker; a slow one for a bulkhead; a bad tenant for shuffle sharding.

  11. Question 11 of 11 Every dependency is healthy, but traffic overall is far above what the service can finish. Which tool from the lesson's table answers that?

    Choose one answer.

    Show the answer: Question 11 of 11

    Answer: Load shedding, which rejects the excess early

    The table's last row is the next lesson's subject: when the total load is the problem, refuse the excess early and cheaply, so the work the service accepts is still finished in time.

Permutation & Combination Calculator Count the possible shuffle shards, n choose k, for your own fleet and shard sizes. Python Online Compiler Change the bulkhead limit or the breaker's window in the simulations above and run them again.

Design practice: failures that spread

Isolation questions in a design round begin with one part that took others down. Pick your first move for each brief, then weigh it against the thread simulation and the shard odds above:

Checkpoint

Your first decision

  1. Question 1 of 2 Design brief: a product page calls a recommendations service that slowed from 40 ms to 4 seconds, and the whole page went down, including parts that never call it. What is your first change?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Give the recommendations calls their own small pool, sized from Little's law, with a timeout

    The page went down because one slow dependency held the threads every request needed. A bulkhead puts a wall around those calls, and a timeout and a breaker keep them short; the fallback decides what the page shows meanwhile.

  2. Question 2 of 2 Design brief: one tenant's malformed requests crash any server they reach, and its client retries each crash on another server. What do you change first?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Confine each tenant to a small shuffle shard of servers, so its retries can reach only its own few

    The damage spreads because any server can take any request, so the retries carry the crash everywhere. Shuffle sharding limits where a tenant's requests can go, and per-tenant limits or a quarantine can then stop the tenant itself.

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

  1. Fresher to senior

    Your product page calls a recommendations service that slowed from 40 ms to 4 seconds, and the whole page went down, including the parts that never call recommendations. Explain the mechanism with numbers, and say what you would change.

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

  2. Senior to staff

    A multi-tenant API runs on 32 servers. One tenant's malformed requests crash whichever server receives them, and its client retries each crash on another server. Design the isolation so that this tenant affects as few other tenants as possible, with numbers.

    Model answer, Pro. First step and follow-ups

Interview questions

Warm-up (fresher to mid level): what are the three states of a circuit breaker, and why does the half-open state exist? Closed is normal: calls go through and the breaker counts recent failures. When the failures pass a threshold, the breaker opens: calls fail at once, with an error or a fallback, so callers stop waiting on a broken dependency and the dependency gets less load. After a timer runs out, the breaker turns half-open and lets a few trial calls through. If they succeed it closes; if one fails it opens again and restarts the timer. The half-open state exists because a service that has just recovered may handle a trickle of requests and not the full load at once, so the breaker tests it gently before sending everything back.

Key takeaways

  • One slow dependency can hold every thread: during a hang its calls in flight are its rate times its timeout. In the simulation, 200 threads and one hanging dependency left only 41 % of unrelated requests working.
  • A bulkhead gives each dependency or tenant its own pool. Size it from Little’s law with headroom, for example 4 in flight normally and a limit of 20.
  • A circuit breaker is closed, open or half-open. It fails fast while a dependency is broken and tests recovery with a few trial calls, at the price of a slower return to normal.
  • Use one breaker per independent failure domain, never retry a call the breaker refused, and exercise the open path and its fallback regularly.
  • Shuffle sharding gives each customer a random small set of servers: with 8 workers and pairs, 1 customer in 28 shares a bad customer’s servers, against 1 in 4 with plain sharding. Clients must retry on their other servers.

Terms in this lesson

bulkhead
A separate, limited share of threads, connections or queue slots for one dependency or one tenant, so that a slow or broken one can use up only its own share and not everyone's.
circuit breaker
A proxy around calls to a dependency that stops sending them for a while once too many fail: callers fail fast instead of waiting, and after a timer a few trial calls decide whether it closes again.
fallback
What a caller does instead of a call that failed or was refused, such as serving a cached answer or a default. It runs only during failures, so it needs regular exercise to stay working.
half-open
The state of a circuit breaker after its open timer runs out, in which a limited number of trial calls go through: if they succeed the breaker closes, and if one fails it opens again.

Corrections

  • The shuffle-sharding table is now read as the program prints it: sharing some workers with a bad customer stays common in the smaller fleets, while sharing all of them is rare in every fleet.
  • Resilience4j opens on its own share of slow calls rather than counting them as failures, and the Azure pattern gives less efficient use of resources as one reason against bulkheads.

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.