LLD Guide · Module 2: Problem prep · Lesson 02.07

Prep: Circuit Breaker

Three states, a clock, consecutive failures, and a limited number of test calls, shared across instances in Redis.

By Cruscible Engineering · Published

A circuit breaker is a state machine with a clock attached. Most bugs come from the clock: when OPEN quietly became HALF_OPEN, and who noticed first.

This lesson prepares you for Build a Circuit Breaker. It doesn't solve it.

1. What the circuit breaker contract asks for

A breaker per service id, with its state in Redis so several app instances agree. While CLOSED, calls go through and consecutive failures are counted. At failureThreshold the breaker opens: calls fail at once without running the action. After recoveryTimeoutMs it's HALF_OPEN: up to halfOpenMaxAttempts test calls may run. One success closes it; one failure opens it again.

MethodReturns / does
configure(failureThreshold, recoveryTimeoutMs, halfOpenMaxAttempts)sets the parameters, before any execute
execute(serviceId, action)true if the action ran and succeeded; false if it failed or was rejected
getState(serviceId)CLOSED, OPEN or HALF_OPEN, as of now
getFailureCount(serviceId)the current consecutive failure count; 0 if none
getLastFailureTimestamp(serviceId)epoch ms of the last failure, or 0
reset(serviceId)back to CLOSED: count, timestamp and half-open tracking cleared

Figure: Three failures trip the breaker; after the cool-down one test call decides

2. Lessons to read before the circuit breaker

3. Circuit breaker design decisions to make first

  1. What counts as a failure? The contract names two outcomes of the action. And what does a success in CLOSED do to the consecutive count?
  2. Who notices that the cool-down ended? No background thread: getState and execute must both see HALF_OPEN once recoveryTimeoutMs has passed since the breaker opened. Which timestamp do you keep for that?
  3. How do you limit test calls? With halfOpenMaxAttempts = 1 and two threads arriving together in HALF_OPEN, exactly one may run the action. What do you count, and when: when a call is let through, or when it finishes?
  4. Which fields change together? List what a trip, a recovery and a re-open each update, and make each update one atomic step.
  5. How are services kept apart? Name the keys so one service tripping never affects another.

4. Circuit breaker pitfalls

⚠️ Trap: an action that returns false is a failure, the same as one that throws.

⚠️ Trap: when the breaker is OPEN, the action must not be called at all, not even to check.

⚠️ Trap: counting HALF_OPEN test calls only when they finish lets a burst of concurrent callers all through. Count them when they're dispatched.

⚠️ Trap: no in-process state. A Java field holding the state breaks "shared across instances".

Before you submit

Further reading

After you've tried it

Submit first. The full walkthrough of one solution: Building a Circuit Breaker from Scratch.

Open the problem