Logos DX
    Preparing search index...

    Function circuitBreakerSync

    • Circuit breaker that protects a function from failing too many times.

      Implements the Circuit Breaker design pattern to improve system resilience and fault tolerance by preventing cascading failures in distributed systems. The circuit breaker monitors function calls and automatically "trips" (opens) when failures exceed a threshold, preventing further calls to the failing function until it has time to recover.

      The circuit breaker operates in three states:

      • Closed: Normal operation, all calls pass through. Failures are counted.
      • Open: Circuit is tripped, all calls fail immediately without invoking the function.
      • Half-Open: After a timeout, allows limited test calls to check if the service has recovered.

      Key features:

      • Configurable failure thresholds and recovery timeouts
      • Concurrency control during half-open testing
      • Selective error handling via shouldTripOnError predicate
      • Comprehensive callback system for monitoring and alerting
      • Thread-safe operation

      Type Parameters

      Parameters

      • fn: T

        Function to protect with circuit breaker

      • opts: CircuitBreakerOptions<T> = {}

        Configuration options for the circuit breaker

      Returns (...args: Parameters<T>) => ReturnType<T> | null | undefined

      Protected function that implements circuit breaker logic

      const unstableService = () => {
      if (Math.random() > 0.7) throw new Error('Service failed');
      return 'Success';
      };

      const protectedService = circuitBreakerSync(unstableService, {
      maxFailures: 3, // Trip after 3 consecutive failures
      resetAfter: 5000, // Test recovery after 5 seconds
      onTripped: (error) => console.log('Circuit breaker tripped:', error.message),
      onReset: () => console.log('Circuit breaker reset - service recovered')
      });

      // Usage
      try {
      const result = protectedService(); // May throw CircuitBreakerError if open
      console.log(result);
      } catch (error) {
      if (error instanceof CircuitBreakerError) {
      console.log('Circuit breaker is open - service unavailable');
      } else {
      console.log('Service error:', error.message);
      }
      }