본문으로 건너뛰기
Skillpedia
웹사이트 및 UI (프런트엔드)7.8k · #13047

data-service-circuit-breaker-aware

하는 일

이 스킬은 대시보드 패널의 API 호출을 가져오고 캐시하고 재시도하는 데이터 서비스를 AI 에이전트가 작성하도록 안내합니다. 안정적인 데이터 처리를 원하고, 브레이커를 언제 쓸지 명확한 규칙이 필요한 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓대시보드 패널이 외부 API에서 데이터를 받고 그 API가 내려갈 수 있을 때.
  • ✓일회성 사용자 작업과 백그라운드 폴링이 섞여 있을 때.
  • ✓장애 중에는 오류 대신 오래된 데이터를 보여 주고 싶을 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/data-service-circuit-breaker-aware/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“날씨 패널의 데이터 서비스를 서킷 브레이커와 함께 작성해 주세요. 브레이커를 적용하지 말아야 할 경우도 알려 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 실패를 세고 너무 많으면 쿨다운에 들어가는 서킷 브레이커 유틸리티를 만듭니다. 각 패널의 서비스는 브레이커를 거쳐 API를 호출하고, 쿨다운 중에는 캐시된 데이터를 제공하며, 사용자가 직접 요청한 호출에는 브레이커를 건너뜁니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 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
자주 묻는 질문

브레이커는 언제 건너뛰나요?

사용자가 한 번만 요청하는 호출은 브레이커를 건너뛸 수 있고, 백그라운드 폴링은 써야 한다고 스킬은 설명합니다.

쿨다운 중에는 무엇이 일어나나요?

쿨다운이 끝날 때까지 서비스는 API를 다시 호출하지 않고 캐시된 데이터를 제공합니다.

브레이커 코드는 어디에 있나요?

스킬은 src/utils/circuit-breaker.ts 같은 유틸리티 파일에 두라고 안내합니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
7.8k
순위
#13047
라이선스
MIT
업데이트
2026. 11. 1.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