Design Patterns in Plain Words / Module 09

Module 9: When Other Services Fail

Timeout, retry with backoff and jitter, and Circuit Breaker for a Node.js backend that calls slow services.

On Saturday at 10:00, tickets for the Summer Lights show went on sale. At 10:02 the Buy page stopped loading. Maya opened the logs and saw every request waiting for the seat-map service, with no answer and no end.

“Is our site down?” Leo wrote.

“Our site is fine,” Maya wrote back. “It is waiting for someone else’s.”

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

TinyTickets calls two services it does not control: the seat-map service and the payment provider. Both can be slow, fail for a second, or go down for minutes. This module adds three wrappers that keep TinyTickets answering when that happens, and each one is a Decorator from Module 3 with one job.

After this module, you can:

  • put a time limit on any call to another service, and say what you know when the limit is reached
  • try a failed call again with growing, random waits, and only when a second try is safe
  • stop calling a service that is down, and test that without waiting for real time
  • pick the wrappers a call needs, in the right order, or decide that it needs none

Set up the folder for this module

Use the folder and tsconfig.json from Module 1. This module adds two files that every example imports. The first, seat-map.ts, is the contract for the seat-map service:

export interface SeatMapClient {
  getSeatMap(showId: string, signal: AbortSignal): Promise<string[]>;
}

// What the seat-map client throws when the service answers with an HTTP error
export class HttpError extends Error {
  readonly status: number;
  constructor(status: number) {
    super(`seat map answered ${status}`);
    this.name = "HttpError";
    this.status = status;
  }
}

getSeatMap takes an AbortSignal, the built-in object from Module 1 that tells running work to stop. A real client would pass it on to fetch. HttpError carries the HTTP status, so later code can tell a broken service (503) from a show that does not exist (404).

The second file, seat-map-fake.ts, is a fake of the service. Like every provider in this course, it prints instead of calling a real service. You give it a plan, one answer per call:

import { setTimeout as sleep } from "node:timers/promises";
import { HttpError, type SeatMapClient } from "./seat-map.ts";

// One planned answer per call: wait this many ms and return seats,
// "down" (the service fails: 503) or "missing" (no such show: 404)
export type FakeAnswer = number | "down" | "missing";

// A fake seat-map service. It prints instead of calling seats.tinytickets.example.
// After the last planned answer, it repeats the last one.
export function makeSeatMapFake(answers: FakeAnswer[]): SeatMapClient {
  let calls = 0;
  return {
    async getSeatMap(showId, signal) {
      const answer = answers[Math.min(calls, answers.length - 1)];
      calls++;
      console.log(`[seats] call ${calls} for ${showId}`);
      if (answer === "down") throw new HttpError(503);
      if (answer === "missing") throw new HttpError(404);
      await sleep(answer, undefined, { signal });
      return [`${showId}-A1`, `${showId}-A2`];
    },
  };
}

makeSeatMapFake([50]) answers every call after 50 ms. makeSeatMapFake(["down", "down", 50]) fails twice and then answers. The fake passes the signal to sleep, so it stops when the signal fires, as a real network call would.

Timeout: stop waiting for an answer that will not come

The Buy page waits as long as the seat-map service does

Here is how the Buy page got its free seats on Saturday, seats-before.ts. The loop at the bottom calls a healthy service (50 ms) and then a slow one (3 s):

import { makeSeatMapFake } from "./seat-map-fake.ts";
import type { SeatMapClient } from "./seat-map.ts";

async function freeSeats(client: SeatMapClient, showId: string): Promise<string[]> {
  const controller = new AbortController(); // nothing ever calls abort()
  return client.getSeatMap(showId, controller.signal);
}

// A healthy service answers in 50 ms, a slow one in 3 s
for (const delayMs of [50, 3000]) {
  const started = Date.now();
  try {
    const seats = await freeSeats(makeSeatMapFake([delayMs]), "spring");
    console.log(`${seats.length} free seats`);
  } catch (err: unknown) {
    if (err instanceof Error) console.log(`seat map failed: ${err.name}`);
  }
  console.log(`waited about ${Math.round((Date.now() - started) / 1000)} s`);
}

Output of npx tsx seats-before.ts:

[seats] call 1 for spring
2 free seats
waited about 0 s
[seats] call 1 for spring
2 free seats
waited about 3 s

The code passes a signal, but nothing ever fires it. So if the service takes 3 seconds, the buyer waits 3 seconds. On Saturday the service took minutes, and every open request held its memory and its socket the whole time. Buyers pressed reload, which added more waiting requests.

Leo’s change request was short: “The Buy page must answer within 2 seconds, even when the seat map is slow.”

Adding that inside freeSeats needs a timer, a cleanup for the timer, and a way to tell a timeout from other errors. And the payment call needs the same code.

Pause and predict: Module 1 had a withTimeout that made a signal with AbortSignal.timeout(ms). What happens if the work ignores the signal? And when the timer fires, how does the caller know it was a timeout and not some other error?

The idea: give every call a deadline

A timeout is a limit on how long a call may take. When the time passes, you stop the call and treat it as failed. You set the limit for each service in one place, without touching the code that makes the call.

Think of a phone call to a box office. You decide before you call that you will let it ring ten times, and after the tenth ring you hang up. Figure 1 puts the call next to the code. It also holds the legend for every figure in this course.

Analogy                             Code
you decide: 10 rings at most        limit: 2000 ms
you hang up after the 10th ring     the signal fires; the call stops
you do not know why                 the call's result is unknown

Legend, the same in every module
(Name)         a person
[name]         a module, function or class
[name] (I)     an interface: a shape that other code must fit
A --> B        A calls B
A ..> B        A implements B: A has the shape that interface B asks for
A ==> B        A creates B (with "new" or a factory function)
NEW            a part that the change added
~ await ~      the caller waits here; Node.js serves other work meanwhile

Figure 1: a timeout is a promise to yourself about how long you wait; it says nothing about why the other side was slow.

As the third row of Figure 1 says, a timeout means “I do not know”. The seat-map service may have finished the work a moment after you stopped waiting. For a seat map, that is harmless. For a payment, the charge may have gone through, and the Retry section comes back to that.

The fix: withTimeout reports the timeout itself

Save with-timeout.ts:

// Run `work` with a deadline. The work must pass the signal on.
export async function withTimeout<T>(
  ms: number,
  work: (signal: AbortSignal) => Promise<T>,
): Promise<T> {
  const timer = AbortSignal.timeout(ms);
  try {
    return await work(timer);
  } catch (err: unknown) {
    // The work may throw any error once aborted; report the timeout itself
    if (timer.aborted) throw timer.reason;
    throw err;
  }
}

When the time is up, AbortSignal.timeout fires and sets its reason to an error named TimeoutError. The work then stops and throws its own error. sleep throws an AbortError, and other code may throw something else.

So the catch checks the timer and throws timer.reason instead, and every caller sees the same TimeoutError. The await inside try is needed, because without it a rejection would skip the catch.

Now seats-after.ts uses it. Only one import and the body of freeSeats change, so this excerpt shows those lines. The loop at the bottom is the same as in seats-before.ts.

// excerpt from seats-after.ts: the other imports and the loop are unchanged
import { withTimeout } from "./with-timeout.ts";

async function freeSeats(client: SeatMapClient, showId: string): Promise<string[]> {
  return withTimeout(2000, (signal) => client.getSeatMap(showId, signal));
}

Output:

[seats] call 1 for spring
2 free seats
waited about 0 s
[seats] call 1 for spring
seat map failed: TimeoutError
waited about 2 s

With a healthy service, both versions print the same three lines. With a slow one, the new version gives up at 2 seconds. Figure 2 shows what moved.

Before
  [freeSeats] ==> [AbortController]          nobody calls abort()
  [freeSeats] --> [SeatMapClient] (I)        waits as long as it takes

After
  [freeSeats] --> [withTimeout] NEW --> [SeatMapClient] (I)
  [withTimeout] ==> [AbortSignal.timeout(2000)] NEW
  [seat-map-fake] ..> [SeatMapClient] (I)

Figure 2: the deadline lives in one wrapper; freeSeats only says how long.

Figure 3 follows one request to a slow service through the new code.

1  (Buyer) --> [freeSeats]               seats for "spring"
2  [freeSeats] --> [withTimeout]         limit 2000 ms
3  [withTimeout] ==> [AbortSignal]       AbortSignal.timeout(2000)
4  [withTimeout] --> [SeatMapClient]     getSeatMap("spring", signal)
     ~ await: no answer; Node.js serves other buyers meanwhile ~
5  [AbortSignal] fires at 2000 ms; the fake's sleep stops
6  [withTimeout] throws the signal's reason, a TimeoutError
7  [freeSeats] rejects; the route answers (Buyer) at 2 s, not 3 s

Figure 3: the buyer’s wait now has an upper limit, and the slow call is stopped, not left running.

Rule: Every call that leaves your process gets a time limit, and the work must pass the signal on.

Test the timeout without waiting

A test of a timeout must not wait for real seconds. So the test uses a fake service that never answers on its own and stops only when its signal fires. Then a limit of 20 ms is enough. Save with-timeout.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import type { SeatMapClient } from "./seat-map.ts";
import { withTimeout } from "./with-timeout.ts";

// A fake service that never answers: it only stops when the signal fires
const hangingClient: SeatMapClient = {
  getSeatMap: (_showId, signal) =>
    new Promise((_resolve, reject) => {
      signal.addEventListener("abort", () => reject(new Error("stopped")));
    }),
};

test("withTimeout stops a call that never answers", async () => {
  await assert.rejects(
    withTimeout(20, (signal) => hangingClient.getSeatMap("spring", signal)),
    { name: "TimeoutError" },
  );
});

test("withTimeout passes a fast answer through", async () => {
  const seats = await withTimeout(20, async () => ["spring-A1"]);
  assert.deepEqual(seats, ["spring-A1"]);
});

npx tsx --test with-timeout.test.ts prints:

