Circuit breaker
The circuit breaker is a design pattern that detects failures and keeps them from repeating nonstop while a service is under maintenance or down. The call to a service is wrapped in an object that counts failures. When they pass a threshold, for example 5 in a row, the circuit trips and every following call returns an error without calling the service. It's like your home's circuit breaker: if there's a short circuit, it cuts the power before a wire burns.
The circuit breaker has 3 states. Closed: all normal, requests pass. If failures go over the threshold, it moves to open: it returns an error instantly without calling the service. After a while, for example 30 seconds, it moves to half-open: it lets a few test requests through. If they succeed, it goes back to closed; if they fail, back to open. It's like a drawbridge: down, everything passes; up, nobody passes; and sometimes it's lowered a bit to test.
In the open state, the circuit breaker returns an error instantly, without even calling the service. That gives the service time to recover, without getting more load, and frees the caller, who doesn't stay waiting. After a wait period, usually set by a monitoring system, it moves to half-open. It's like putting up a «closed for renovation» sign: people don't line up at the door and the shop gets fixed in peace.
In the half-open state, the circuit breaker lets a limited number of requests through, for example 3, to test whether the service recovered. If they succeed, it goes back to closed and everything continues normally. If they keep failing, it goes back to open and waits again. It's like testing the water with your foot before jumping into the pool: if it's fine, you go in; if it's freezing, you wait.
A circuit breaker is tuned with 2 numbers: the failure threshold to open (for example, 5 failures in a row or 50% errors in 10 seconds) and the wait time before moving to half-open (for example, 30 seconds). A very low threshold trips on any stray error; a very high one is slow to protect. It's like a car alarm's sensitivity: if the wind sets it off, it's annoying; if a theft doesn't, it's useless.
