DEV Community

Mohit Verma
Mohit Verma

Posted on • Edited on

Implement circuit breaker in Javascript

In software development, a circuit breaker is a design pattern used to prevent a service from becoming overwhelmed or failing in the event of an error or too much traffic. It acts as a safety valve that stops the flow of traffic to a service when it detects an error or a high number of requests.

In JavaScript, a circuit breaker can be implemented by creating a wrapper function around the code that is prone to failure or high traffic. The wrapper function monitors the number of errors or requests and determines whether to allow traffic to pass through to the original function.

Image description



function circuitBreaker(originalFunction, 
failureThreshold, recoveryTime) {
  let failureCount = 0;
  let lastFailureTime = null;
  let isOpen = false;

  return function(...args) {
    if (isOpen) {
      const timeSinceFailure = new Date() - lastFailureTime;
      if (timeSinceFailure > recoveryTime) {
        isOpen = false;
      } else {
        throw new Error('Service is unavailable');
      }
    }

    try {
      const result = originalFunction(...args);
      failureCount = 0;
      return result;
    } catch (error) {
      failureCount++;
      lastFailureTime = new Date();

      if (failureCount >= failureThreshold) {
        isOpen = true;
      }

      throw error;
    }
  };
}



Enter fullscreen mode Exit fullscreen mode

This function takes three parameters: the original function that we want to wrap, the failure threshold (the number of allowed failures before the circuit breaker is triggered), and the recovery time (the amount of time to wait before trying the original function again).

The circuit breaker function returns a new function that acts as a wrapper around the original function. The wrapper function checks if the circuit is open, and if it is, it either throws an error or waits for the recovery time to expire before allowing traffic through again. If the circuit is closed, the wrapper function calls the original function and catches any errors. If the number of errors exceeds the failure threshold, the circuit is opened, and traffic is stopped from passing through until the recovery time has passed.

To use this circuit breaker, we can pass our original function to the circuitBreaker function along with the desired failure threshold and recovery time:

For more frontend interview questions & preparation can use
Preparefrontend

Top comments (0)