Why This Matters at Engineering Leadership Scale
Cascading failures drive the worst Sev-1 outages in SaaS platforms. When a downstream tax, payment, or AI API stops failing fast and hangs for 30 seconds before timing out, waiting sockets pile up until every gateway pod starves its database pool and unrelated endpoints crash too.
A Circuit Breaker breaks that loop by failing fast in O(1) microseconds once a rolling failure threshold trips. In Atlassian M60/M70 and staff-level coding loops, this drill tests modeling explicit finite state machines cleanly instead of scattered boolean flags (isBroken, isTesting). At minute 30, adding fallback handlers, ignoring 400 Bad Request client errors, and emitting state-transition telemetry hooks fits straight into the state machine with zero rewrite.
Core Mental Model & Architecture
| Current State | Incoming Call Behavior | Transition Trigger | Next State | Concurrency Guard |
|---|---|---|---|---|
CLOSED | Executes downstream call | Rolling failures reach failureThreshold in rollingWindowMs | OPEN | Unlimited concurrent calls |
OPEN | Fails fast (CircuitOpenError) or runs fallback | nowMs() >= openedAtMs + openCooldownMs | HALF_OPEN | Zero downstream calls |
HALF_OPEN | Tests downstream recovery with canary probe | halfOpenSuccessThreshold probes pass -> CLOSED; any probe fails -> OPEN | CLOSED or OPEN | Single-probe gate (halfOpenProbeInFlight) blocks thundering herd |
Without the single-probe gate in HALF_OPEN, 500 QPS traffic rushes through the millisecond cooldown expires and immediately knocks the recovering dependency offline again. Gating HALF_OPEN lets exactly one probe test recovery while fast-failing the remaining 499 calls.
Step-by-Step Implementation Tutorial
1. Implement the Explicit State Machine, Error Classifier, Fallback, and Hooks (Minutes 5 to 28)
export type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
export interface Clock { nowMs(): number; }
export interface StateChangeEvent { from: CircuitState; to: CircuitState; timestampMs: number; reason: string; }
export interface CircuitBreakerOptions {
failureThreshold: number;
rollingWindowMs: number;
openCooldownMs: number;
halfOpenSuccessThreshold?: number;
// Minute-30 Extension: Ignore 4xx client errors; trip only on 5xx / 429 / timeouts
shouldRecordFailure?: (error: unknown) => boolean;
// Minute-30 Extension: Observability hook for alerts/metrics
onStateChange?: (event: StateChangeEvent) => void;
clock?: Clock;
}
export class CircuitOpenError extends Error {
constructor(public readonly retryAfterMs: number) {
super(`Circuit breaker is OPEN; retry after ${retryAfterMs}ms`);
this.name = "CircuitOpenError";
}
}
export class HttpStatusError extends Error {
constructor(public readonly statusCode: number, message: string) {
super(message);
this.name = "HttpStatusError";
}
}
export const defaultServerErrorClassifier = (err: unknown): boolean =>
err instanceof HttpStatusError ? err.statusCode >= 500 || err.statusCode === 429 : true;
export class CircuitBreaker {
private state: CircuitState = "CLOSED";
private failureTimestamps: number[] = [];
private openedAtMs = 0;
private halfOpenSuccesses = 0;
private halfOpenProbeInFlight = false;
private readonly clock: Clock;
private readonly halfOpenSuccessThreshold: number;
private readonly shouldRecordFailure: (error: unknown) => boolean;
private readonly onStateChange?: (event: StateChangeEvent) => void;
constructor(private readonly options: CircuitBreakerOptions) {
if (options.failureThreshold <= 0 || options.openCooldownMs <= 0 || options.rollingWindowMs <= 0) {
throw new Error("Thresholds and durations must be positive");
}
this.clock = options.clock ?? { nowMs: () => Date.now() };
this.halfOpenSuccessThreshold = options.halfOpenSuccessThreshold ?? 1;
this.shouldRecordFailure = options.shouldRecordFailure ?? defaultServerErrorClassifier;
this.onStateChange = options.onStateChange;
}
public getState(): CircuitState {
if (this.state === "OPEN" && this.clock.nowMs() >= this.openedAtMs + this.options.openCooldownMs) {
this.transitionTo("HALF_OPEN", "Cooldown elapsed");
}
return this.state;
}
// Minute-30 Extension: Optional fallback handler
public async execute<T>(action: () => Promise<T>, fallback?: (err: unknown) => Promise<T> | T): Promise<T> {
const now = this.clock.nowMs();
if (this.state === "OPEN") {
if (now >= this.openedAtMs + this.options.openCooldownMs) {
this.transitionTo("HALF_OPEN", "Cooldown elapsed");
} else {
const retryAfterMs = Math.max(0, this.openedAtMs + this.options.openCooldownMs - now);
return this.failOrFallback(new CircuitOpenError(retryAfterMs), fallback);
}
}
if (this.state === "HALF_OPEN") {
if (this.halfOpenProbeInFlight) {
return this.failOrFallback(new CircuitOpenError(this.options.openCooldownMs), fallback);
}
this.halfOpenProbeInFlight = true;
}
try {
const result = await action();
this.onSuccess();
return result;
} catch (error) {
this.onFailure(error);
return this.failOrFallback(error, fallback);
} finally {
if (this.state === "HALF_OPEN") this.halfOpenProbeInFlight = false;
}
}
private onSuccess(): void {
if (this.state !== "HALF_OPEN") return;
this.halfOpenProbeInFlight = false;
if (++this.halfOpenSuccesses >= this.halfOpenSuccessThreshold) {
this.failureTimestamps = [];
this.halfOpenSuccesses = 0;
this.transitionTo("CLOSED", "Half-open recovery succeeded");
}
}
private onFailure(error: unknown): void {
const now = this.clock.nowMs();
if (!this.shouldRecordFailure(error)) {
if (this.state === "HALF_OPEN") this.halfOpenProbeInFlight = false;
return;
}
if (this.state === "HALF_OPEN") {
this.halfOpenProbeInFlight = false;
this.halfOpenSuccesses = 0;
this.openedAtMs = now;
this.transitionTo("OPEN", "Half-open probe failed");
return;
}
const cutoff = now - this.options.rollingWindowMs;
while (this.failureTimestamps.length > 0 && this.failureTimestamps[0] <= cutoff) {
this.failureTimestamps.shift();
}
this.failureTimestamps.push(now);
if (this.failureTimestamps.length >= this.options.failureThreshold) {
this.openedAtMs = now;
this.transitionTo("OPEN", `Reached ${this.failureTimestamps.length} failures`);
}
}
private transitionTo(next: CircuitState, reason: string): void {
if (this.state === next) return;
const prev = this.state;
this.state = next;
this.onStateChange?.({ from: prev, to: next, timestampMs: this.clock.nowMs(), reason });
}
private async failOrFallback<T>(err: unknown, fallback?: (e: unknown) => Promise<T> | T): Promise<T> {
if (fallback) return fallback(err);
throw err;
}
}2. Write Unit Tests & Minute-30 Extension Walkthrough (Minutes 30 to 50)
Using a fake Clock, assert four behaviors:
4xxignored vs.5xxtrips: 10HttpStatusError(400)calls keep stateCLOSED;failureThreshold503calls flipCLOSED -> OPENand invokeonStateChange.- Fast-fail + fallback: While
OPEN,execute(spy, () => fallbackVal)returnsfallbackValwithout callingspy. - Single-probe
HALF_OPENgate: Advance pastopenCooldownMs, start one pending probe, fire a second concurrentexecute(), and assert the second rejects immediately withCircuitOpenError. - Recovery vs. re-open: A failed probe resets
openedAtMsand flips back toOPEN; passing probes flipHALF_OPEN -> CLOSED.
Worked Production Scenario: Before vs. After
Context: A B2B SaaS checkout service called an external tax API with a 15-second timeout and no circuit breaker. During a 25-minute vendor brownout, 24 Node.js pods queued thousands of 15-second sockets, exhausted PostgreSQL pools, and took down unrelated login and dashboard endpoints.
After: Payments wrapped the tax client in CircuitBreaker (failureThreshold: 5 in 30s, openCooldownMs: 20s, ignoring 400/422, exporting onStateChange gauges to Prometheus, and falling back to cached regional estimates on cart previews).
| Metric | Before | After |
|---|---|---|
| Cart preview p99 during vendor outage | 15,200 ms (504) | 11 ms (fallback) |
| Blast radius to login & dashboards | Full 25-min platform outage | 0 impact (100% up) |
| Recovery probes sent on vendor recovery | 400+ req/s stampede | 1 canary / 20s |
False trips from bad ZIP codes (400) | N/A | 0 (4xx excluded) |
Common Failure Modes & Anti-Patterns
- Tripping on
400/404client errors: One buggy frontend release sending invalid payloads opens the circuit for every customer. Fix: Classify4xxas healthy downstream responses; count only5xx,429, and timeouts. - Sharing one global breaker across unrelated dependencies: Lets a flaky reporting API trip authentication. Fix: Scope one
CircuitBreakerper downstream dependency. - Omitting outbound HTTP timeouts: A hung socket never throws, so the breaker never counts it. Fix: Always pair
CircuitBreakerwithAbortSignal.timeout(3000).
How to Handle Pushback in the Room
Skeptical Principal Engineer: "With 20 pods, each pod runs an independent breaker - won't pods probe separately?"
Calm Response: "Yes, and per-pod independence is a strength: it needs zero Redis coordination during an outage. Even 20 pods probing once per 20-second cooldown is 1 req/sec total versus 1,000 req/sec without a breaker."
Pushing Product Manager: "If we serve fallback responses while open, won't users see stale numbers?"
Calm Response: "Only on read paths like cart previews where an estimated tax badge beats an error screen. On financial writes like capturing payment, we omit the fallback so the breaker fails fast with a retryable 503."
Key Takeaways & This Week's Action Rep
- Model explicit states (
CLOSED,OPEN,HALF_OPEN): Centralize transitions intransitionTo()so hooks fire reliably. - Gate
HALF_OPENwith a single-probe lock: Prevent recovery thundering herds. - Classify errors carefully: Trip on
5xx,429, and timeouts; never trip on4xx. - Pair breakers with explicit timeouts: Hung sockets must time out quickly to feed the failure window.
This Week's Action Rep: Disable autocomplete for 45 minutes and implement CircuitBreaker with injected Clock, 4xx/5xx classification, fallback support, and the HALF_OPEN single-probe concurrency test.