💻 Dev

🛠️ 처음부터 만드는 Circuit Breaker — opossum-style 장애 차단기 22줄 구현

무엇인가?


Circuit Breaker는 장애가 연쇄되는 것을 방지하는 패턴입니다. 불이 나면 브레이커를 내려서 흐름을 끊죠.
```javascript
class CircuitBreaker {
constructor(fn, { threshold = 5, timeout = 60000 } = {}) {
this.fn = fn;
this.threshold = threshold;
this.timeout = timeout;
this.failures = 0;
this.lastError = null;
this.state = 'CLOSED'; // CLOSED → OPEN → HALF_OPEN → CLOSED
this.openedAt = null;
}
async call(...args) {
if (this.state === 'OPEN') {
if (Date.now() - this.openedAt > this.timeout) {
this.state = 'HALF_OPEN';
} else {
throw new Error(`Circuit OPEN. Last: ${this.lastError.message}`);
}
}
try {
const result = await this.fn(...args);
this.onSuccess();
return result;
} catch (error) {
this.onFailure(error);
throw error;
}
}
onSuccess() {
this.failures = 0;
this.state = 'CLOSED';
}
onFailure(error) {
this.lastError = error;
this.failures++;
if (this.failures >= this.threshold) {
this.state = 'OPEN';
this.openedAt = Date.now();
}
}
}
```

사용


```javascript
const breaker = new CircuitBreaker(
async () => fetch('https://flaky-api.com'),
{ threshold: 3, timeout: 5000 }
);
try {
await breaker.call();
} catch (e) {
console.log('Circuit open, backing off...');
}
```

세 가지 상태


  • CLOSED: 정상 작동 ✅

  • OPEN: 장애 연쇄 중단 🚫

  • HALF_OPEN: 복구 시도 🔄

  • 실전에서는 [opossum](https://github.com/nodeunify/opossum)이나 [cockatiel](https://github.com/connor4312/cockatiel) 같은 라이브러리로 더 강력한 기능(fallback, stats, events)을 얻을 수 있습니다.
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!