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.
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 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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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
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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
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):
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.
- Closed: calls go through to the dependency, and the breaker counts the failures. When the failures pass the threshold, the breaker moves to open.
- Open: calls fail at once, without reaching the dependency, while a timer runs. When the timer runs out, the breaker moves to half-open.
- 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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 66 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 152 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 8 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 20 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 717 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 184 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 10 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
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:
The drawing shows the whole scene; its 8 steps are listed below.
Every step as text
- 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.
- 20 s. The dependency goes down. Calls still go through, because the breaker has seen only one failure in its last 10 calls.
- 24 s. The fifth failure in a row makes 5 of the last 10 calls failures, the 50 % threshold, and the breaker opens.
- 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.
- 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.
- 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.
- 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.
- 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:
- 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.
- 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.
- 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
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).
# 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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
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
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()returnsTrue.on_failure()adds one to a count of failures in a row, andon_success()sets it back to 0. When the count reachesthreshold, the breaker opens and remembers the time. - Open:
allow()returnsFalse, untilcooldownseconds have passed since it opened. Then the breaker becomes half-open, and that call toallow()returnsTrue: it is the trial call. - Half-open: only one trial call at a time, so
allow()returnsFalsewhile 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.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Then 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.
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
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
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.
-
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.
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
- Circuit Breaker pattern (Azure Architecture Center) (Microsoft)
- Bulkhead pattern (Azure Architecture Center) (Microsoft)
- Workload isolation using shuffle-sharding (Amazon Builders' Library) (Amazon Web Services)
- Avoiding fallback in distributed systems (Amazon Builders' Library) (Amazon Web Services)
- Timeouts, retries, and backoff with jitter (Amazon Builders' Library) (Amazon Web Services)
- CircuitBreaker (Resilience4j documentation) (Resilience4j project)
- Bulkhead (Resilience4j documentation) (Resilience4j project)
- Circuit breaking (Envoy documentation) (Envoy Project Authors)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress