8/12
Technical Architecture & AI Engineering · 7 min read

Circuit Breaker State Machine Wrapper for Flaky Downstream APIs

Implement an explicit CLOSED-OPEN-HALF_OPEN circuit breaker in TypeScript with single-probe concurrency gating, 4xx vs 5xx error classification, fallback handlers, and state transition hooks.

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 StateIncoming Call BehaviorTransition TriggerNext StateConcurrency Guard
CLOSEDExecutes downstream callRolling failures reach failureThreshold in rollingWindowMsOPENUnlimited concurrent calls
OPENFails fast (CircuitOpenError) or runs fallbacknowMs() >= openedAtMs + openCooldownMsHALF_OPENZero downstream calls
HALF_OPENTests downstream recovery with canary probehalfOpenSuccessThreshold probes pass -> CLOSED; any probe fails -> OPENCLOSED or OPENSingle-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)

typescript
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:

  1. 4xx ignored vs. 5xx trips: 10 HttpStatusError(400) calls keep state CLOSED; failureThreshold 503 calls flip CLOSED -> OPEN and invoke onStateChange.
  2. Fast-fail + fallback: While OPEN, execute(spy, () => fallbackVal) returns fallbackVal without calling spy.
  3. Single-probe HALF_OPEN gate: Advance past openCooldownMs, start one pending probe, fire a second concurrent execute(), and assert the second rejects immediately with CircuitOpenError.
  4. Recovery vs. re-open: A failed probe resets openedAtMs and flips back to OPEN; passing probes flip HALF_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).

MetricBeforeAfter
Cart preview p99 during vendor outage15,200 ms (504)11 ms (fallback)
Blast radius to login & dashboardsFull 25-min platform outage0 impact (100% up)
Recovery probes sent on vendor recovery400+ req/s stampede1 canary / 20s
False trips from bad ZIP codes (400)N/A0 (4xx excluded)

Common Failure Modes & Anti-Patterns

  1. Tripping on 400/404 client errors: One buggy frontend release sending invalid payloads opens the circuit for every customer. Fix: Classify 4xx as healthy downstream responses; count only 5xx, 429, and timeouts.
  2. Sharing one global breaker across unrelated dependencies: Lets a flaky reporting API trip authentication. Fix: Scope one CircuitBreaker per downstream dependency.
  3. Omitting outbound HTTP timeouts: A hung socket never throws, so the breaker never counts it. Fix: Always pair CircuitBreaker with AbortSignal.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 in transitionTo() so hooks fire reliably.
  • Gate HALF_OPEN with a single-probe lock: Prevent recovery thundering herds.
  • Classify errors carefully: Trip on 5xx, 429, and timeouts; never trip on 4xx.
  • 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.