💻 Dev

🛠️ 처음부터 만드는 Circuit Breaker — 장애 전파 차단기 25줄 구현

외부 API가 죽었는데 계속 요청 보내본 적 있나요?
Circuit Breaker는 연속 실패를 감지하면 요청 자체를 차단하는 패턴입니다.
마이크로서비스 필수 패턴, 25줄로 핵심을 구현합니다.

3가지 상태


```
CLOSED → 정상. 요청 통과
OPEN → 차단. 즉시 에러 반환
HALF_OPEN → 시험. 1회 통과시켜 복구 확인
```

구현


```typescript
type State = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
function circuitBreaker(
fn: () => Promise,
{ threshold = 3, timeout = 5000 } = {}
) {
let state: State = 'CLOSED';
let failures = 0;
let openedAt = 0;
return async (): Promise => {
if (state === 'OPEN') {
if (Date.now() - openedAt > timeout)
state = 'HALF_OPEN';
else
throw new Error('Circuit OPEN — fail fast');
}
try {
const result = await fn();
state = 'CLOSED';
failures = 0;
return result;
} catch (err) {
failures++;
openedAt = Date.now();
if (failures >= threshold) state = 'OPEN';
throw err;
}
};
}
```

사용


```typescript
const safeFetch = circuitBreaker(
() => fetch('https://api.example.com').then(r => r.json()),
{ threshold: 3, timeout: 10000 }
);
// 3번 연속 실패 → OPEN → 10초간 즉시 에러
// 10초 후 → HALF_OPEN → 1회 시도
// 성공 → CLOSED / 실패 → 다시 OPEN
```

핵심 포인트


  • threshold: 몇 번 실패하면 차단할지

  • timeout: 차단 후 몇 ms 뒤에 재시도할지

  • HALF_OPEN에서 성공하면 CLOSED, 실패하면 다시 OPEN

  • Netflix Hystrix, resilience4j가 이 패턴입니다.
    장애가 전파되기 전에 빠르게 실패(fail fast)하는 게 핵심.
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!