Circuit breaker for a payment gateway
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.
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 Circuit Breaker (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.
Task
The breaker wraps a call (call(action); in C# Execute, in Go Execute(func() error) error) and has three states:
| State | Call | Transitions |
|---|---|---|
| closed | the action runs | a success resets the failure count; failureThreshold failures in a row → open |
| open | an immediate error Circuit is open without running the action | openTimeout after opening the state reports half-open |
| half-open | the action runs as a trial | successThreshold successful trials → closed (counters reset); one failure → open again for a full timeout |
Additionally:
- the action's errors always reach the caller unchanged;
isFailure(error)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;- 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;
successThresholddefaults to 1.
Language details: TypeScript/JavaScript – an options object, CircuitOpenError, the state as a string; Python – CircuitBreaker(failure_threshold, open_timeout_ms, *, success_threshold, is_failure, now); C# – CircuitState { Closed, Open, HalfOpen }, TimeSpan, Func<DateTime>, CircuitOpenException; Java – CircuitState.HALF_OPEN, Supplier<T>, Predicate<RuntimeException>, LongSupplier; Go – a Settings struct (modelled on the sony/gobreaker library), the constants Closed, Open, HalfOpen and ErrCircuitOpen.
Topics: Circuit Breaker, Microservices
Related articles
- Circuit breaker: turning a slow failure into a fast one
The Circuit Breaker pattern from the ground up: closed, open and half-open states, thresholds and windows, filtering business errors, working with timeouts, retries and bulkheads. Configuration in Polly, opossum, Resilience4j, gobreaker…