Saltar al contenido
Skillpedia
Sitios e interfaces (frontend)7,8 mil · #13047

data-service-circuit-breaker-aware

Qué hace

Esta skill guía al agente de IA para escribir servicios de datos que obtienen, guardan en caché y reintentan llamadas a una API para los paneles de control. Es para desarrolladores que quieren un manejo de datos resistente con reglas claras sobre cuándo usar el circuit breaker.

Cuándo usarla

  • ✓Cuando un panel de control obtiene sus datos de una API externa que puede caerse.
  • ✓Cuando algunas llamadas son acciones puntuales del usuario y otras son sondeos en segundo plano.
  • ✓Cuando quieres que se muestren datos antiguos durante una caída en lugar de errores.

Link de la skill

https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/data-service-circuit-breaker-aware/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/data-service-circuit-breaker-aware/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“Escribe el servicio de datos de mi panel del tiempo con un circuit breaker, y dime cuándo no debería aplicarse.”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

El agente crea una utilidad de circuit breaker que cuenta los fallos y entra en un período de espera cuando son demasiados. El servicio de cada panel llama a la API a través del circuit breaker, sirve datos en caché durante la espera y omite el circuit breaker en las llamadas directas que lanza el usuario.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

Data Service Pattern

Each panel's data comes from a dedicated service module in src/services/. Services handle API calls, caching, error handling with circuit breaker pattern.

Circuit Breaker

The circuit breaker prevents cascading failures when an API is down. After N consecutive failures, it enters "cooldown" mode and serves cached data instead of hitting the API.

Create src/utils/circuit-breaker.ts:

interface CircuitState {
  failures: number;
  cooldownUntil: number;
}

interface CacheEntry<T> {
  data: T;
  timestamp: number;
}

export interface CircuitBreakerOptions {
  name: string;
  maxFailures?: number;
  cooldownMs?: number;
  cacheTtlMs?: number;
}

export class CircuitBreaker<T> {
  private state: CircuitState = { failures: 0, cooldownUntil: 0 };
  private cache: CacheEntry<T> | null = null;
  private name: string;
  private maxFailures: number;
  private cooldownMs: number;
  private cacheTtlMs: number;

  constructor(options: CircuitBreakerOptions) {
    this.name = options.name;
    this.maxFailures = options.maxFailures ?? 2;
    this.cooldownMs = options.cooldownMs ?? 5 * 60 * 1000;  // 5 minutes
    this.cacheTtlMs = options.cacheTtlMs ?? 10 * 60 * 1000; // 10 minutes
  }

  isOnCooldown(): boolean {
    if (Date.now() < this.state.cooldownUntil) return true;
    if (this.state.cooldownUntil > 0) {
      this.state = { failures: 0, cooldownUntil: 0 };
    }
    return false;
  }

  getCached(): T | null {
    if (this.cache && Date.now() - this.cache.timestamp < this.cacheTtlMs) {
      return this.cache.data;
    }
    return null;
  }

  recordSuccess(data: T): void {
    this.state = { failures: 0, cooldownUntil: 0 };
    this.cache = { data, timestamp: Date.now() };
  }

  recordFailure(error?: string): void {
    this.state.failures++;
    if (this.state.failures >= this.maxFailures) {
      this.state.cooldownUntil = Date.now() + this.cooldownMs;
      console.warn(`[${this.name}] Cooldown for ${this.cooldownMs / 1000}s`);
    }
  }

  async execute<R extends T>(fn: () => Promise<R>, defaultValue: R): Promise<R> {
    if (this.isOnCooldown()) {
      const cached = this.getCached();
      return (cached as R) ?? defaultValue;
    }
    const cached = this.getCached();
    if (cached !== null) return cached as R;
    try {
      const result = await fn();
      this.recordSuccess(result);
      return result;
    } catch (e) {
      console.error(`[${this.name}] Failed:`, e);
      this.recordFailure(String(e));
      return defaultValue;
    }
  }
}

export function createCircuitBreaker<T>(options: CircuitBreakerOptions): CircuitBreaker<T> {
  return new CircuitBreaker<T>(options);
}

Service Module Pattern

Each service is a TypeScript module that exports async data-fetching functions:

// src/services/stock-market.ts
import { createCircuitBreaker } from '../utils/circuit-breaker';

export interface StockQuote {
  symbol: string;
  name: string;
  price: number | null;
  change: number | null;
  sparkline?: number[];
}

const breaker = createCircuitBreaker<StockQuote[]>({
  name: 'StockMarket',
  cacheTtlMs: 60_000, // 1 minute cache
});

export async function fetchStockQuotes(symbols: string[]): Promise<StockQuote[]> {
  return breaker.execute(async () => {
    const params = new URLSearchParams({ symbols: symbols.join(',') });
    const resp = await fetch(`/api/stocks?${params}`);
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
    return resp.json();
  }, []);
}

Key Patterns

  1. One circuit breaker per API endpoint — create at module level
  2. Export typed interfaces for data shapes
  3. Wrap fetch calls in breaker.execute(fn, defaultValue)
  4. Default values are empty arrays [] or empty objects {}
  5. Services are stateless modules — no class instances, just exported functions
  6. API proxy: Frontend calls /api/... which proxies to external APIs (hides API keys)

When to Skip the Circuit Breaker

The circuit breaker is designed to protect background auto-polling services from cascading failures. It is not always appropriate — applying it blindly adds unnecessary complexity and can actively cause problems for user-driven flows.

Use the circuit breaker when:

  • The service is polled automatically on an interval (e.g., every 30 seconds, every minute)
  • Repeated failures would hammer a degraded API endpoint
  • Serving stale cached data is an acceptable fallback (the user won't no
Preguntas frecuentes

¿Cuándo se debe omitir el circuit breaker?

La skill indica que las llamadas puntuales lanzadas por el usuario pueden omitirlo, mientras que el sondeo en segundo plano debe usarlo.

¿Qué pasa durante el período de espera?

El servicio sirve datos en caché en lugar de volver a llamar a la API hasta que termine la espera.

¿Dónde está el código del circuit breaker?

La skill lo coloca en un archivo de utilidades, como src/utils/circuit-breaker.ts.

Detalles

Descripción original del autor

Create data fetching services with circuit breaker pattern for API resilience. Services handle fetch, cache, retry, and expose typed data to panel components. Includes clear guidance on when to skip the circuit breaker for user-triggered one-shot calls versus background auto-polling services.

repo: HKUDS/AgentPilot

Popularidad

Estrellas en GitHub
7,8 mil
Posición en el ranking
#13047
Licencia
MIT
Actualizada
1/11/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas