Circuit Breaker With Half Open State

A typed circuit breaker that trips after consecutive failures, probes recovery in half open state, and resets after a success streak.

TypescriptData Fetching

Code

export type CircuitState = "closed" | "open" | "half-open";

export interface CircuitBreakerOptions {
  failureThreshold: number;
  resetTimeoutMs: number;
  successThreshold: number;
  now?: () => number;
}

export class CircuitBreaker {
  private state: CircuitState = "closed";
  private failures = 0;
  private successes = 0;
  private openedAt = 0;
  private readonly now: () => number;

  private readonly options: CircuitBreakerOptions;

  constructor(options: CircuitBreakerOptions) {
    this.options = options;
    this.now = options.now ?? (() => Date.now());
  }

  getState(): CircuitState {
    if (this.state === "open" && this.now() - this.openedAt >= this.options.resetTimeoutMs) {
      this.state = "half-open";
      this.successes = 0;
    }
    return this.state;
  }

  async call<T>(fn: () => Promise<T>): Promise<T> {
    const state = this.getState();
    if (state === "open") {
      throw new Error("circuit breaker is open");
    }
    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (err) {
      this.onFailure();
      throw err;
    }
  }

  private onSuccess(): void {
    this.failures = 0;
    if (this.getState() === "half-open") {
      this.successes += 1;
      if (this.successes >= this.options.successThreshold) {
        this.state = "closed";
        this.successes = 0;
      }
    }
  }

  private onFailure(): void {
    this.failures += 1;
    if (this.getState() === "half-open") {
      this.state = "open";
      this.openedAt = this.now();
      this.successes = 0;
      return;
    }
    if (this.failures >= this.options.failureThreshold) {
      this.state = "open";
      this.openedAt = this.now();
    }
  }
}

A flaky downstream service makes every request wait for timeouts, amplifying load instead of shedding it.

Use case: backend engineers wrapping unreliable downstream calls

Inputs / outputs

  • Input: a call function, failure threshold, reset timeout, half open probe count
  • Output: call results, or a rejected promise while the breaker is open

Error conditions

  • downstream call throws
  • breaker open (fast fail)
  • half open probe fails

Approach

closed/open/half-open state machine; consecutive failure counter trips to open; after resetTimeout one probe is allowed in half-open; success streak closes the breaker.

Implementation

export type CircuitState = "closed" | "open" | "half-open";

export interface CircuitBreakerOptions {
  failureThreshold: number;
  resetTimeoutMs: number;
  successThreshold: number;
  now?: () => number;
}

export class CircuitBreaker {
  private state: CircuitState = "closed";
  private failures = 0;
  private successes = 0;
  private openedAt = 0;
  private readonly now: () => number;

  private readonly options: CircuitBreakerOptions;

  constructor(options: CircuitBreakerOptions) {
    this.options = options;
    this.now = options.now ?? (() => Date.now());
  }

  getState(): CircuitState {
    if (this.state === "open" && this.now() - this.openedAt >= this.options.resetTimeoutMs) {
      this.state = "half-open";
      this.successes = 0;
    }
    return this.state;
  }

  async call<T>(fn: () => Promise<T>): Promise<T> {
    const state = this.getState();
    if (state === "open") {
      throw new Error("circuit breaker is open");
    }
    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (err) {
      this.onFailure();
      throw err;
    }
  }

  private onSuccess(): void {
    this.failures = 0;
    if (this.getState() === "half-open") {
      this.successes += 1;
      if (this.successes >= this.options.successThreshold) {
        this.state = "closed";
        this.successes = 0;
      }
    }
  }

  private onFailure(): void {
    this.failures += 1;
    if (this.getState() === "half-open") {
      this.state = "open";
      this.openedAt = this.now();
      this.successes = 0;
      return;
    }
    if (this.failures >= this.options.failureThreshold) {
      this.state = "open";
      this.openedAt = this.now();
    }
  }
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { CircuitBreaker } from "./example.ts";

function makeBreaker(now?: () => number) {
  return new CircuitBreaker({ failureThreshold: 2, resetTimeoutMs: 1000, successThreshold: 2, now });
}

test("opens after threshold consecutive failures", async () => {
  const b = makeBreaker();
  const boom = async (): Promise<number> => { throw new Error("down"); };
  await assert.rejects(b.call(boom));
  assert.equal(b.getState(), "closed");
  await assert.rejects(b.call(boom));
  assert.equal(b.getState(), "open");
});

test("fast fails while open without calling downstream", async () => {
  const b = makeBreaker();
  await assert.rejects(b.call(async (): Promise<number> => { throw new Error("x"); }));
  await assert.rejects(b.call(async (): Promise<number> => { throw new Error("x"); }));
  assert.equal(b.getState(), "open");
  let called = 0;
  await assert.rejects(b.call(async () => { called += 1; return 1; }));
  assert.equal(called, 0);
});

test("half-open success streak closes the breaker", async () => {
  let t = 0;
  const b = makeBreaker(() => t);
  const boom = async () => { throw new Error("x"); };
  await assert.rejects(b.call(boom));
  await assert.rejects(b.call(boom));
  assert.equal(b.getState(), "open");
  t += 1001;
  assert.equal(b.getState(), "half-open");
  assert.equal(await b.call(async () => 42), 42);
  assert.equal(b.getState(), "half-open");
  assert.equal(await b.call(async () => 43), 43);
  assert.equal(b.getState(), "closed");
});

test("half-open failure reopens immediately", async () => {
  let t = 0;
  const b = makeBreaker(() => t);
  await assert.rejects(b.call(async (): Promise<number> => { throw new Error("x"); }));
  await assert.rejects(b.call(async (): Promise<number> => { throw new Error("x"); }));
  t += 1001;
  assert.equal(b.getState(), "half-open");
  await assert.rejects(b.call(async (): Promise<number> => { throw new Error("still down"); }));
  assert.equal(b.getState(), "open");
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts

Limitations and error handling

single-process in-memory state; no persistence across restarts; no jitter on probe.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic