{"id":"6b093dc291bd8fbaf2a0c8d8","slug":"payment-circuit-breaker","title":"Bezpiecznik przed bramką płatności","summary":"Circuit breaker ze stanami zamknięty, otwarty i półotwarty, wstrzykiwanym zegarem, progiem prób testowych i filtrem błędów biznesowych – żeby awaria bramki płatności nie położyła całego sklepu.","servedLang":"pl","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":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"W piątek o 20:00 bramka płatności zaczęła odpowiadać po 30 sekundach albo wcale. Sklep czekał na każdą odpowiedź, wątki się skończyły, a razem z płatnościami przestał działać katalog i koszyk. "},{"type":"text","text":"Bezpiecznik","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"Circuit Breaker","marks":[{"type":"italic"}]},{"type":"text","text":", opisany przez Michaela Nygarda w „Release It!”) przerywa obwód: po serii awarii przestaje wołać chorą usługę i od razu zwraca błąd, a po pewnym czasie ostrożnie sprawdza, czy usługa wróciła."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"Bezpiecznik opakowuje wywołanie ("},{"type":"text","text":"call(action)","marks":[{"type":"code"}]},{"type":"text","text":"; w C# "},{"type":"text","text":"Execute","marks":[{"type":"code"}]},{"type":"text","text":", w Go "},{"type":"text","text":"Execute(func() error) error","marks":[{"type":"code"}]},{"type":"text","text":") i ma trzy stany:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Stan"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wywołanie"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przejścia"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zamknięty ("},{"type":"text","text":"closed","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"akcja się wykonuje"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"sukces zeruje licznik porażek; "},{"type":"text","text":"failureThreshold","marks":[{"type":"code"}]},{"type":"text","text":" porażek "},{"type":"text","text":"z rzędu","marks":[{"type":"bold"}]},{"type":"text","text":" → otwarty"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"otwarty ("},{"type":"text","text":"open","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"natychmiastowy błąd","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"Circuit is open","marks":[{"type":"code"}]},{"type":"text","text":" bez uruchamiania akcji"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"po "},{"type":"text","text":"openTimeout","marks":[{"type":"code"}]},{"type":"text","text":" od otwarcia stan zgłasza się jako półotwarty"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"półotwarty ("},{"type":"text","text":"half-open","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"akcja wykonuje się jako próba"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"successThreshold","marks":[{"type":"code"}]},{"type":"text","text":" udanych prób → zamknięty (liczniki od zera); jedna porażka → znowu otwarty na pełny czas"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Dodatkowo:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"błędy akcji zawsze wychodzą do wywołującego "},{"type":"text","text":"bez zmian","marks":[{"type":"bold"}]},{"type":"text","text":";"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"isFailure(error)","marks":[{"type":"code"}]},{"type":"text","text":" decyduje, które błędy się liczą (domyślnie wszystkie) – odrzucona karta to błąd biznesowy, a nie awaria bramki, więc nie powinna otwierać obwodu;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"zegar jest wstrzykiwany, a przejście z otwartego w półotwarty następuje leniwie – przy odczycie stanu lub przy wywołaniu po upływie czasu;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"successThreshold","marks":[{"type":"code"}]},{"type":"text","text":" domyślnie wynosi 1."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Szczegóły językowe: TypeScript/JavaScript – obiekt opcji, "},{"type":"text","text":"CircuitOpenError","marks":[{"type":"code"}]},{"type":"text","text":", stan jako napis; 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 – struktura "},{"type":"text","text":"Settings","marks":[{"type":"code"}]},{"type":"text","text":" (wzorowana na bibliotece sony/gobreaker), stałe "},{"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":" i "},{"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: bezpiecznik, który zamienia wolną awarię w szybką"},{"id":"6b08bd3b80884893657cc9d2","slug":"monolith","title":"Monolit: jedna aplikacja, jedno wdrożenie i dlaczego to często dobry start"},{"id":"6b08bd3b80884893657cc9c8","slug":"modular-monolith","title":"Modularny monolit: twarde granice bez kosztów sieci"},{"id":"6b08bd3a80884893657cc9be","slug":"microservices","title":"Mikroserwisy: niezależne wdrożenia, prawdziwe koszty i kiedy to się opłaca"},{"id":"6b08bd3880884893657cc98c","slug":"hexagonal-architecture","title":"Pierogi w Heksagonie"},{"id":"6b08bd3280884893657cc942","slug":"event-driven-architecture","title":"Architektura sterowana zdarzeniami: kto publikuje, kto słucha i co może pójść nie tak"}],"topicsInfo":[{"slug":"circuit-breaker","title":"Bezpiecznik (Circuit Breaker)","group":"architecture","icon":"zap-off"},{"slug":"microservices","title":"Mikroserwisy","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"}