Logos DX
    Preparing search index...

    Function circuitBreaker

    • Async 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 async 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 for async environments

      Type Parameters

      Parameters

      • fn: T

        Async function to protect with circuit breaker

      • opts: CircuitBreakerOptions<T> = {}

        Configuration options for the circuit breaker

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

      Protected async function that implements circuit breaker logic

      const unstableApiCall = async (url: string) => {
      const response = await fetch(url);
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return response.json();
      };

      const protectedApiCall = circuitBreaker(unstableApiCall, {
      maxFailures: 5,
      resetAfter: 10000,
      shouldTripOnError: (error) => {
      // Only trip on server errors, not client errors
      return error.message.includes('HTTP 5') || error.name === 'NetworkError';
      },
      onTripped: (error, store) => {
      console.log(`Circuit breaker tripped after ${store.failures} failures`);
      },
      onHalfOpen: () => console.log('Testing service recovery...'),
      onReset: () => console.log('Service recovered - circuit breaker reset')
      });

      // Usage
      try {
      const data = await protectedApiCall('/api/users');
      console.log('API response:', data);
      } catch (error) {
      if (error instanceof CircuitBreakerError) {
      console.log('API temporarily unavailable - circuit breaker is open');
      // Implement fallback logic here
      } else {
      console.log('API error:', error.message);
      }
      }