Timeouts retries and circuit breakers
Prerequisite: node-error-categories-and-propagation. Objective: Model bounded retry. Local baseline: Node.js 22.16.0 on Linux, ESM. Each example is independent: save as main.mjs in a disposable directory and run node main.mjs. The author harness uses a five-second timeout. Static snippets are not ByteMind interactive execution.
How it works
Use an AbortSignal when the underlying API cooperates. A Promise.race timeout alone does not cancel its losing operation. Retry only classified transient failures for safe/idempotent operations, with a total deadline, maximum attempts and jittered backoff. A breaker typically transitions closed to open, then permits a limited half-open probe before closing or reopening. Bulkheads limit concurrent work; load shedding rejects excess work instead of accumulating an unbounded queue. These policies are not a guarantee of success.
Cancel a cooperative timer
import {setTimeout as delay} from 'node:timers/promises';import assert from 'node:assert/strict';const controller=new AbortController();const task=delay(1000,'done',{signal:controller.signal});controller.abort();await assert.rejects(task,{name:'AbortError'});console.log('cancelled');Expected output:
cancelledCancellation is observed by the timer API; it does not imply cancellation of arbitrary promises.
Model a bounded retry decision with no external calls
function attempt(outcomes,max){let used=0;for(const result of outcomes.slice(0,max)){used++;if(result==='ok'||result==='permanent')return {result,used};}return {result:'exhausted',used};}for(const values of [['transient','ok'],['permanent','ok'],['transient','transient','ok']])console.log(JSON.stringify(attempt(values,2)));Expected output:
{"result":"ok","used":2}{"result":"permanent","used":1}{"result":"exhausted","used":2}This models only attempt classification and count. A real retry implementation also needs deadlines, jitter and cancellation.
Common mistakes
Do not retry validation failures or assume an expired request never caused a side effect. Avoid testing actual backoff by relying on arbitrary elapsed times.
Practice
Trace two transient errors and one success under a three-attempt budget; then change the second error to permanent.
Reference candidate: node-timeouts-retries-and-circuit-breakers-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/errors.html. Selected versioned documentation opened.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Timeouts retries and circuit breakers — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Does Promise.race cancel the losing promise?
Which failure should a retry policy stop on immediately?
What does a half-open breaker permit?