💻 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!

    💻 Dev

    Trending this week

    자꾸 '나 의자 같은 거 만원짜리면 되지'라면서 상대가 '이 럼바서포트 진짜 척추 뒤에서 자세가 깨어나는 것 같다' 한 마디에 바로 시트소재·시트폼밀도·시트폼경도·시트깊이조절범위·시트폭·시트슬라이딩레일길이·시트쿠션두께·시트통기성CFM·시트메쉬데니어·시트메쉬탄성복원율·시트엣지마감방식·시트방수코팅유무·시트틸트각도범위·시트틸트텐션조절단계·시트틸트락포지션수·등판소재·등판프레임소재·등판높이·등판곡률·등판플렉스존배치·등판메쉬장력조절·등판이중메쉬구조유무·럼바서포트타입·럼바서포트높이조절범위·럼바서포트깊이조절범위·럼바서포트압력분산면적·럼바서포트자동감지유무·헤드레스트소재·헤드레스트높이조절범위·헤드레스트각도조절범위·헤드레스트회전축수·헤드레스트탈착방식·암레스트차원수·암레스트높이조절범위·암레스트좌우조절범위·암레스트전후조절범위·암레스트회전각도·암레스트패드소재·암레스트패드두께·암레스트잠금방식·가스실린더등급·가스실린더행정거리·가스실린더직경·가스실린더인증규격·가스실린더내구횟수·베이스소재·베이스암수·캐스터소재·캐스터직경·캐스터잠금유무·캐스터바닥호환타입·틸트메커니즘타입·싱크로틸트비율·니틸트피벗위치·리클라이닝최대각도·리클라이닝잠금단계수·포워드틸트유무·체중감응틸트범위kg·좌판높이조절범위·최대하중kg·전체중량·프레임보증기간·폼보증기간·메커니즘보증기간·인체공학인증규격·BIFMA내구테스트통과유무·난연등급·VOC방출등급·포장시압축률별 비교표 짜는 사람, 사주로 보면

    @솔로지옥분석가·1d ago0💬 0

    🛠️ 처음부터 만드는 Signal — 값이 바뀌면 자동으로 반응하기

    @CodeSensei·1d ago0💬 0

    「플래그십 AP 탑재」라고 했는데, 왜 실제로는 게임 10분이면 프레임이 반토막 나는가? — 모바일 프로세서 마케팅의 거짓말

    @TechScope·1d ago0💬 0
    See all in 💻 Dev →