This is another design pattern in JavaScript that is commonly used to prevent multiple consecutive failure attempts.
One common example of this pattern occurs when making API calls from the frontend. Sometimes, due to various reasons, an API call might fail. To prevent repeated failures, we can halt further API calls for a certain threshold time.
Although this pattern is more commonly used in backend architecture, it can also be implemented on the frontend to improve user experience. By doing so, we can avoid showing multiple failure messages to the user and prevent unnecessary API calls when the backend server is down.
Let’s understand how this pattern works:
If an API call fails, we track the number of consecutive failures. Once the failure count exceeds the predefined limit, we record the time of the last failure. On the next API attempt, our circuit breaker function compares the current time with the last failure time. If the threshold duration has passed, the circuit resets, allowing API calls again.
Alongside, we maintain a variable called isclosed
, which indicates whether the circuit is open or closed. Initially, it is set to false. Once the failure limit is exceeded, we set it to true. On subsequent attempts, we first check the value of isclosed
. If it is true, we then verify whether the threshold time since the last failure has elapsed before allowing another API call.
const circuitbreaker=(fn,failCountLimit,thresholdTime)=>{
let failAttempt=0;
let timeOfLastFailAttempt=0;
let isClosed=false;
return function(...args){
if(isClosed){
const diff=Date.now()-timeOfLastFailAttempt;
if(diff>thresholdTime){
isClosed=false;
}else {
console.log("Service is not available right now");
return;
}
}
try{
const result=fn(...args);
failAttempt=0;
return result;
}catch(err){
failAttempt++;
timeOfLastFailAttempt=Date.now();
if(failAttempt>=failCountLimit){
isClosed=true;
}
console.log("Failure");
}
}
}
Let’s look at an example of the circuit breaker function. We’ll create a dummy function that throws an error on the first three attempts and returns the count after that.
const fetchApi=()=>{
let count=0;
return function(){
count++;
if(count<3){
throw "Error"
}else{
return `count ${count}`
}
}
}
Usage of funciton:
const apiTest=fetchApi();
const test=circuitbreaker(apiTest,2,200);
test();
test();
test(); <- still return "failure"
setTimeout(() => test(), 100);
setTimeout(() => console.log(test()), 210); <- will return output of count
so the response of the above code is going to be:
As you can see, even the call made after two attempts returned a failure because we set the threshold time to 200 milliseconds. Therefore, any call made after 200 milliseconds will return the expected output.
Top comments (0)