circuit-breaker

Circuit breaker for fault tolerance — closed/open/half-open states, fallback, resilience libs

39 stars

Best use case

circuit-breaker is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Circuit breaker for fault tolerance — closed/open/half-open states, fallback, resilience libs

Teams using circuit-breaker should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/circuit-breaker/SKILL.md --create-dirs "https://raw.githubusercontent.com/InugamiDev/ultrathink-oss/main/.claude/skills/circuit-breaker/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/circuit-breaker/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How circuit-breaker Compares

Feature / Agentcircuit-breakerStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Circuit breaker for fault tolerance — closed/open/half-open states, fallback, resilience libs

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 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

- Calling external APIs or microservices that may become unavailable
- Database connections under heavy load
- Any I/O operation where repeated failures waste resources and degrade UX
- Systems where partial degradation is preferable to total failure

## 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

```typescript
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)

```typescript
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

```typescript
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

- **Threshold too low**: Normal transient errors trip the breaker unnecessarily. Use error-rate percentages rather than raw counts.
- **No fallback defined**: An open circuit with no fallback just throws a different error — always provide a degraded response.
- **Shared state in serverless**: Each Lambda/Edge Function instance has its own breaker state. Use Redis or a shared store for distributed breakers.
- **Missing observability**: Always emit metrics on state transitions — an open circuit you don't know about is a silent outage.
- **Reset timeout too short**: Half-open probes hit a still-recovering service and re-open the circuit. Start with 30s+ and tune from there.

Related Skills

ultrathink

39
from InugamiDev/ultrathink-oss

UltraThink Workflow OS — 4-layer skill mesh with persistent memory and privacy hooks for complex engineering tasks. Routes prompts through intent detection to activate the right domain skills automatically.

ultrathink_review

39
from InugamiDev/ultrathink-oss

Multi-pass code review powered by UltraThink's quality gate — checks correctness, security (OWASP), performance, readability, and project conventions in a single structured pass.

ultrathink_memory

39
from InugamiDev/ultrathink-oss

Persistent memory system for UltraThink — search, save, and recall project context, decisions, and patterns across sessions using Postgres-backed fuzzy search with synonym expansion.

ui-design

39
from InugamiDev/ultrathink-oss

Comprehensive UI design system: 230+ font pairings, 48 themes, 65 design systems, 23 design languages, 30 UX laws, 14 color systems, Swiss grid, Gestalt principles, Pencil.dev workflow. Inherits ui-ux-pro-max (99 UX rules) + impeccable-frontend-design (anti-AI-slop). Triggers on any design, UI, layout, typography, color, theme, or styling task.

Zod

39
from InugamiDev/ultrathink-oss

> TypeScript-first schema validation with static type inference.

webinar-registration-page

39
from InugamiDev/ultrathink-oss

Build a webinar or live event registration page as a self-contained HTML file with countdown timer, speaker bio, agenda, and registration form. Triggers on: "build a webinar registration page", "create a webinar sign-up page", "event registration landing page", "live training registration page", "workshop sign-up page", "create a webinar page", "build an event page", "free webinar landing page", "live demo registration page", "online event page", "create a registration page for my webinar", "build a training event page".

webhooks

39
from InugamiDev/ultrathink-oss

Webhook design patterns — delivery, retry with exponential backoff, HMAC signature verification, payload validation, idempotency keys

web-workers

39
from InugamiDev/ultrathink-oss

Offload heavy computation from the main thread using Web Workers, SharedWorkers, and Comlink — structured messaging, transferable objects, and off-main-thread architecture patterns

web-vitals

39
from InugamiDev/ultrathink-oss

Core Web Vitals monitoring (LCP, FID, CLS, INP, TTFB), measurement with web-vitals library, reporting to analytics, and optimization strategies for Next.js

web-components

39
from InugamiDev/ultrathink-oss

Native Web Components, custom elements API, Shadow DOM, HTML templates, slots, lifecycle callbacks, and framework-agnostic design patterns

wasm

39
from InugamiDev/ultrathink-oss

WebAssembly integration — Rust to WASM with wasm-pack/wasm-bindgen, WASI, browser usage, server-side WASM, and performance considerations

vue

39
from InugamiDev/ultrathink-oss

Vue 3 Composition API, Nuxt patterns, reactivity system, component architecture, and production development practices