API Fundamentals Course
API Fundamentals
/
Advanced

Circuit Breaker Pattern

Definition

A software design pattern used in distributed systems to prevent an application from repeatedly trying to execute an operation that is highly likely to fail, allowing the failing system time to recover.

Explain Like I'm New

If a lightbulb blows out and creates a short circuit, you don't want electricity to keep pumping in and start a fire. A physical circuit breaker 'trips' and cuts the power. In APIs, if the Database is dead, you 'trip' the circuit breaker in your code so the API instantly returns an error, rather than forcing 5,000 users to wait 30 seconds for a timeout.

Real World Example

Microservices. The 'Search' service calls the 'Recommendation' service. The Recommendation service crashes. If the Search service keeps trying to call it, the Search service will run out of memory waiting for responses and ALSO crash (Cascading Failure). A Circuit Breaker stops the calls instantly.

Common Use Cases

  • •Microservices architecture
  • •Preventing cascading failures

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What are the three states of a Circuit Breaker? (Hint: Think of electrical switches)

intermediate

  • What happens when the Circuit Breaker is in the 'Half-Open' state?

Flash Cards

Question

Three states?

Click to reveal answer
Answer

Closed (Electricity flows, everything is fine). Open (Tripped, electricity is blocked, instant errors). Half-Open (Testing to see if the system is fixed).

Question

Half-Open state?

Click to reveal answer
Answer

After being 'Open' (blocked) for a while, the breaker transitions to Half-Open. It allows a single test request to go through to the broken service. If it succeeds, the breaker Closes (fixes itself). If it fails, it violently Opens again.