Skip to the solution
HardLow-Level Design7 min read

Implement a Circuit Breaker for Flaky API Calls

61 views

The problem

Problem, as an interviewer would state it: "Implement a circuit breaker wrapping a flaky async function — after enough real failures, STOP calling the real function entirely for a cooldown period, then cautiously try again."

Examples:

Code
const breaker = createCircuitBreaker(flakyApi, { failureThreshold: 3 });
// after 3 real failures, breaker.call() rejects IMMEDIATELY, without even invoking flakyApi

Clarifying questions expected:

  • What are the real, standard circuit-breaker states, and what triggers each transition between them?
  • After the cooldown period, does the breaker immediately go back to normal, or cautiously test ONE real call first?
  • Should a successful call during the cautious "testing" phase fully reset the breaker back to normal?

Code / implementation expected: Yes — real, direct proof of a FULL real state cycle: real failures tripping it open, an immediately-rejected call while open (with a real call counter confirming the function was genuinely never invoked), and real recovery after the cooldown.

  • resilience
  • async
  • system-design

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a full circuit-breaker cycle against a genuinely flaky function — tripping OPEN, rejecting without invoking the function, and recovering

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 154 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

End of the topic

That was the last JavaScript coding question.

Pick another topic