✔ withTimeout stops a call that never answers (22.149833ms)
✔ withTimeout passes a fast answer through (0.341041ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

The times come from one run, and yours will differ. The first test also proves the point of the catch, because the fake rejects with "stopped" and the test still sees TimeoutError. A test of the “before” code would hang until the test runner gave up.

The next change: stop when the buyer leaves

Leo noticed that a buyer who closes the page still costs a seat-map call that runs until the limit. Maya wanted the call to stop when the buyer leaves or when the 2 seconds pass. AbortSignal.any([a, b]) returns a signal that fires when any of its input signals fires. The change is two lines and one parameter in with-timeout.ts:

// Run `work` with a deadline. The work must pass the signal on.
export async function withTimeout<T>(
  ms: number,
  work: (signal: AbortSignal) => Promise<T>,
  callerSignal?: AbortSignal, // NEW: stop early when the caller gives up
): Promise<T> {
  const timer = AbortSignal.timeout(ms);
  const signal = callerSignal ? AbortSignal.any([callerSignal, timer]) : timer; // NEW
  try {
    return await work(signal); // CHANGED: was work(timer)
  } catch (err: unknown) {
    // The work may throw any error once aborted; report the timeout itself
    if (timer.aborted) throw timer.reason;
    throw err;
  }
}

seats-next.ts plays a buyer who leaves after 100 ms:

import { makeSeatMapFake } from "./seat-map-fake.ts";
import { withTimeout } from "./with-timeout.ts";

const client = makeSeatMapFake([3000]);
const buyerLeft = new AbortController();
setTimeout(() => buyerLeft.abort(), 100); // the buyer closes the page after 100 ms

const started = Date.now();
try {
  await withTimeout(2000, (signal) => client.getSeatMap("spring", signal), buyerLeft.signal);
} catch (err: unknown) {
  if (err instanceof Error) console.log(`seat map stopped: ${err.name}`);
}
console.log(`waited about ${Math.round((Date.now() - started) / 100) * 100} ms`);

Output:

[seats] call 1 for spring
seat map stopped: AbortError
waited about 100 ms

The error is an AbortError, not a TimeoutError, because the timer did not fire. So callers can still tell “too slow” from “nobody wants the answer now”. freeSeats, the fake and both tests did not change, and the tests still pass. In an Express route, you would abort the controller when the response closes before it has finished.

When a timeout is worth it, and what it costs

Use a timeout on every call that leaves your process, such as an HTTP request or a database query. In code, the sign is an await on a network call with no signal, or with a signal that nothing fires. Pick the limit from what the buyer can accept, not from how slow the service usually is.

You don’t need your own wrapper when the client already takes a signal on each call. fetch(url, { signal: AbortSignal.timeout(2000) }) is one line and needs no withTimeout.

A timeout costs a number that someone must choose and keep up to date, because a limit that is too short turns slow successes into failures. It also leaves you with an unknown result, and your code must decide what that means for each call. And the wrapper stops only work that listens to its signal.

Exercise: a time limit on the payment

Leo agreed that buyers can wait 10 seconds for a payment. Maya wrote withTimeout(10_000, () => provider.charge(2550)), where provider fits the PaymentProvider interface and charge(amountCents) has no signal parameter. Does the limit work? If it did fire, was the buyer charged?

Answer

It compiles, because a function that ignores its parameter still fits (signal: AbortSignal) => Promise<T>. But it does not work. Nothing passes the signal to charge, so withTimeout waits as long as charge takes, and the timer has no effect.

To fix it, the payment client must accept a signal and pass it to its HTTP call (an Adapter from Module 3 can add that). If the timer then fires, you do not know whether the buyer was charged. Keep the order "pending" and check with the provider later, and do not show “payment failed”.

Retry: try again, waiting longer each time

Maya’s first retry loop

After Saturday, the logs showed a second kind of failure. The seat-map service sometimes answered 503 for a second and then worked again. A failure that passes on its own like this is called transient.

Leo’s change request: “If the seat map fails for a moment, try again before you show an error.”

Maya’s first attempt put a loop into freeSeats, seats-retry-before.ts:

import { setTimeout as sleep } from "node:timers/promises";
import { makeSeatMapFake } from "./seat-map-fake.ts";
import type { SeatMapClient } from "./seat-map.ts";
import { withTimeout } from "./with-timeout.ts";

async function freeSeats(client: SeatMapClient, showId: string): Promise<string[]> {
  for (let attempt = 1; ; attempt++) {
    try {
      return await withTimeout(2000, (signal) => client.getSeatMap(showId, signal));
    } catch (err: unknown) {
      if (attempt === 3) throw err;
      await sleep(1000); // every buyer waits the same second
    }
  }
}

// The service fails twice with a 503, then answers
const client = makeSeatMapFake(["down", "down", 50]);
const seats = await freeSeats(client, "spring");
console.log(`${seats.length} free seats`);

Output, after about 2 seconds:

[seats] call 1 for spring
[seats] call 2 for spring
[seats] call 3 for spring
2 free seats

It works for one buyer, and it has four problems:

  • It retries every error. A 404 for a show that does not exist is asked three times and will never pass.
  • Every buyer waits exactly 1 second. When 3,000 buyers fail at 10:00:00, all 3,000 try again at 10:00:01, and the recovering service gets the same crowd again.
  • A test of this loop waits 2 real seconds, because sleep is imported, not passed in.
  • The loop lives inside freeSeats, so the next developer who needs a retry copies it. The payment change below shows what happens when the copy lands around a charge.

Pause and predict: what parts of this loop change from one call to another (how many tries, which errors), and what parts stay the same? How would you let a test replace the waiting and the randomness?

The idea: wait longer each time, and not all at once

Retry means that when a call fails in a way that may pass, you wait and call again, a limited number of times. Exponential backoff means the longest allowed wait doubles after each failure: 100 ms, then 200 ms, then 400 ms, up to a cap. Jitter means each wait is a random time between zero and that limit, so clients that failed together do not come back together.

Think of a busy phone line. You get a busy tone, wait a little, and call again, and after each busy tone you wait longer. If a whole crowd is calling the same number, it helps when each person waits a different, random time. Figure 4 matches the two.

Analogy                              Code
busy tone: wait, then call again     503: sleep, then call again
wait longer after each busy tone     ceiling doubles: 100, 200, 400 ms
each caller picks a random moment    wait = random() * ceiling

Figure 4: backoff spreads your own tries over time; jitter spreads everyone’s tries.

The analogy stops fitting at one point, because calling a phone again costs nothing. Calling a service again can repeat work, such as a charge.

Figure 5 shows what jitter changes. It is a sketch, not a measurement.

Fixed wait of 1 s: everyone who failed at 0 s comes back together
time (s)  0          1          2
calls     ||||||||   ||||||||   ||||||||     three spikes of the same size

Backoff with full jitter: each buyer picks a random wait
time (s)  0          1          2
calls     ||||||||   | || | |||  | | |  |    the same calls, spread out

Figure 5: without jitter, retries arrive in waves; with jitter, the service sees a flatter load.

The fix: one retry function whose waiting tests can replace

Save retry.ts:

import { setTimeout as nodeSleep } from "node:timers/promises";

export type Sleep = (ms: number, signal?: AbortSignal) => Promise<void>;

export interface RetryOptions {
  attempts: number; // all tries, the first one included
  baseMs: number; // the longest first wait; it doubles after each failure
  maxMs: number; // no wait is longer than this
  shouldRetry: (err: unknown) => boolean; // only errors that may pass
  signal?: AbortSignal; // the caller can stop the retries
  sleep?: Sleep; // tests pass a fake
  random?: () => number; // a number from 0 up to 1; tests pass a fake
}

export async function retry<T>(work: () => Promise<T>, options: RetryOptions): Promise<T> {
  const sleep = options.sleep ?? ((ms, signal) => nodeSleep(ms, undefined, { signal }));
  const random = options.random ?? Math.random;
  for (let attempt = 1; ; attempt++) {
    options.signal?.throwIfAborted();
    try {
      return await work();
    } catch (err: unknown) {
      if (attempt >= options.attempts || !options.shouldRetry(err)) throw err;
      const ceiling = Math.min(options.maxMs, options.baseMs * 2 ** (attempt - 1));
      await sleep(Math.round(random() * ceiling), options.signal); // full jitter
    }
  }
}

The code calls the doubled limit ceiling, and it stops doubling at maxMs. Each wait is random() * ceiling, a random number from zero up to the ceiling. sleep and random are options with real defaults, so a test can pass fakes.

signal.throwIfAborted() throws the signal’s reason if the caller has already given up. So no new try starts for a buyer who left, and the real sleep also stops early when that signal fires.

Which errors may pass is a fact about the seat-map service, so it goes into seat-map.ts. Add this function at the end of that file:

// Errors that may pass if you try again: a 5xx answer or a timeout. Not a 404.
export function isTransient(err: unknown): boolean {
  if (err instanceof HttpError) return err.status >= 500;
  return err instanceof Error && err.name === "TimeoutError";
}

err is unknown, so the function narrows it with instanceof before it reads status or name. Now seats-retry.ts:

import { makeSeatMapFake } from "./seat-map-fake.ts";
import { isTransient, type SeatMapClient } from "./seat-map.ts";
import { retry } from "./retry.ts";
import { withTimeout } from "./with-timeout.ts";

async function freeSeats(client: SeatMapClient, showId: string): Promise<string[]> {
  return retry(() => withTimeout(2000, (signal) => client.getSeatMap(showId, signal)), {
    attempts: 3,
    baseMs: 100,
    maxMs: 2000,
    shouldRetry: isTransient,
  });
}

// The service fails twice with a 503, then answers
const client = makeSeatMapFake(["down", "down", 50]);
const seats = await freeSeats(client, "spring");
console.log(`${seats.length} free seats`);

The output is the same four lines as the loop, and it arrives in under half a second instead of 2 seconds. retry wraps withTimeout, so every try gets its own 2-second limit. Figure 6 shows the new structure.

Before
  [freeSeats] --> loop: try, sleep(1000), try    copied into each caller
  [freeSeats] --> [withTimeout] --> [SeatMapClient] (I)

After
  [freeSeats] --> [retry] NEW --> [withTimeout] --> [SeatMapClient] (I)
  [retry] --> [isTransient] NEW        which errors may pass
  [retry] --> [sleep] [random]         real ones, or fakes in a test

Figure 6: the loop moved into retry; the caller only says how many tries and which errors.

Figure 7 follows the request from the example: two 503 answers, then seats.

1  (Buyer) --> [freeSeats]                    seats for "spring"
2  [freeSeats] --> [retry]                    3 attempts, base 100 ms
3  [retry] --> [withTimeout] --> [SeatMapClient]   try 1: 503
4  [retry] --> [isTransient]                  a 503 may pass: yes
5  [retry] --> [sleep]                        random wait, at most 100 ms
     ~ await ~
6  [retry] --> [withTimeout] --> [SeatMapClient]   try 2: 503
7  [retry] --> [sleep]                        random wait, at most 200 ms
     ~ await ~
8  [retry] --> [withTimeout] --> [SeatMapClient]   try 3: 2 seats
9  [freeSeats] answers (Buyer)                2 free seats

Figure 7: the buyer waits for two short random pauses, and each try has its own time limit.

Test the retry without waiting

The test passes a fake sleep that records each wait instead of waiting, and a fake random that always returns 0.5. So the waits are exact, half of 100 and half of 200. Save retry.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { retry, type RetryOptions } from "./retry.ts";

function fakeOptions(waits: number[]): RetryOptions {
  return {
    attempts: 3,
    baseMs: 100,
    maxMs: 2000,
    shouldRetry: (err) => err instanceof Error && err.message === "503",
    sleep: async (ms) => { waits.push(ms); }, // no real waiting
    random: () => 0.5, // always the middle of the range
  };
}

test("retry waits longer each time, then returns the answer", async () => {
  const waits: number[] = [];
  let calls = 0;
  const seats = await retry(async () => {
    calls++;
    if (calls < 3) throw new Error("503");
    return ["spring-A1"];
  }, fakeOptions(waits));
  assert.deepEqual(seats, ["spring-A1"]);
  assert.deepEqual(waits, [50, 100]); // half of 100, half of 200
});

test("retry does not repeat an error that will not pass", async () => {
  const waits: number[] = [];
  let calls = 0;
  const work = async () => { calls++; throw new Error("404"); };
  await assert.rejects(retry(work, fakeOptions(waits)), { message: "404" });
  assert.equal(calls, 1);
});

test("retry stops when the caller aborts", async () => {
  const buyerLeft = new AbortController();
  let calls = 0;
  const options = { ...fakeOptions([]), signal: buyerLeft.signal, sleep: async () => buyerLeft.abort() };
  const work = async () => { calls++; throw new Error("503"); };
  await assert.rejects(retry(work, options), { name: "AbortError" });
  assert.equal(calls, 1);
});

Output of npx tsx --test retry.test.ts:

✔ retry waits longer each time, then returns the answer (0.79075ms)
✔ retry does not repeat an error that will not pass (0.263041ms)
✔ retry stops when the caller aborts (0.160792ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0

All three tests finish in about a millisecond. In the third test, the fake sleep plays a buyer who leaves during the wait, and retry starts no second try. Maya’s loop could not be tested like this, because its sleep was a fixed import.

The next change: retry the payment, safely

Leo asked for the same help at checkout: “When the payment provider times out, try again.” This is where retry can hurt buyers. If the provider charged the card and only the answer was lost, a second call charges again.

A call is idempotent when doing it twice has the same effect as doing it once. Reading a seat map is idempotent, but a charge is not.

The usual fix is an idempotency key, a unique value such as the order id that you send with every try of the same charge. The provider remembers the key and answers a repeat with the first result instead of charging again. This works only if the provider supports such a key. pay-retry.ts uses a fake provider whose first answer is lost, and runs the same retry with and without a key:

import { retry } from "./retry.ts";

type PaymentResult = { status: "paid"; chargeId: string } | { status: "declined"; reason: string };

// A fake payment provider. It prints instead of charging. The answer to
// its first call is lost on the way back, as in a network timeout.
function makePayFake() {
  const charges = new Map<string, string>(); // idempotency key -> charge id
  let calls = 0;
  return {
    async charge(amountCents: number, idempotencyKey?: string): Promise<PaymentResult> {
      calls++;
      const earlier = idempotencyKey === undefined ? undefined : charges.get(idempotencyKey);
      if (earlier !== undefined) {
        console.log(`[pay] key ${idempotencyKey} seen before: no new charge`);
        return { status: "paid", chargeId: earlier };
      }
      const chargeId = `ch_${calls}`;
      if (idempotencyKey !== undefined) charges.set(idempotencyKey, chargeId);
      console.log(`[pay] charged ${amountCents} cents as ${chargeId}`);
      if (calls === 1) throw new Error("timeout: the answer was lost");
      return { status: "paid", chargeId };
    },
  };
}

const options = { attempts: 3, baseMs: 100, maxMs: 2000, shouldRetry: () => true };

console.log("Without a key:");
const unsafe = makePayFake();
await retry(() => unsafe.charge(2550), options);

console.log("With a key:");
const safe = makePayFake();
await retry(() => safe.charge(2550, "order-7"), options); // the same key on every try

Output:

Without a key:
[pay] charged 2550 cents as ch_1
[pay] charged 2550 cents as ch_2
With a key:
[pay] charged 2550 cents as ch_1
[pay] key order-7 seen before: no new charge

Without a key, the buyer paid 2550 cents twice. With a key, the second try returned the first charge. retry.ts did not change at all, because the fix is in what the work sends.

In real code, shouldRetry accepts only timeouts and 5xx answers, never every error as in this demo. And a decline is a PaymentResult, not an error, so retry never sees it and never repeats it.

Rule: Retry a call only if it is idempotent or sends the same idempotency key on every try.

When retry is worth it, and what it costs

Use retry when three things are true:

  • The failures are transient, such as timeouts, 503 answers or a dropped connection.
  • The call is idempotent or carries an idempotency key.
  • The caller can afford the extra wait.

In code, the sign is a try/catch around a remote call, where the catch shows an error that a reload usually fixes.

Skip it when the error will not pass, such as a 400, a 404 or a declined card. Skip it when a person is waiting and will press the button again anyway. And skip it inside a background job system that already retries failed jobs, because the two layers multiply. Three tries inside 5 job attempts make 15 calls.

Retry makes the slow path slower. Three tries with a 2-second limit and pauses of up to 100 and 200 ms can take more than 6 seconds. Each try also adds load to a service that is already in trouble, which jitter softens but does not stop. And retry hides failures, so the logs should still record each failed try.

Exercise: predict the waits

Change the options to attempts: 5, baseMs: 100, maxMs: 300, with a fake random that returns 0.5 and work that always fails with a transient error. What does the fake sleep record?

Answer

The fake sleep records [50, 100, 150, 150], because five attempts mean four waits. The ceilings are 100, 200, then 400 and 800, both cut to the 300 cap. Half of each is 50, 100, 150 and 150. After the fifth failure, retry throws instead of waiting.

Circuit Breaker: stop calling a service that is down

Retries make an outage worse

Two weeks later, the seat-map service went down for twenty minutes during a sale. Every buyer’s request now tried three times. Here is the code from the Retry section with three buyers in a row, seats-breaker-before.ts. The service answers once and then stays down:

import { makeSeatMapFake } from "./seat-map-fake.ts";
import { isTransient, type SeatMapClient } from "./seat-map.ts";
import { retry } from "./retry.ts";
import { withTimeout } from "./with-timeout.ts";

async function freeSeats(client: SeatMapClient, showId: string): Promise<string[]> {
  return retry(() => withTimeout(2000, (signal) => client.getSeatMap(showId, signal)), {
    attempts: 3, baseMs: 100, maxMs: 2000, shouldRetry: isTransient,
  });
}

// The service answers once, then goes down
const client = makeSeatMapFake([50, "down"]);
for (const buyer of ["Ana", "Ben", "Chi"]) {
  try {
    const seats = await freeSeats(client, "spring");
    console.log(`${buyer}: ${seats.length} free seats`);
  } catch (err: unknown) {
    if (err instanceof Error) console.log(`${buyer}: ${err.name}`);
  }
}

Output:

[seats] call 1 for spring
Ana: 2 free seats
[seats] call 2 for spring
[seats] call 3 for spring
[seats] call 4 for spring
Ben: HttpError
[seats] call 5 for spring
[seats] call 6 for spring
[seats] call 7 for spring
Chi: HttpError

Ben and Chi each cost three calls and two pauses, and both still got an error. With 3,000 buyers, that is 9,000 calls to a service that is already down. If the service hangs instead of answering 503, each buyer waits for three 2-second timeouts.

Each request is correct alone. Together, they keep the service from recovering and keep the Buy page slow.

Leo’s change request: “When the seat map is down, show the page at once, and leave the seat-map service alone for a while.”

Pause and predict: the knowledge “the service is down” must be shared by all requests. Where would you keep it, and how would the code learn that the service is back?

The idea: trip after repeated failures, then test with one call

A circuit breaker sits in front of the calls to one service. While it is closed, calls pass through. After a set number of failures in a row, it opens, and for a while every call fails at once without reaching the service.

When that time is over, the breaker becomes half-open and lets one trial call through. If the trial succeeds, the breaker closes and calls flow again. If it fails, the breaker opens for another round.

The name comes from the circuit breaker in a house’s fuse box. When too much current flows, it trips and cuts the power, so the wires do not burn. Figure 8 matches the parts.

Analogy                                  Code
[breaker in the fuse box]                [CircuitBreaker]
  sits between the grid and a kettle       sits between freeSeats and
                                           SeatMapClient
too much current: it trips (open)        3 failures in a row: "open"
open: no power reaches the kettle        open: call() throws
                                           CircuitOpenError at once

Figure 8: the breaker protects what is behind it by refusing to pass anything for a while.

The analogy stops fitting at the reset. A house breaker stays open until a person flips it, but the software breaker tests the service itself with one trial call.

The fix: one shared CircuitBreaker

The breaker keeps state that every request shares: the current state, the count of failures, and when it opened. State that lives across calls is a good reason for a class. Save circuit-breaker.ts:

export type BreakerState = "closed" | "open" | "halfOpen";

export class CircuitOpenError extends Error {
  override name = "CircuitOpenError";
}

export interface BreakerOptions {
  failureThreshold: number; // failures in a row that open the circuit
  openMs: number; // how long to fail fast before one trial call
  now?: () => number; // the clock in ms; tests pass a fake
}

export class CircuitBreaker {
  #state: BreakerState = "closed";
  #failures = 0;
  #openedAt = 0;
  #options: BreakerOptions;
  constructor(options: BreakerOptions) {
    this.#options = options;
  }
  get state(): BreakerState {
    return this.#state;
  }

  async call<T>(work: () => Promise<T>): Promise<T> {
    const now = this.#options.now ?? Date.now;
    if (this.#state === "halfOpen") throw new CircuitOpenError("a trial call is running");
    if (this.#state === "open") {
      if (now() - this.#openedAt < this.#options.openMs) throw new CircuitOpenError("circuit is open");
      this.#state = "halfOpen"; // the wait is over: let this one call through
    }
    try {
      const result = await work();
      this.#close();
      return result;
    } catch (err: unknown) {
      this.#failures++;
      if (this.#state === "halfOpen" || this.#failures >= this.#options.failureThreshold) {
        this.#state = "open";
        this.#openedAt = now();
      }
      throw err;
    }
  }

  #close(): void {
    this.#state = "closed";
    this.#failures = 0;
  }
}

Read call from the top. A half-open breaker already has its one trial call running, so any other call fails at once. An open breaker fails at once until openMs has passed, and then it becomes half-open and lets this call through. Any success closes the breaker and resets the count.

A failure in half-open opens the breaker again, and so does the failure that reaches the threshold. Either way, the breaker notes the time from the now option, so a test can move time by hand. A field whose name starts with # is private, so only code inside the class can read it.

CircuitOpenError is its own error class, so callers can show “seat map unavailable” for it. isTransient returns false for it, so retry never tries again while the breaker is open.

Now seats-breaker.ts puts the breaker inside the retry. This excerpt leaves out the imports and the loop over Ana, Ben and Chi. The loop is the same as in seats-breaker-before.ts, and the imports add CircuitBreaker. After the loop, the file prints the breaker’s state.

// excerpt from seats-breaker.ts: imports and the buyer loop are left out
// One breaker for the seat-map service, shared by every request
const seatMapBreaker = new CircuitBreaker({ failureThreshold: 3, openMs: 30_000 });

async function freeSeats(client: SeatMapClient, showId: string): Promise<string[]> {
  return retry(
    () => seatMapBreaker.call(() => withTimeout(2000, (signal) => client.getSeatMap(showId, signal))),
    { attempts: 3, baseMs: 100, maxMs: 2000, shouldRetry: isTransient },
  );
}

console.log(`breaker: ${seatMapBreaker.state}`);

Pause and predict: before you run it, how many [seats] lines will print, and what will Chi see?

Output:

[seats] call 1 for spring
Ana: 2 free seats
[seats] call 2 for spring
[seats] call 3 for spring
[seats] call 4 for spring
Ben: HttpError
Chi: CircuitOpenError
breaker: open

Ana’s line is the same as before. Ben’s three failures opened the breaker. Chi got an answer at once, with no call and no pause, so the run made 4 calls instead of 7. Figure 9 shows the structure.

Before
  [freeSeats] --> [retry] --> [withTimeout] --> [SeatMapClient] (I)

After
  [freeSeats] --> [retry] --> [seatMapBreaker] NEW --> [withTimeout]
  [withTimeout] --> [SeatMapClient] (I)
  [seats-breaker.ts] ==> [CircuitBreaker] NEW    one, for all requests

Figure 9: the breaker sits between the retry and the call, so it sees every try.

The breaker is created once, at the top of the module, because its state must outlive one request. A breaker created inside freeSeats would start closed on every request and never open. The retry sits outside the breaker, so the breaker counts every try and the retry stops at CircuitOpenError.

Rule: Create one breaker per service, share it across requests, and put it inside the retry.

Figure 10 follows Chi’s request while the breaker is open.

1  (Chi) --> [freeSeats]               seats for "spring"
2  [freeSeats] --> [retry]             try 1
3  [retry] --> [seatMapBreaker]        call(work)
4  [seatMapBreaker]                    state "open", 30 s not over:
                                       throws CircuitOpenError at once
5  [retry] --> [isTransient]           CircuitOpenError may pass: no
6  [freeSeats] rejects; the route answers (Chi) at once

Figure 10: while the breaker is open, a request makes no network call and has no await on the service.

Figure 11 is the state figure. In a state figure, read A --> B as “A moves to state B”, and the label on the arrow says when.

  [closed] --- failureThreshold failures in a row ---> [open]
     ^                                                  |  ^
     |                                   openMs passed, |  |
     |                                 next call comes  |  | the trial
     |                                                  v  | call fails
     +------------ the trial call succeeds ------ [halfOpen]

closed:   calls pass; failures in a row are counted
open:     every call fails at once with CircuitOpenError
halfOpen: one trial call passes; other calls fail at once

Figure 11: a breaker has three states, and only the half-open state talks to a service it does not trust.

Test the breaker with a fake clock

The test passes a fake clock, a variable now that the test moves forward by hand. So nothing waits for 30 real seconds. Save circuit-breaker.test.ts:

import { test } from "node:test";
import assert from "node:assert/strict";
import { CircuitBreaker } from "./circuit-breaker.ts";

test("the breaker opens, fails fast, then closes after a good trial", async () => {
  let now = 0; // a fake clock: the test moves time by hand
  const breaker = new CircuitBreaker({ failureThreshold: 3, openMs: 30_000, now: () => now });
  let calls = 0;
  const down = async (): Promise<string[]> => { calls++; throw new Error("503"); };

  for (let i = 0; i < 3; i++) await assert.rejects(breaker.call(down), { message: "503" });
  assert.equal(breaker.state, "open");

  await assert.rejects(breaker.call(down), { name: "CircuitOpenError" });
  assert.equal(calls, 3); // the fourth call never reached the service

  now += 30_000;
  assert.deepEqual(await breaker.call(async () => ["spring-A1"]), ["spring-A1"]);
  assert.equal(breaker.state, "closed");
});

Output of npx tsx --test circuit-breaker.test.ts:

✔ the breaker opens, fails fast, then closes after a good trial (0.976833ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

The fake work is a plain function, and calls proves that the open breaker did not call it.

The next change: a missing show is not an outage

A week later, an old link sent many buyers to the show “winter”, which does not exist. The seat-map service answered 404 each time, which was correct. But the breaker counted three 404 answers as failures and opened. So the next buyer of “spring” got CircuitOpenError from a healthy service.

Leo’s request: “Only count failures that mean the service is broken.” The change is one option and four lines in call:

export interface BreakerOptions {
  failureThreshold: number; // failures in a row that open the circuit
  openMs: number; // how long to fail fast before one trial call
  now?: () => number; // the clock in ms; tests pass a fake
  isFailure?: (err: unknown) => boolean; // NEW: which errors count; default all
}

and, at the top of the catch block in call:

      if (this.#options.isFailure?.(err) === false) {
        this.#close(); // NEW: the service answered, so it is healthy
        throw err;
      }

A 404 means the service answered, so the breaker treats it like a success and then passes the error on. seats-breaker-next.ts sends three requests for “winter” and one for “spring”:

import { CircuitBreaker } from "./circuit-breaker.ts";
import { makeSeatMapFake } from "./seat-map-fake.ts";
import { isTransient } from "./seat-map.ts";

const breaker = new CircuitBreaker({ failureThreshold: 3, openMs: 30_000, isFailure: isTransient });

// Three requests for a show that does not exist, then one for "spring"
const client = makeSeatMapFake(["missing", "missing", "missing", 50]);
for (const showId of ["winter", "winter", "winter", "spring"]) {
  try {
    const seats = await breaker.call(() => client.getSeatMap(showId, AbortSignal.timeout(2000)));
    console.log(`${showId}: ${seats.length} free seats`);
  } catch (err: unknown) {
    if (err instanceof Error) console.log(`${showId}: ${err.message}, breaker ${breaker.state}`);
  }
}

Output:

[seats] call 1 for winter
winter: seat map answered 404, breaker closed
[seats] call 2 for winter
winter: seat map answered 404, breaker closed
[seats] call 3 for winter
winter: seat map answered 404, breaker closed
[seats] call 4 for spring
spring: 2 free seats

Without the isFailure option, the third line for “winter” ends with breaker open, and “spring” prints circuit is open, breaker open. Now the same isTransient serves both the retry and the breaker. freeSeats, the test and the fake did not change, and the test still passes, because isFailure is optional.

When a breaker is worth it, and what it costs

Use a breaker when three things are true:

  • The service can be down for minutes.
  • Your app calls it many times a minute.
  • Failing fast is better for the buyer than waiting.

In code, the sign is a remote call with a timeout and a retry, where the logs during an outage show the same failure thousands of times.

Skip it for calls that happen rarely, because a breaker learns from repeated calls. A nightly job that calls a service once has nothing to count. Skip it for your own main database too. If PostgreSQL is down, TinyTickets cannot work at all, and failing fast changes only the error message.

A breaker adds shared state, and each Node.js process has its own copy. So with four processes, the service gets four sets of trial calls. You must also choose the threshold and the open time, and wrong numbers either never open or open on a healthy service. While open, the breaker refuses calls that might have worked, so you need to show its state in logs or a health check.

Exercise: test the failed trial

Write a second test: after the breaker opens and openMs passes, the trial call fails. What state should the breaker be in, and what does the next call do?

Answer

The breaker opens again, and the next call fails at once with CircuitOpenError:

test("a failed trial call opens the breaker again", async () => {
  let now = 0;
  const breaker = new CircuitBreaker({ failureThreshold: 1, openMs: 30_000, now: () => now });
  const down = async (): Promise<string[]> => { throw new Error("503"); };

  await assert.rejects(breaker.call(down), { message: "503" });
  now += 30_000;
  await assert.rejects(breaker.call(down), { message: "503" }); // the trial call
  assert.equal(breaker.state, "open");
  await assert.rejects(breaker.call(down), { name: "CircuitOpenError" });
});

Add it to circuit-breaker.test.ts, and both tests pass. A threshold of 1 keeps the test short.

Bulkhead: keep one slow service from using up what everyone shares

Suppose the seat-map route holds a database connection while it waits. Then ten slow seat-map requests take all ten connections in the pool, and checkout waits behind them.

A bulkhead gives each service you call its own limited share of a resource, so one slow service cannot use up what the others need. The name comes from ships, whose hull is split into compartments so that one leak does not sink the whole ship. Figure 12 shows the fix, a limit of five seat-map calls at a time, so at least five connections stay free.

Without a bulkhead
  [seats route] --> [db pool: 10]       10 slow requests hold all 10
  [checkout route] --> [db pool: 10]    waits: no connection is free

With a bulkhead
  [seats route] --> [seat-map limit: 5 at a time] NEW --> [SeatMapClient]
  [checkout route] --> [db pool: 10]    at least 5 connections stay free

Figure 12: a bulkhead caps how much of a shared resource one service may hold.

You need one when a slow call to one service makes unrelated routes slow too. The cost is one more limit to choose, and under load it rejects or delays calls past that limit.

Fallback: give a lesser answer instead of an error

When the seat map fails, the buyer sees an error page, even when an older seat map would still help.

A fallback is the answer you give when the real one fails, such as the last seat map you saw or a page without the optional part. It turns a TimeoutError or CircuitOpenError into something the buyer can still use. Figure 13 shows the seat page with a fallback.

[seatsPage] --> [freeSeats]       throws TimeoutError or CircuitOpenError
[seatsPage] --> [lastKnownSeats] NEW   the seat map from 5 minutes ago
[seatsPage] answers (Buyer)      "Seat map may be out of date"

Figure 13: the fallback sits outside every other wrapper and catches what they let through.

You need one when a lesser answer exists and is better than an error page. The cost is stale or partial data, so tell the buyer, as Figure 13 does. Never use a fallback that pretends something happened, such as a fake “paid” for a charge that timed out.

Side by side

All five patterns wrap a call to another service. The table compares them.

Pattern The problem it solves What it lets you change Its cost
Timeout A call can hang with no end How long you wait per call A number to choose; an unknown result to handle
Retry with backoff and jitter Short failures reach buyers How often and which errors you try again Slower failures; extra load; unsafe for non-idempotent calls
Circuit Breaker An outage is made worse by calls When to stop calling, and for how long Shared state per process; two numbers to tune
Bulkhead One slow service uses up a shared resource How much each service may hold A limit that rejects calls under load
Fallback An error page where a lesser answer would do What the buyer sees when calls fail Stale or partial data; must never fake success

Figure 14 is the decision figure for this module. It starts from a call to another service and has an exit with no pattern.

A call to another service is slow or fails
  |
  v
Does the call have a time limit? -- no --> Add a Timeout first. Always.
  | yes
  v
Is it rare, with a person who can try again? -- yes --> No pattern needed.
  | no                                         Show a clear error.
  v
Do the failures pass in seconds (503, timeout)? -- no --> No retry.
  | yes
  v
Is the call safe to repeat (a read, or a key)? -- no --> Add an
  | yes                                       idempotency key first.
  v
Retry with backoff and jitter, 2 or 3 attempts
  |
  v
Can the service be down for minutes, under many calls? -- yes -->
  | no                                    add a Circuit Breaker, and a
  v                                       Fallback if a lesser answer
Done                                      exists

Figure 14: a timeout is always the first step; the other patterns each need a reason.

Check yourself

  1. A call stopped by a timeout: did it fail?
  2. Why does a retry wait a random time instead of a fixed time?
  3. Which of these is safe to retry as it is: reading a seat map, charging a card, sending a reminder SMS?
  4. What does a circuit breaker do in each of its three states?
  5. In the order Fallback, Retry, Circuit Breaker, Timeout (outside to inside), why is the timeout the innermost wrapper?
Answers
  1. You do not know. The other side may have finished the work after you stopped waiting. For a read that is harmless, but for a charge, treat the result as unknown and check later.
  2. So that clients that failed at the same moment do not all retry at the same moment. Jitter spreads the tries, and the service sees a flatter load.
  3. Reading a seat map is idempotent and safe. A charge is safe only if every try sends the same idempotency key. A reminder SMS is not idempotent, because a second try may send a duplicate text, which you may accept.
  4. Closed: calls pass and failures in a row are counted. Open: every call fails at once with CircuitOpenError. Half-open: one trial call passes, and success closes the breaker while failure opens it again.
  5. So that each try gets its own time limit, and the breaker and the retry see a timeout as one failed try.

Lab: retry reminders without stopping the loop

Time: about 20 minutes. Make a folder lab next to your other files, and copy retry.ts into it.

Module 1’s lab ended with sendReminders, which sends one reminder per buyer by email, SMS or push. Since then, someone added retries by hand. Here is reminders.ts now:

import { setTimeout as sleep } from "node:timers/promises";

export type Channel = "email" | "sms" | "push";
export type Buyer = { name: string; channel: Channel; contact: string };
export type Send = (to: string, text: string) => Promise<void>;
export type Senders = Record<Channel, Send>;

// A sender throws this when the address can never work (no such number or device)
export class BadAddressError extends Error {
  override name = "BadAddressError";
}

export async function sendReminders(senders: Senders, buyers: Buyer[], showTitle: string): Promise<number> {
  let sent = 0;
  for (const buyer of buyers) {
    const text = `Hi ${buyer.name}, ${showTitle} starts at 19:00 tonight.`;
    if (buyer.channel === "sms") {
      // SMS fails a lot on sale nights, so try three times
      for (let i = 0; i < 3; i++) {
        try {
          await senders.sms(buyer.contact, text);
          sent++;
          break;
        } catch {
          await sleep(1000);
        }
      }
    } else if (buyer.channel === "email") {
      try {
        await senders.email(buyer.contact, text);
      } catch {
        await sleep(2000);
        await senders.email(buyer.contact, text);
      }
      sent++;
    } else {
      await senders.push(buyer.contact, text);
      sent++;
    }
  }
  return sent;
}

The change request from Leo: “Every channel should try up to three times, waiting longer each time. Never retry an address that can never work. One buyer’s failure must not stop the reminders for everyone else, and I want the names of buyers who got nothing.”

Refactor reminders.ts so that this test file, reminders.test.ts, passes with no real waiting:

import { test } from "node:test";
import assert from "node:assert/strict";
import { BadAddressError, sendReminders, type Buyer, type Senders } from "./reminders.ts";

const buyers: Buyer[] = [
  { name: "Ana", channel: "email", contact: "ana@example.com" },
  { name: "Ben", channel: "sms", contact: "+15550101" },
  { name: "Chi", channel: "push", contact: "device-42" },
];

test("failing sends are retried with growing waits; one bad buyer stops nobody", async () => {
  const sent: string[] = [];
  const waits: number[] = [];
  let smsCalls = 0;
  let pushCalls = 0;
  const senders: Senders = {
    email: async (to) => { sent.push(`email ${to}`); },
    sms: async (to) => {
      smsCalls++;
      if (smsCalls < 3) throw new Error("sms service answered 503");
      sent.push(`sms ${to}`);
    },
    push: async () => {
      pushCalls++;
      throw new BadAddressError("unknown device");
    },
  };

  const report = await sendReminders(senders, buyers, "Songs of Spring", {
    sleep: async (ms) => { waits.push(ms); },
    random: () => 0.5,
  });

  assert.deepEqual(report, { sent: 2, failed: ["Chi"] });
  assert.deepEqual(sent, ["email ana@example.com", "sms +15550101"]);
  assert.deepEqual(waits, [500, 1000]); // SMS: two waits that grow
  assert.equal(pushCalls, 1); // a bad address is never retried
});

Run it with npx tsx --test reminders.test.ts, and check types with npx tsc --noEmit. Against the current code, the test fails after about 2 real seconds of waiting, because Chi’s BadAddressError escapes and stops the loop.

Pause and predict: list the three problems in the current code that the change request names. Which part of the retry is the same for every channel, and which part is specific to one call?

Hint 1

The three channels have three different retry rules, and none of them is the one Leo asked for. The retry itself is the same for every channel, and only the sender differs. senders[buyer.channel] picks the sender, as in Module 1.

Hint 2

Use retry from retry.ts. shouldRetry returns false for a BadAddressError. Put a try/catch around the whole retry for one buyer, so a failure adds the name to failed and the loop goes on.

Hint 3

The test passes a fourth argument with sleep and random. Give sendReminders a parameter wait: { sleep?: Sleep; random?: () => number } = {} and spread it into the retry options. The expected waits, 500 and 1000 with random at 0.5, tell you that baseMs is 1000.

Solution

reminders.ts:

import { retry, type Sleep } from "./retry.ts";

export type Channel = "email" | "sms" | "push";
export type Buyer = { name: string; channel: Channel; contact: string };
export type Send = (to: string, text: string) => Promise<void>;
export type Senders = Record<Channel, Send>;
export type Report = { sent: number; failed: string[] };

// A sender throws this when the address can never work (no such number or device)
export class BadAddressError extends Error {
  override name = "BadAddressError";
}

export async function sendReminders(
  senders: Senders,
  buyers: Buyer[],
  showTitle: string,
  wait: { sleep?: Sleep; random?: () => number } = {},
): Promise<Report> {
  const report: Report = { sent: 0, failed: [] };
  for (const buyer of buyers) {
    const text = `Hi ${buyer.name}, ${showTitle} starts at 19:00 tonight.`;
    try {
      await retry(() => senders[buyer.channel](buyer.contact, text), {
        attempts: 3,
        baseMs: 1000,
        maxMs: 10_000,
        shouldRetry: (err) => !(err instanceof BadAddressError),
        ...wait,
      });
      report.sent++;
    } catch {
      report.failed.push(buyer.name); // real code would also log the error
    }
  }
  return report;
}

npx tsx --test reminders.test.ts prints:

✔ failing sends are retried with growing waits; one bad buyer stops nobody (1.4735ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

Three hand-written retry rules became one call to retry, and the if chain over channels went away. The test runs in about a millisecond, because sleep and random are fakes.

A reminder is not idempotent, so if the SMS service sent the text and only its answer was lost, Ben gets two texts. For a reminder that is acceptable, but for a charge it would not be. The solution adds no circuit breaker, because reminders run once a day in a short burst and a breaker would have few calls to learn from.

shouldRetry retries every error except a bad address, because the senders do not tell 4xx from 5xx yet. When they do, use a check like isTransient.

Which pattern, if any?

Scenario 1: the payment provider times out at checkout

The checkout code calls the payment provider with a 10-second limit. Its payment client was adapted (Module 3) to accept a signal. This is an excerpt, and provider, order and res come from the route around it:

// excerpt from the checkout route
const result = await withTimeout(10_000, (signal) => provider.charge(order.totalCents, { signal }));
if (result.status === "declined") {
  res.status(402).json({ error: result.reason });
  return;
}

A few times per sale, the provider does not answer within 10 seconds, and the buyer sees an error. Leo’s request: “When the payment times out, try again automatically.”

Hint 1

Ask the idempotency question first. If the timeout fired, was the buyer charged?

Hint 2

Look at which outcomes are errors and which are results. A decline arrives as result.status, not as a thrown error.

A strong answer

Retry, but only after the call carries an idempotency key, such as the order id, sent on every try. Without a key, a retry after a lost answer charges the buyer twice. If the provider supports no key, do not retry. Keep the order "pending", tell the buyer the payment is being checked, and ask the provider for the result later.

With a key, use two or three attempts, shouldRetry only for timeouts and 5xx answers, and backoff with jitter. A decline is a result, not an error, so retry never repeats it. The buyer’s total wait grows, so the limit for each try may need to shrink, for example to 5 seconds.

A circuit breaker can help if the provider has long outages, so buyers learn at once that payments are down. Add no fallback, because there is no lesser answer for a payment.

Scenario 2: Leo’s monthly seat report

Once a month, Leo opens an admin page that lists each show with its free seats. Here is the excerpt that loads one show:

// excerpt from the admin report route
const seats = await withTimeout(5000, (signal) => seatMapClient.getSeatMap(show.id, signal));
rows.push({ title: show.title, freeSeats: seats.length });

The report covers four shows. Twice this year, the seat-map service was slow and Leo saw an error. He pressed reload, and it worked. Maya’s teammate suggests “a retry and a circuit breaker, like the Buy page has”.

Hint 1

How many calls does this page make in a month, and who is waiting for it?

Hint 2

Go through Figure 14 from the top.

A strong answer

Add no new pattern. The call already has a timeout. The page makes four calls a month, so a breaker would never see enough failures to learn anything. A person is waiting and can press reload, which is the retry.

The useful change is a clear message, such as “The seat map did not answer. Try again in a minute.”, instead of a generic error. If Leo later runs the report as a nightly job with nobody watching, one retry with backoff becomes worth adding.

Get feedback on your answer

Copy this prompt into an AI assistant, with your answer at the end:

I am learning resilience patterns (Timeout, Retry with backoff and jitter,
Circuit Breaker, Bulkhead, Fallback) in TypeScript and Node.js. Below is a
scenario and my answer. Tell me whether my choice fits the scenario, what I
missed about idempotency and about the cost of each pattern, and whether a
simpler option would work. Do not rewrite my whole answer; point to the
weakest part first.

Scenario: <paste the scenario and its code>
My answer: <paste your answer>

Going deeper

You can skip this section. It covers where the patterns come from, the class form of a wrapper, and libraries that do the same jobs.

Where these patterns come from

None of the five is one of the 23 patterns in the Gang of Four (GoF) book. Michael Nygard listed Timeouts, Circuit Breaker and Bulkheads as stability patterns, patterns that keep a system working when its parts fail. His book is Release It! (2007; second edition, 2018). Martin Fowler’s article CircuitBreaker (2014) describes the breaker, including the half-open state.

The retry in this module uses full jitter, where each wait is random between zero and the ceiling. It comes from Marc Brooker’s article Exponential Backoff And Jitter on the AWS Architecture Blog (2015). The article simulated competing clients and found that jitter cut the number of calls by more than half compared with backoff alone.

The class form of a wrapper

Each wrapper in this module can also be a class that has the client’s shape and adds its job to every call. This is the Decorator class form from Module 3. For example, a TimedSeatMapClient class could take a client and a limit, and its getSeatMap would call withTimeout.

Prefer the function when different calls need different limits. Prefer the class when one service always gets the same limit, and you want callers to receive a client that already has it. For retry, a class that only stores the options adds little over the function. The breaker is a class because it carries state across calls, but a closure that holds the same three variables works too.

Libraries that do the same jobs

  • Node.js has the parts built in: AbortSignal.timeout, AbortSignal.any and the signal option of setTimeout in node:timers/promises.
  • opossum creates a breaker with new CircuitBreaker(action, options) and runs it with breaker.fire(...). It opens on a failure rate (errorThresholdPercentage) instead of on failures in a row, and it waits resetTimeout ms before a half-open trial. Its timeout option counts a call that runs too long as a failure, and breaker.fallback(fn) registers a fallback.
  • cockatiel has retry(handleAll, { maxAttempts: 3, backoff: new ExponentialBackoff() }). Its README says ExponentialBackoff uses decorrelated jitter by default, a variant from the same AWS article. Its circuitBreaker with ConsecutiveBreaker opens after failures in a row, like the class in this module, and bulkhead(limit, queue) runs at most limit calls at once.
  • In Node.js, an http.Agent with maxSockets limits open sockets per origin. So a separate agent for each service works as a bulkhead for sockets.
  • The IETF draft The Idempotency-Key HTTP Header Field describes a header for idempotency keys. It is still a draft, not a standard.

Patterns these get confused with

  • Proxy (Module 3) controls access to an object. A breaker is a Proxy-like wrapper whose access rule is “is the service healthy?”.
  • State (Module 4) moves an object between states. The breaker uses a union of three state names instead of three state classes, because each state has one or two lines of behavior.
  • A job queue’s retry runs a failed job again over minutes and survives a restart. retry works over milliseconds, inside one request.

Cheat sheet

Pattern The problem The signal in your code
Timeout A remote call can hang with no end An await on a network call with no signal, or a signal nothing fires
Retry with backoff and jitter Short failures reach buyers A reload fixes the error; the call is a read or has an idempotency key
Circuit Breaker Calls to a down service make the outage worse The same failure logged thousands of times during an outage
Bulkhead One slow service slows unrelated routes Checkout gets slow when only the seat map is slow
Fallback An error page where a lesser answer would do A cached or partial answer exists and is better than nothing
No pattern Rare calls with a person who can try again A few calls a month; a timeout and a clear message are enough

Figure 15 shows the wrappers around one seat-map request, from outside to inside.

[seatsPage]              Fallback: catches any error, shows the last map
  [retry]                Retry: up to 3 tries, random growing waits
    [seatMapBreaker]     Circuit Breaker: fails fast while the service
                           is down; retry does not repeat that error
      [withTimeout]      Timeout: each try stops after 2000 ms
        [SeatMapClient] (I)     the call over the network
A Bulkhead limits how many of these run at the same time.

Figure 15: each wrapper answers one question, and the order decides what each one sees.

  • Timeout first: every remote call gets a limit, and a call stopped by it has an unknown result.
  • Retry: only transient errors, only calls that are idempotent or send an idempotency key, with growing random waits.
  • Breaker: one per service, shared by every request, counting only errors that mean the service is broken.
  • Order: Fallback, Retry, Circuit Breaker, Timeout, from outside to inside.
  • Tests: pass the sleep, the random and the clock in, so no test waits for real time.

Next, Module 10 uses every pattern of the course on three messy pieces of TinyTickets code, one of them a nightly show import whose seat-map calls have no timeout.

Sources