Belajar
← All lessons

How circuit breakers work

Closed, open, half-open

Shop
Breaker
Recommendations

breaker.js

async function call(fn) {  if (state === "open") {    if (now() - openedAt < COOLDOWN) throw new OpenError(); // open: don't even try    state = "half-open"; // cooldown over: let one trial through  }  try {    const res = await withTimeout(fn(), 2000);    state = "closed"; failures = 0; // success closes it and resets the count    return res;  } catch (err) {    failures += 1;    if (state === "half-open" || failures >= THRESHOLD) {      state = "open"; openedAt = now(); // too many failures in a row: open    }    throw err;  }}

product-page.js

const recs = await call(() => fetchRecommendations(user))  .catch(() => popularItems()); // show popular items instead

Drive the breaker break the service, wait, recover

The service isHealthyDown
Trip after failures in a row3
Calls t = 0 s

    breaker.js

    async function call(fn) {  if (state === "open") {    if (now() - openedAt < COOLDOWN) throw new OpenError(); // open: don't even try    state = "half-open"; // cooldown over: let one trial through  }  try {    const res = await withTimeout(fn(), 2000);    state = "closed"; failures = 0; // success closes it and resets the count    return res;  } catch (err) {    failures += 1;    if (state === "half-open" || failures >= THRESHOLD) {      state = "open"; openedAt = now(); // too many failures in a row: open    }    throw err;  }}

    Why fail fast a slow service eats your workers

    Requests per second that need it
    Timeout1 s2 s5 s10 sCircuit breakerOffOn
    Shop workers stuck waiting on it

    The shop has 64 workers. Every page needs one, even pages that never call this service

    product-page.js

    // no breaker: every page waits out the timeoutconst recs = await withTimeout(fetchRecs(user), TIMEOUT)  .catch(() => popularItems()); // breaker: once open, it answers at onceconst recs = await breaker.call(() => fetchRecs(user))  .catch(() => popularItems());

    Topics

    Next: How public-key cryptography works

    Open lesson