Article · Circuit Breaker · Microservices
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 and pybreaker.
Friday, 8 p.m., peak shopping time. The payment gateway starts answering after 30 seconds, or not at all. The shop waits for every response, the thread and connection pools run dry, and a few minutes later nothing works – including the catalog and the cart, which have nothing to do with payments. One sick dependency took down the whole system. A Circuit Breaker works like the one in a home fuse box: after a series of failures it trips and lets no calls through for a while, then carefully checks whether they can resume.
- 3
- states – closed, open, half-open
- 2007
- "Release It!" – Michael Nygard describes the pattern in the context of production systems
- 2018
- Hystrix in maintenance mode – Netflix recommends Resilience4j as the successor
The problem: cascading failure
A service that does not answer right away is more dangerous than one that fails right away. Every gateway call holds a thread, an HTTP connection and memory for the whole wait. Under heavy traffic the resources run out within seconds, and further requests – even to other endpoints – queue up. On top of that, customers and their browsers retry, so the sick gateway gets even more traffic.
// No timeout, no breaker: every request waits as long as the gateway wants.
app.post("/checkout", async (req, res) => {
const receipt = await gateway.charge(req.body.order); // 30 s... or never
res.json(receipt);
});The solution: a state machine in front of the call
The breaker sits between the code and the dependency and has the same interface as the call it protects (structurally it is a proxy). In the closed state it lets traffic through and counts failures. When they cross the threshold it moves to open: for a set time it rejects calls immediately without touching the dependency. After that it moves to half-open and lets a few trial calls through – if they succeed it goes back to closed, if not it opens again.
| Setting | Meaning | Typical value |
|---|---|---|
| Failure threshold | failures in a row, or the failure percentage in a window | 5 in a row or 50% |
| Minimum number of calls | below it the percentage is not evaluated | 10–20 |
| Measurement window | the number of calls or the time span used for statistics | 20 calls or 30 s |
| Open duration | how long the circuit rejects calls | 15–60 s |
| Trial calls | how many calls the half-open state lets through | 1–5 |
| Error filter | which errors count (outages, not business errors) | 5xx, timeouts, network errors |
Implementation in five languages
Breakers are rarely written from scratch – every ecosystem has a mature library. Below is the same policy for the payment gateway: a 3 s timeout, opening at 50% failures (or a run of failures), a 30 s break, a declined card does not count as an outage, and while open the order goes to a payment queue.
Circuit breaker in front of a payment gateway
// Polly v8 + Microsoft.Extensions.Http.Resilience: a typed HttpClient guarded by a circuit breaker.
builder.Services.AddHttpClient<PaymentGatewayClient>(c => c.BaseAddress = new Uri("https://gateway.example"))
.AddResilienceHandler("payments", pipeline =>
{
// Strategies added first wrap the later ones: the breaker sees the timeouts of single attempts.
pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.5, // open at 50% failures...
MinimumThroughput = 20, // ...out of at least 20 calls...
SamplingDuration = TimeSpan.FromSeconds(30), // ...within a 30 s window
BreakDuration = TimeSpan.FromSeconds(30), // then stay open for 30 s
// The default ShouldHandle counts 5xx, 408, 429 and exceptions – a 402 "card declined" does not trip it.
});
pipeline.AddTimeout(TimeSpan.FromSeconds(3)); // a slow call becomes a failure
});
public sealed class CheckoutService(PaymentGatewayClient gateway, IPaymentQueue queue, ILogger<CheckoutService> log)
{
public async Task<CheckoutResult> PayAsync(Order order, CancellationToken ct)
{
try
{
return CheckoutResult.Paid(await gateway.ChargeAsync(order, ct));
}
catch (BrokenCircuitException) // the circuit is open – no call was made
{
log.LogWarning("Payment gateway circuit open, queueing order {OrderId}", order.Id);
await queue.EnqueueAsync(order, ct); // fallback: take the order, charge later
return CheckoutResult.PendingPayment(order.Id);
}
}
}import CircuitBreaker from "opossum";
// opossum wraps any function returning a Promise.
const charge = (order: Order): Promise<Receipt> => gateway.charge(order);
const breaker = new CircuitBreaker(charge, {
timeout: 3000, // slower than 3 s = failure
errorThresholdPercentage: 50, // open at 50% failures...
volumeThreshold: 20, // ...once at least 20 calls were made
rollingCountTimeout: 30000, // statistics window
resetTimeout: 30000, // after 30 s let a trial call through (half-open)
errorFilter: (err: unknown) => err instanceof CardDeclinedError, // true = do not count this error
});
breaker.fallback(async (order: Order) => {
await paymentQueue.enqueue(order); // take the order, charge later
return { orderId: order.id, status: "pending" } satisfies Receipt;
});
breaker.on("open", () => logger.warn("payments circuit OPEN"));
breaker.on("halfOpen", () => logger.info("payments circuit HALF-OPEN – trial call"));
breaker.on("close", () => logger.info("payments circuit CLOSED"));
export const pay = (order: Order): Promise<Receipt> => breaker.fire(order);// Resilience4j: a sliding window, slow calls counted as failures, business exceptions ignored.
@Service
class PaymentService {
private static final Logger log = LoggerFactory.getLogger(PaymentService.class);
private final PaymentGateway gateway;
private final PaymentQueue queue;
private final CircuitBreaker breaker;
PaymentService(PaymentGateway gateway, PaymentQueue queue) {
this.gateway = gateway;
this.queue = queue;
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
.slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
.slidingWindowSize(20)
.minimumNumberOfCalls(20)
.failureRateThreshold(50) // open at 50% failures in the window
.slowCallDurationThreshold(Duration.ofSeconds(3)) // a call slower than 3 s...
.slowCallRateThreshold(50) // ...counts towards opening as well
.waitDurationInOpenState(Duration.ofSeconds(30))
.permittedNumberOfCallsInHalfOpenState(3)
.ignoreExceptions(CardDeclinedException.class) // business errors do not trip the breaker
.build();
this.breaker = CircuitBreakerRegistry.of(config).circuitBreaker("payments");
breaker.getEventPublisher().onStateTransition(e -> log.warn("payments: {}", e.getStateTransition()));
}
Receipt pay(Order order) {
Supplier<Receipt> guarded = CircuitBreaker.decorateSupplier(breaker, () -> gateway.charge(order));
try {
return guarded.get();
} catch (CallNotPermittedException open) { // the circuit is open – no call was made
queue.enqueue(order);
return Receipt.pending(order.id());
}
}
// Spring Boot alternative: @CircuitBreaker(name = "payments", fallbackMethod = "queuePayment") + YAML config.
}package payments
import (
"context"
"errors"
"log"
"time"
"github.com/sony/gobreaker/v2"
)
var ErrCardDeclined = errors.New("card declined")
var breaker = gobreaker.NewCircuitBreaker[*Receipt](gobreaker.Settings{
Name: "payments",
MaxRequests: 3, // trial calls allowed in half-open
Interval: 30 * time.Second, // while closed, reset the counts every 30 s
Timeout: 30 * time.Second, // open → half-open after 30 s
ReadyToTrip: func(c gobreaker.Counts) bool {
return c.Requests >= 20 && float64(c.TotalFailures)/float64(c.Requests) >= 0.5
},
// Business errors are "successful" from the breaker's point of view.
IsSuccessful: func(err error) bool { return err == nil || errors.Is(err, ErrCardDeclined) },
OnStateChange: func(name string, from, to gobreaker.State) {
log.Printf("%s: %s -> %s", name, from, to)
},
})
func Pay(ctx context.Context, order Order) (*Receipt, error) {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second) // a slow call becomes a failure
defer cancel()
receipt, err := breaker.Execute(func() (*Receipt, error) { return gateway.Charge(ctx, order) })
if errors.Is(err, gobreaker.ErrOpenState) || errors.Is(err, gobreaker.ErrTooManyRequests) {
if qerr := queue.Enqueue(ctx, order); qerr != nil {
return nil, qerr
}
return &Receipt{OrderID: order.ID, Status: "pending"}, nil // fallback: charge later
}
return receipt, err
}import logging
import pybreaker
import requests
log = logging.getLogger(__name__)
class CardDeclined(Exception):
pass
class LogStateChanges(pybreaker.CircuitBreakerListener):
def state_change(self, cb, old_state, new_state):
log.warning("payments circuit: %s -> %s", old_state.name, new_state.name)
payments_breaker = pybreaker.CircuitBreaker(
fail_max=5, # 5 failures in a row open the circuit
reset_timeout=30, # seconds until a trial call (half-open)
exclude=[CardDeclined], # business errors do not count
listeners=[LogStateChanges()],
)
@payments_breaker
def charge(order: "Order") -> "Receipt":
response = requests.post(GATEWAY_URL, json=order.to_json(), timeout=(3.05, 5)) # connect, read
if response.status_code == 402:
raise CardDeclined(order.id)
response.raise_for_status()
return Receipt.from_json(response.json())
def pay(order: "Order") -> "Receipt":
try:
return charge(order)
except pybreaker.CircuitBreakerError: # the circuit is open – fail fast
payment_queue.enqueue(order) # take the order, charge later
return Receipt.pending(order.id)The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- The breaker in the family of resilience patterns
- When to use it and when not
- History
- Related topics
- In practice
- Check yourself
- Practice challenge