{"id":"6b093dc291bd8fbaf2a0c8d8","slug":"payment-circuit-breaker","title":"Circuit breaker for a payment gateway","summary":"A circuit breaker with closed, open and half-open states, an injected clock, a trial-success threshold and a business-error filter – so a payment gateway outage does not take the whole shop down.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"architecture","status":"published","difficulty":"hard","topics":["circuit-breaker","microservices"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["circuit-breaker","resilience","fault-tolerance","state-machine","payments"],"languages":[{"lang":"typescript","runner":"browser","starter":"type BreakerState = 'closed' | 'open' | 'half-open';\n\ninterface BreakerOptions {\n  /** Consecutive failures in `closed` that open the circuit. */\n  failureThreshold: number;\n  /** How long the circuit stays open before a trial call is allowed. */\n  openTimeoutMs: number;\n  /** Successful trial calls in `half-open` needed to close the circuit (default 1). */\n  successThreshold?: number;\n  /** Which errors count as failures (default: all). Other errors are rethrown but ignored by the breaker. */\n  isFailure?: (error: unknown) => boolean;\n  /** Clock in milliseconds (default Date.now). */\n  now?: () => number;\n}\n\nclass CircuitOpenError extends Error {\n  constructor() {\n    super('Circuit is open');\n    this.name = 'CircuitOpenError';\n  }\n}\n\n/**\n * closed    → calls pass; a success resets the failure count; failureThreshold failures in a row → open.\n * open      → calls fail fast with CircuitOpenError WITHOUT running the action;\n *             once openTimeoutMs has passed since opening, `state` reports 'half-open'.\n * half-open → calls pass as trials; successThreshold successes → closed (counters reset); one failure → open again.\n * The action's own errors are always rethrown unchanged.\n */\nclass CircuitBreaker {\n  constructor(private readonly options: BreakerOptions) {}\n\n  get state(): BreakerState {\n    throw new Error('Not implemented');\n  }\n\n  call<T>(action: () => T): T {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":9,"tests":"function testClock() {\n  const clock = { t: 0, now: () => clock.t };\n  return clock;\n}\n\nconst gatewayDown = () => {\n  throw new Error('Gateway timeout');\n};\nconst charge = () => 'paid';\n\n/** Calls through the breaker and swallows the error – handy for setting up a state. */\nfunction attempt(breaker, action) {\n  try {\n    return breaker.call(action);\n  } catch (error) {\n    return error;\n  }\n}\n\nfunction openBreaker(clock, extra = {}) {\n  const breaker = new CircuitBreaker({ failureThreshold: 3, openTimeoutMs: 30000, now: clock.now, ...extra });\n  for (let i = 0; i < 3; i++) attempt(breaker, gatewayDown);\n  return breaker;\n}\n\ntest('a closed breaker passes results and errors through', () => {\n  const breaker = new CircuitBreaker({ failureThreshold: 3, openTimeoutMs: 30000, now: testClock().now });\n  expect(breaker.state).toBe('closed');\n  expect(breaker.call(charge)).toBe('paid');\n  expect(() => breaker.call(gatewayDown)).toThrow('Gateway timeout');\n  expect(breaker.state).toBe('closed');\n});\n\ntest('consecutive failures open the circuit', () => {\n  const breaker = new CircuitBreaker({ failureThreshold: 3, openTimeoutMs: 30000, now: testClock().now });\n  attempt(breaker, gatewayDown);\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('closed');\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('open');\n});\n\ntest('a success resets the count of failures', () => {\n  const breaker = new CircuitBreaker({ failureThreshold: 3, openTimeoutMs: 30000, now: testClock().now });\n  attempt(breaker, gatewayDown);\n  attempt(breaker, gatewayDown);\n  breaker.call(charge);\n  attempt(breaker, gatewayDown);\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('closed');\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('open');\n});\n\ntest('an open circuit fails fast without calling the gateway', () => {\n  const breaker = openBreaker(testClock());\n  let calls = 0;\n  const spy = () => {\n    calls++;\n    return 'paid';\n  };\n  expect(() => breaker.call(spy)).toThrow(CircuitOpenError);\n  expect(() => breaker.call(spy)).toThrow('Circuit is open');\n  expect(calls).toBe(0);\n});\n\ntest('after the open timeout the breaker becomes half-open', () => {\n  const clock = testClock();\n  clock.t = 1000;\n  const breaker = openBreaker(clock);\n  clock.t = 30999;\n  expect(breaker.state).toBe('open');\n  clock.t = 31000;\n  expect(breaker.state).toBe('half-open');\n});\n\ntest('a successful trial call closes the circuit and resets the counters', () => {\n  const clock = testClock();\n  const breaker = openBreaker(clock);\n  clock.t = 30000;\n  expect(breaker.call(charge)).toBe('paid');\n  expect(breaker.state).toBe('closed');\n  attempt(breaker, gatewayDown);\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('closed');\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('open');\n});\n\ntest('a failed trial call opens the circuit again for a full timeout', () => {\n  const clock = testClock();\n  const breaker = openBreaker(clock);\n  clock.t = 31000;\n  expect(() => breaker.call(gatewayDown)).toThrow('Gateway timeout');\n  expect(breaker.state).toBe('open');\n  clock.t = 60999;\n  expect(breaker.state).toBe('open');\n  clock.t = 61000;\n  expect(breaker.state).toBe('half-open');\n});\n\ntest('successThreshold requires several successful trial calls', () => {\n  const clock = testClock();\n  const breaker = openBreaker(clock, { successThreshold: 2 });\n  clock.t = 30000;\n  breaker.call(charge);\n  expect(breaker.state).toBe('half-open');\n  breaker.call(charge);\n  expect(breaker.state).toBe('closed');\n});\n\ntest('errors filtered out by isFailure do not trip the breaker', () => {\n  class CardDeclined extends Error {}\n  const declined = () => {\n    throw new CardDeclined('Card declined');\n  };\n  const breaker = new CircuitBreaker({\n    failureThreshold: 3,\n    openTimeoutMs: 30000,\n    now: testClock().now,\n    isFailure: (error) => !(error instanceof CardDeclined),\n  });\n  for (let i = 0; i < 5; i++) expect(() => breaker.call(declined)).toThrow(CardDeclined);\n  expect(breaker.state).toBe('closed');\n  for (let i = 0; i < 3; i++) attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('open');\n});\n"},{"lang":"javascript","runner":"browser","starter":"// States: 'closed' | 'open' | 'half-open'\n// Options: { failureThreshold, openTimeoutMs, successThreshold = 1, isFailure = () => true, now = Date.now }\n\nclass CircuitOpenError extends Error {\n  constructor() {\n    super('Circuit is open');\n    this.name = 'CircuitOpenError';\n  }\n}\n\n/**\n * closed    → calls pass; a success resets the failure count; failureThreshold failures in a row → open.\n * open      → calls fail fast with CircuitOpenError WITHOUT running the action;\n *             once openTimeoutMs has passed since opening, `state` reports 'half-open'.\n * half-open → calls pass as trials; successThreshold successes → closed (counters reset); one failure → open again.\n * Errors for which isFailure(error) is false are rethrown but ignored by the breaker.\n * The action's own errors are always rethrown unchanged.\n */\nclass CircuitBreaker {\n  constructor(options) {\n    this.options = options;\n  }\n\n  get state() {\n    throw new Error('Not implemented');\n  }\n\n  call(action) {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":9,"tests":"function testClock() {\n  const clock = { t: 0, now: () => clock.t };\n  return clock;\n}\n\nconst gatewayDown = () => {\n  throw new Error('Gateway timeout');\n};\nconst charge = () => 'paid';\n\n/** Calls through the breaker and swallows the error – handy for setting up a state. */\nfunction attempt(breaker, action) {\n  try {\n    return breaker.call(action);\n  } catch (error) {\n    return error;\n  }\n}\n\nfunction openBreaker(clock, extra = {}) {\n  const breaker = new CircuitBreaker({ failureThreshold: 3, openTimeoutMs: 30000, now: clock.now, ...extra });\n  for (let i = 0; i < 3; i++) attempt(breaker, gatewayDown);\n  return breaker;\n}\n\ntest('a closed breaker passes results and errors through', () => {\n  const breaker = new CircuitBreaker({ failureThreshold: 3, openTimeoutMs: 30000, now: testClock().now });\n  expect(breaker.state).toBe('closed');\n  expect(breaker.call(charge)).toBe('paid');\n  expect(() => breaker.call(gatewayDown)).toThrow('Gateway timeout');\n  expect(breaker.state).toBe('closed');\n});\n\ntest('consecutive failures open the circuit', () => {\n  const breaker = new CircuitBreaker({ failureThreshold: 3, openTimeoutMs: 30000, now: testClock().now });\n  attempt(breaker, gatewayDown);\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('closed');\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('open');\n});\n\ntest('a success resets the count of failures', () => {\n  const breaker = new CircuitBreaker({ failureThreshold: 3, openTimeoutMs: 30000, now: testClock().now });\n  attempt(breaker, gatewayDown);\n  attempt(breaker, gatewayDown);\n  breaker.call(charge);\n  attempt(breaker, gatewayDown);\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('closed');\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('open');\n});\n\ntest('an open circuit fails fast without calling the gateway', () => {\n  const breaker = openBreaker(testClock());\n  let calls = 0;\n  const spy = () => {\n    calls++;\n    return 'paid';\n  };\n  expect(() => breaker.call(spy)).toThrow(CircuitOpenError);\n  expect(() => breaker.call(spy)).toThrow('Circuit is open');\n  expect(calls).toBe(0);\n});\n\ntest('after the open timeout the breaker becomes half-open', () => {\n  const clock = testClock();\n  clock.t = 1000;\n  const breaker = openBreaker(clock);\n  clock.t = 30999;\n  expect(breaker.state).toBe('open');\n  clock.t = 31000;\n  expect(breaker.state).toBe('half-open');\n});\n\ntest('a successful trial call closes the circuit and resets the counters', () => {\n  const clock = testClock();\n  const breaker = openBreaker(clock);\n  clock.t = 30000;\n  expect(breaker.call(charge)).toBe('paid');\n  expect(breaker.state).toBe('closed');\n  attempt(breaker, gatewayDown);\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('closed');\n  attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('open');\n});\n\ntest('a failed trial call opens the circuit again for a full timeout', () => {\n  const clock = testClock();\n  const breaker = openBreaker(clock);\n  clock.t = 31000;\n  expect(() => breaker.call(gatewayDown)).toThrow('Gateway timeout');\n  expect(breaker.state).toBe('open');\n  clock.t = 60999;\n  expect(breaker.state).toBe('open');\n  clock.t = 61000;\n  expect(breaker.state).toBe('half-open');\n});\n\ntest('successThreshold requires several successful trial calls', () => {\n  const clock = testClock();\n  const breaker = openBreaker(clock, { successThreshold: 2 });\n  clock.t = 30000;\n  breaker.call(charge);\n  expect(breaker.state).toBe('half-open');\n  breaker.call(charge);\n  expect(breaker.state).toBe('closed');\n});\n\ntest('errors filtered out by isFailure do not trip the breaker', () => {\n  class CardDeclined extends Error {}\n  const declined = () => {\n    throw new CardDeclined('Card declined');\n  };\n  const breaker = new CircuitBreaker({\n    failureThreshold: 3,\n    openTimeoutMs: 30000,\n    now: testClock().now,\n    isFailure: (error) => !(error instanceof CardDeclined),\n  });\n  for (let i = 0; i < 5; i++) expect(() => breaker.call(declined)).toThrow(CardDeclined);\n  expect(breaker.state).toBe('closed');\n  for (let i = 0; i < 3; i++) attempt(breaker, gatewayDown);\n  expect(breaker.state).toBe('open');\n});\n"},{"lang":"python","runner":"browser","starter":"import time\nfrom typing import Callable\n\n\nclass CircuitOpenError(Exception):\n    def __init__(self):\n        super().__init__(\"Circuit is open\")\n\n\nclass CircuitBreaker:\n    \"\"\"States: 'closed' | 'open' | 'half-open'.\n    closed    → calls pass; a success resets the failure count; failure_threshold failures in a row → open.\n    open      → calls fail fast with CircuitOpenError WITHOUT running the action;\n                once open_timeout_ms has passed since opening, `state` reports 'half-open'.\n    half-open → calls pass as trials; success_threshold successes → closed (counters reset); one failure → open again.\n    Exceptions for which is_failure(exc) is False are re-raised but ignored by the breaker.\n    The action's own exceptions are always re-raised unchanged.\"\"\"\n\n    def __init__(\n        self,\n        failure_threshold: int,\n        open_timeout_ms: float,\n        *,\n        success_threshold: int = 1,\n        is_failure: Callable[[BaseException], bool] | None = None,\n        now: Callable[[], float] | None = None,\n    ):\n        self.failure_threshold = failure_threshold\n        self.open_timeout_ms = open_timeout_ms\n        self.success_threshold = success_threshold\n        self.is_failure = is_failure or (lambda exc: True)\n        self.now = now or (lambda: time.monotonic() * 1000)\n\n    @property\n    def state(self) -> str:\n        raise NotImplementedError\n\n    def call(self, action: Callable, *args, **kwargs):\n        raise NotImplementedError\n","testCount":9,"tests":"class FakeClock:\n    def __init__(self):\n        self.t = 0\n\n    def now(self):\n        return self.t\n\n\nclass GatewayTimeout(Exception):\n    pass\n\n\ndef gateway_down():\n    raise GatewayTimeout(\"Gateway timeout\")\n\n\ndef charge():\n    return \"paid\"\n\n\ndef attempt(breaker, action):\n    \"\"\"Calls through the breaker and swallows the exception – handy for setting up a state.\"\"\"\n    try:\n        return breaker.call(action)\n    except Exception as exc:\n        return exc\n\n\ndef open_breaker(clock, **extra):\n    breaker = CircuitBreaker(3, 30000, now=clock.now, **extra)\n    for _ in range(3):\n        attempt(breaker, gateway_down)\n    return breaker\n\n\ndef expect_state(breaker, want):\n    assert breaker.state == want, f\"expected {want!r}, got {breaker.state!r}\"\n\n\ndef test_a_closed_breaker_passes_results_and_errors_through():\n    breaker = CircuitBreaker(3, 30000, now=FakeClock().now)\n    expect_state(breaker, \"closed\")\n    assert breaker.call(charge) == \"paid\"\n    with raises(GatewayTimeout, match=\"Gateway timeout\"):\n        breaker.call(gateway_down)\n    expect_state(breaker, \"closed\")\n\n\ndef test_consecutive_failures_open_the_circuit():\n    breaker = CircuitBreaker(3, 30000, now=FakeClock().now)\n    attempt(breaker, gateway_down)\n    attempt(breaker, gateway_down)\n    expect_state(breaker, \"closed\")\n    attempt(breaker, gateway_down)\n    expect_state(breaker, \"open\")\n\n\ndef test_a_success_resets_the_count_of_failures():\n    breaker = CircuitBreaker(3, 30000, now=FakeClock().now)\n    attempt(breaker, gateway_down)\n    attempt(breaker, gateway_down)\n    breaker.call(charge)\n    attempt(breaker, gateway_down)\n    attempt(breaker, gateway_down)\n    expect_state(breaker, \"closed\")\n    attempt(breaker, gateway_down)\n    expect_state(breaker, \"open\")\n\n\ndef test_an_open_circuit_fails_fast_without_calling_the_gateway():\n    breaker = open_breaker(FakeClock())\n    calls = []\n\n    def spy():\n        calls.append(1)\n        return \"paid\"\n\n    with raises(CircuitOpenError, match=\"Circuit is open\"):\n        breaker.call(spy)\n    assert calls == [], f\"the action must not run, it ran {len(calls)} times\"\n\n\ndef test_after_the_open_timeout_the_breaker_becomes_half_open():\n    clock = FakeClock()\n    clock.t = 1000\n    breaker = open_breaker(clock)\n    clock.t = 30999\n    expect_state(breaker, \"open\")\n    clock.t = 31000\n    expect_state(breaker, \"half-open\")\n\n\ndef test_a_successful_trial_call_closes_the_circuit_and_resets_the_counters():\n    clock = FakeClock()\n    breaker = open_breaker(clock)\n    clock.t = 30000\n    assert breaker.call(charge) == \"paid\"\n    expect_state(breaker, \"closed\")\n    attempt(breaker, gateway_down)\n    attempt(breaker, gateway_down)\n    expect_state(breaker, \"closed\")\n    attempt(breaker, gateway_down)\n    expect_state(breaker, \"open\")\n\n\ndef test_a_failed_trial_call_opens_the_circuit_again_for_a_full_timeout():\n    clock = FakeClock()\n    breaker = open_breaker(clock)\n    clock.t = 31000\n    with raises(GatewayTimeout):\n        breaker.call(gateway_down)\n    expect_state(breaker, \"open\")\n    clock.t = 60999\n    expect_state(breaker, \"open\")\n    clock.t = 61000\n    expect_state(breaker, \"half-open\")\n\n\ndef test_success_threshold_requires_several_successful_trial_calls():\n    clock = FakeClock()\n    breaker = open_breaker(clock, success_threshold=2)\n    clock.t = 30000\n    breaker.call(charge)\n    expect_state(breaker, \"half-open\")\n    breaker.call(charge)\n    expect_state(breaker, \"closed\")\n\n\ndef test_errors_filtered_out_by_is_failure_do_not_trip_the_breaker():\n    class CardDeclined(Exception):\n        pass\n\n    def declined():\n        raise CardDeclined(\"Card declined\")\n\n    breaker = CircuitBreaker(3, 30000, now=FakeClock().now, is_failure=lambda exc: not isinstance(exc, CardDeclined))\n    for _ in range(5):\n        with raises(CardDeclined):\n            breaker.call(declined)\n    expect_state(breaker, \"closed\")\n    for _ in range(3):\n        attempt(breaker, gateway_down)\n    expect_state(breaker, \"open\")\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\n\npublic enum CircuitState { Closed, Open, HalfOpen }\n\npublic class CircuitOpenException : Exception\n{\n    public CircuitOpenException() : base(\"Circuit is open\") { }\n}\n\n/// <summary>\n/// Closed   → calls pass; a success resets the failure count; failureThreshold failures in a row → Open.\n/// Open     → calls fail fast with CircuitOpenException WITHOUT running the action;\n///            once openTimeout has passed since opening, State reports HalfOpen.\n/// HalfOpen → calls pass as trials; successThreshold successes → Closed (counters reset); one failure → Open again.\n/// Exceptions for which isFailure(e) is false are rethrown but ignored by the breaker.\n/// The action's own exceptions are always rethrown unchanged.\n/// </summary>\npublic class CircuitBreaker\n{\n    private readonly int failureThreshold;\n    private readonly TimeSpan openTimeout;\n    private readonly Func<DateTime> clock;\n    private readonly int successThreshold;\n    private readonly Func<Exception, bool> isFailure;\n\n    public CircuitBreaker(int failureThreshold, TimeSpan openTimeout, Func<DateTime> clock = null,\n        int successThreshold = 1, Func<Exception, bool> isFailure = null)\n    {\n        this.failureThreshold = failureThreshold;\n        this.openTimeout = openTimeout;\n        this.clock = clock ?? (() => DateTime.UtcNow);\n        this.successThreshold = successThreshold;\n        this.isFailure = isFailure ?? (e => true);\n    }\n\n    public CircuitState State { get { throw new NotImplementedException(); } }\n\n    public T Execute<T>(Func<T> action) { throw new NotImplementedException(); }\n}\n","testCount":9},{"lang":"java","runner":"judge0","starter":"import java.util.function.LongSupplier;\nimport java.util.function.Predicate;\nimport java.util.function.Supplier;\n\nenum CircuitState { CLOSED, OPEN, HALF_OPEN }\n\nclass CircuitOpenException extends RuntimeException {\n    CircuitOpenException() { super(\"Circuit is open\"); }\n}\n\n/**\n * CLOSED    → calls pass; a success resets the failure count; failureThreshold failures in a row → OPEN.\n * OPEN      → calls fail fast with CircuitOpenException WITHOUT running the action;\n *             once openTimeoutMillis has passed since opening, state() reports HALF_OPEN.\n * HALF_OPEN → calls pass as trials; successThreshold successes → CLOSED (counters reset); one failure → OPEN again.\n * Exceptions for which isFailure.test(e) is false are rethrown but ignored by the breaker.\n * The action's own exceptions are always rethrown unchanged.\n */\nclass CircuitBreaker {\n    private final int failureThreshold;\n    private final long openTimeoutMillis;\n    private final int successThreshold;\n    private final Predicate<RuntimeException> isFailure;\n    private final LongSupplier clock;\n\n    CircuitBreaker(int failureThreshold, long openTimeoutMillis, int successThreshold,\n                   Predicate<RuntimeException> isFailure, LongSupplier clock) {\n        this.failureThreshold = failureThreshold;\n        this.openTimeoutMillis = openTimeoutMillis;\n        this.successThreshold = successThreshold;\n        this.isFailure = isFailure;\n        this.clock = clock;\n    }\n\n    CircuitBreaker(int failureThreshold, long openTimeoutMillis, LongSupplier clock) {\n        this(failureThreshold, openTimeoutMillis, 1, e -> true, clock);\n    }\n\n    CircuitState state() { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    <T> T call(Supplier<T> action) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n","testCount":9},{"lang":"go","runner":"judge0","starter":"package main\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n// State of the breaker.\ntype State int\n\nconst (\n\tClosed State = iota\n\tOpen\n\tHalfOpen\n)\n\nfunc (s State) String() string {\n\tswitch s {\n\tcase Closed:\n\t\treturn \"closed\"\n\tcase Open:\n\t\treturn \"open\"\n\t}\n\treturn \"half-open\"\n}\n\n// ErrCircuitOpen is returned without running the action while the circuit is open.\nvar ErrCircuitOpen = errors.New(\"circuit is open\")\n\n// Settings configure the breaker. Zero values: SuccessThreshold → 1, IsFailure → every error counts,\n// Now → time.Now.\ntype Settings struct {\n\tFailureThreshold int           // failures in a row (in Closed) that open the circuit\n\tOpenTimeout      time.Duration // how long the circuit stays open before a trial call is allowed\n\tSuccessThreshold int           // successful trial calls in HalfOpen needed to close\n\tIsFailure        func(error) bool\n\tNow              func() time.Time\n}\n\n// CircuitBreaker:\n// Closed   → calls pass; a success resets the failure count; FailureThreshold failures in a row → Open.\n// Open     → Execute returns ErrCircuitOpen WITHOUT running the action;\n//            once OpenTimeout has passed since opening, State reports HalfOpen.\n// HalfOpen → calls pass as trials; SuccessThreshold successes → Closed (counters reset); one failure → Open again.\n// Errors for which IsFailure is false are returned but ignored by the breaker.\n// The action's own errors are always returned unchanged.\ntype CircuitBreaker struct {\n\tsettings Settings\n\t// TODO: state, counters, moment of opening\n}\n\n// NewCircuitBreaker applies the defaults.\nfunc NewCircuitBreaker(s Settings) *CircuitBreaker {\n\tif s.SuccessThreshold <= 0 {\n\t\ts.SuccessThreshold = 1\n\t}\n\tif s.IsFailure == nil {\n\t\ts.IsFailure = func(error) bool { return true }\n\t}\n\tif s.Now == nil {\n\t\ts.Now = time.Now\n\t}\n\treturn &CircuitBreaker{settings: s}\n}\n\n// State reports the current state (Open turns into HalfOpen after OpenTimeout).\nfunc (cb *CircuitBreaker) State() State {\n\t// TODO\n\treturn Closed\n}\n\n// Execute runs the action through the breaker.\nfunc (cb *CircuitBreaker) Execute(action func() error) error {\n\t// TODO\n\treturn errors.New(\"not implemented\")\n}\n","testCount":9}],"questionCount":null,"xp":40,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.251Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"On Friday at 8 p.m. the payment gateway started answering after 30 seconds, or not at all. The shop waited for every response, ran out of threads, and the catalog and cart went down together with payments. The "},{"type":"text","text":"Circuit Breaker","marks":[{"type":"bold"}]},{"type":"text","text":" (described by Michael Nygard in \"Release It!\") breaks the circuit: after a series of failures it stops calling the sick service and fails immediately, and after a while it carefully checks whether the service is back."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"The breaker wraps a call ("},{"type":"text","text":"call(action)","marks":[{"type":"code"}]},{"type":"text","text":"; in C# "},{"type":"text","text":"Execute","marks":[{"type":"code"}]},{"type":"text","text":", in Go "},{"type":"text","text":"Execute(func() error) error","marks":[{"type":"code"}]},{"type":"text","text":") and has three states:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"State"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Call"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Transitions"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"closed"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the action runs"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a success resets the failure count; "},{"type":"text","text":"failureThreshold","marks":[{"type":"code"}]},{"type":"text","text":" failures "},{"type":"text","text":"in a row","marks":[{"type":"bold"}]},{"type":"text","text":" → open"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"open"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"an immediate error","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"Circuit is open","marks":[{"type":"code"}]},{"type":"text","text":" without running the action"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"openTimeout","marks":[{"type":"code"}]},{"type":"text","text":" after opening the state reports half-open"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"half-open"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the action runs as a trial"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"successThreshold","marks":[{"type":"code"}]},{"type":"text","text":" successful trials → closed (counters reset); one failure → open again for a full timeout"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Additionally:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"the action's errors always reach the caller "},{"type":"text","text":"unchanged","marks":[{"type":"bold"}]},{"type":"text","text":";"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"isFailure(error)","marks":[{"type":"code"}]},{"type":"text","text":" decides which errors count (all by default) – a declined card is a business error, not a gateway outage, so it must not open the circuit;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"the clock is injected, and the open → half-open transition is lazy – it happens when the state is read or a call arrives after the timeout;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"successThreshold","marks":[{"type":"code"}]},{"type":"text","text":" defaults to 1."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Language details: TypeScript/JavaScript – an options object, "},{"type":"text","text":"CircuitOpenError","marks":[{"type":"code"}]},{"type":"text","text":", the state as a string; Python – "},{"type":"text","text":"CircuitBreaker(failure_threshold, open_timeout_ms, *, success_threshold, is_failure, now)","marks":[{"type":"code"}]},{"type":"text","text":"; C# – "},{"type":"text","text":"CircuitState { Closed, Open, HalfOpen }","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"TimeSpan","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Func<DateTime>","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"CircuitOpenException","marks":[{"type":"code"}]},{"type":"text","text":"; Java – "},{"type":"text","text":"CircuitState.HALF_OPEN","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Supplier<T>","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Predicate<RuntimeException>","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"LongSupplier","marks":[{"type":"code"}]},{"type":"text","text":"; Go – a "},{"type":"text","text":"Settings","marks":[{"type":"code"}]},{"type":"text","text":" struct (modelled on the sony/gobreaker library), the constants "},{"type":"text","text":"Closed","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Open","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"HalfOpen","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"ErrCircuitOpen","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b093dbf91bd8fbaf2a0c8a7","slug":"circuit-breaker","title":"Circuit breaker: turning a slow failure into a fast one"},{"id":"6b08bd3b80884893657cc9d2","slug":"monolith","title":"The Monolith: one application, one deployment, and why it is often the right start"},{"id":"6b08bd3b80884893657cc9c8","slug":"modular-monolith","title":"The Modular Monolith: hard boundaries without the cost of the network"},{"id":"6b08bd3a80884893657cc9be","slug":"microservices","title":"Microservices: independent deployments, real costs and when it pays off"},{"id":"6b08bd3880884893657cc98c","slug":"hexagonal-architecture","title":"Pierogi in the Hexagon"},{"id":"6b08bd3280884893657cc942","slug":"event-driven-architecture","title":"Event-driven architecture: who publishes, who listens and what can go wrong"}],"topicsInfo":[{"slug":"circuit-breaker","title":"Circuit Breaker","group":"architecture","icon":"zap-off"},{"slug":"microservices","title":"Microservices","group":"architecture","icon":"container"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:26.253Z","updatedAt":"2026-11-27T08:22:26.253Z"}