💻 Dev

🛠️ 처음부터 만드는 Circuit Breaker — 외부 API 장애 전파 차단기

외부 API가 죽었을 때 우리 서버까지 같이 죽는 거, 막아본 적 있나요?
Circuit Breaker는 3가지 상태를 순환합니다:
  • CLOSED → 정상. 요청 통과

  • OPEN → 장애 감지. 요청 즉시 차단

  • HALF_OPEN → 테스트 요청 1개만 통과시켜 복구 확인

  • ```typescript
    class CircuitBreaker {
    private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED';
    private failCount = 0;
    private lastFailTime = 0;
    constructor(
    private threshold = 5,
    private timeout = 30_000
    ) {}
    async execute(fn: () => Promise): Promise {
    if (this.state === 'OPEN') {
    if (Date.now() - this.lastFailTime > this.timeout) {
    this.state = 'HALF_OPEN';
    } else {
    throw new Error('Circuit OPEN — blocked');
    }
    }
    try {
    const result = await fn();
    this.failCount = 0;
    this.state = 'CLOSED';
    return result;
    } catch (err) {
    this.failCount++;
    this.lastFailTime = Date.now();
    if (this.failCount >= this.threshold)
    this.state = 'OPEN';
    throw err;
    }
    }
    }
    ```
    사용법 — fetch를 감싸면 끝:
    ```typescript
    const breaker = new CircuitBreaker(3, 10_000);
    const data = await breaker.execute(() =>
    fetch('https://api.payment.com/charge')
    .then(r => { if (!r.ok) throw new Error(`${r.status}`); return r.json(); })
    );
    ```
    실패 3회 → 회로 차단 → 10초 후 재시도 → 성공하면 자동 복구.
    Netflix가 Hystrix로 유명하게 만든 패턴이고, 지금은 cockatiel(TS), resilience4j(Java)가 프로덕션 구현체입니다. 핵심 원리는 이 40줄이 전부 🔌
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!