Circuit breaker

From InugamiDev/ultrathink-oss · View interactive version

Circuit breaker is an AI agent skill from the GitHub repository InugamiDev/ultrathink-oss. Circuit breaker for fault tolerance — closed/open/half-open states, fallback, resilience libs

How to use this skill

Skill file

Circuit Breaker

Overview

The circuit breaker pattern prevents cascading failures in distributed systems by wrapping calls to external services in a state machine. When failures exceed a threshold, the circuit "opens" and short-circuits requests, returning a fallback response instead of overwhelming a degraded service.

When to Use

Key Patterns

Three States

| State | Behavior |

|-------|----------|

| Closed | Requests pass through normally; failures are counted |

| Open | Requests are immediately rejected; fallback is returned |

| Half-Open | A limited number of probe requests are allowed to test recovery |

Basic Implementation

type CircuitState = 'closed' | 'open' | 'half-open';

interface CircuitBreakerOptions {
  failureThreshold: number;   // failures before opening
  resetTimeoutMs: number;     // time before half-open probe
  halfOpenMax: number;        // probe requests in half-open
}

class CircuitBreaker {
  private state: CircuitState = 'closed';
  private failureCount = 0;
  private lastFailureTime = 0;
  private halfOpenAttempts = 0;

  constructor(private opts: CircuitBreakerOptions) {}

  async call<T>(fn: () => Promise<T>, fallback: () => T): Promise<T> {
    if (this.state === 'open') {
      if (Date.now() - this.lastFailureTime > this.opts.resetTimeoutMs) {
        this.state = 'half-open';
        this.halfOpenAttempts = 0;
      } else {
        return fallback();
      }
    }

    if (this.state === 'half-open' && this.halfOpenAttempts >= this.opts.halfOpenMax) {
      return fallback();
    }

    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (err) {
      this.onFailure();
      return fallback();
    }
  }

  private onSuccess() {
    this.failureCount = 0;
    this.state = 'closed';
  }

  private onFailure() {
    this.failureCount++;
    this.lastFailureTime = Date.now();
    if (this.state === 'half-open' || this.failureCount >= this.opts.failureThreshold) {
      this.state = 'open';
    }
  }
}

Usage with a Resilience Library (opossum)

import CircuitBreaker from 'opossum';

const breaker = new CircuitBreaker(fetchUserProfile, {
  timeout: 3000,
  errorThresholdPercentage: 50,
  resetTimeout: 10000,
});

breaker.fallback(() => ({ name: 'Guest', cached: true }));
breaker.on('open', () => metrics.increment('circuit.open'));
breaker.on('halfOpen', () => metrics.increment('circuit.halfOpen'));

const profile = await breaker.fire(userId);

Per-Service Breakers in an API Gateway

const breakers = new Map<string, CircuitBreaker>();

function getBreaker(service: string) {
  if (!breakers.has(service)) {
    breakers.set(service, new CircuitBreaker({
      failureThreshold: 5,
      resetTimeoutMs: 30_000,
      halfOpenMax: 2,
    }));
  }
  return breakers.get(service)!;
}

Pitfalls

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.