AniUI Academy
hard+350 XPPractice

Build a circuit breaker

Hammering a service that is already failing makes the outage worse and makes your UI slow, since every call waits for a timeout. A circuit breaker trips after a run of failures and fails fast instead, then lets a single trial call through later to see if the service is back.

Implement createBreaker(task, options) where options may contain failureThreshold (default 3) and resetTimeout (default 1000). It returns a function call(...args) that forwards its arguments to task, plus a call.state() method returning "closed", "open" or "half-open". It starts closed. A fulfilment resets the consecutive-failure count to zero. Once failureThreshold consecutive failures happen, the breaker opens and records the time: while open, call rejects with new Error("Circuit is open") without invoking task. Once resetTimeout milliseconds have passed since it opened, state() reports "half-open" and the next call does invoke task: if it fulfils the breaker closes and the count resets, and if it rejects the breaker opens again with a fresh timestamp.

What it has to do

  • Forward arguments to task and resolve with its value while closed.
  • Open after failureThreshold consecutive failures.
  • Reject with an Error reading Circuit is open without calling task while open.
  • Reset the failure count on any success.
  • Report half-open after resetTimeout, and close again on a successful trial call.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.