Design Patterns in Plain Words / Module 10

Module 10: Capstone

Three refactorings of a TinyTickets backend that use the patterns from Modules 1 to 9, plus the pairs people confuse and the signs of overuse.

Leo sent Maya three messages on one Monday. Buyers wanted to pay by bank transfer. One buyer’s push message had never arrived. The nightly show import had started at 02:00, and at 08:00 it was still waiting.

“Can you fix all three this week?” Leo wrote.

“Yes,” Maya wrote back. “But first I’ll list what will change.”

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

This module has no new pattern. It gives you a method you can repeat on any codebase, and three refactoring challenges, one for each of Leo’s messages. Then it covers the patterns people confuse, the signs of overuse and a cheat sheet for the whole course.

After this module, you can:

  • apply a six-step method to unfamiliar code, and add a pattern only where a change would otherwise spread
  • refactor messy TinyTickets code until a given test passes, and say what you left alone and why
  • tell apart five pairs of patterns that look alike, by the one difference in each pair
  • spot five signs of pattern overuse, and name the simpler code to go back to

Set up the capstone folders

You need the same tools as in Module 1. This course targets Node.js 26 LTS, and you also need tsx, TypeScript, @types/node, and Express 5 for the first challenge. Make three folders, challenge-1, challenge-2 and challenge-3. Copy Module 1’s package.json, tsconfig.json and fakes.ts into each one.

The payment, email, SMS and push clients in fakes.ts print a line instead of calling a real service. The challenges add three more fakes of the same kind, for a wallet SDK, a seat-map service and a database table.

Each challenge has five parts:

  • today’s code
  • the change requests that are coming
  • a test file that must pass
  • three hints
  • a full solution

Hints and solutions are hidden. Try each challenge for at least 20 minutes before you open the first hint.

A method you can repeat on any codebase

Here is a table Maya could have written for Leo’s SMS request in Module 1, before she added any pattern.

Change request Code it touches today Places
Send an SMS when an order is paid POST /checkout handler, between charge and email 1
Test the confirmation text sendConfirmation, which creates its own MailClient 1, but untestable
Add push next month the handler again, next to the SMS code 1, same function again

A change map is a table like this one, with one row per change and the code that change touches today. This one shows that every change lands in the same function. It also shows that nothing in that function can be tested.

Every refactoring in this course followed the same six steps, and the change map is step 2.

  1. List what is likely to change. Read the change requests you already have. Run git log --oneline -- src/checkout.ts to see how often a file changed, and why. Listen for phrases like “another provider”, “one more channel” or “this keeps timing out”.
  2. Map each change to the code it touches. Write the change map. A change that touches one place is cheap. A change that touches many places is the signal to act.
  3. Pin today’s behavior. Save a test, or a script’s output, that you can compare after each move. If the code cannot be tested at all, making it testable is the first change.
  4. Pick the simplest fix. Go through the exits of Module 1’s Figure 10 in order: a plain edit, then a function, an object map or a union.
  5. Add a pattern only where a change would otherwise spread. Name the change the pattern absorbs, such as “Strategy, so a new provider is one new class”. If you cannot name the change, do not add the pattern.
  6. Write down what you chose not to change, and why. A refactoring that fixes everything never ends. The next reader also needs to know what you saw and left alone.

Figure 1 shows the six steps as one path. It also holds the legend that every figure in this course uses.

1 List what is likely to change        change requests, git log, Leo
  |
  v
2 Map each change to the code it touches     one row per change
  |
  v
3 Pin today's behavior                 a test, or a run script's output
  |
  v
4 Pick the simplest fix                edit, function, object map, union
  |
  v
5 Add a pattern only where a change would otherwise spread
  |
  v
6 Write down what you chose not to change, and why

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: list, map, pin and pick come before any pattern; a pattern is step 5 of 6.

Challenge 1 (beginner): a checkout route with two payment providers

Time: about 45 minutes. Expected patterns: Strategy (Module 4), Factory (Module 2) and Adapter (Module 3).

Today’s checkout code

TinyTickets takes cards through PayClient, the fake card SDK from fakes.ts. It also takes a phone wallet, through a fake wallet SDK with its own shape. The wallet SDK wants dollars as text, such as "25.50", and it answers with approved instead of throwing. Save it as wallet-sdk.ts.

// A fake wallet SDK. It prints instead of calling a real service.
export type WalletRequest = { amount: string; currency: "USD" };
export type WalletAnswer = { approved: boolean; ref?: string; message?: string };

export class WalletSdk {
  constructor(merchantId: string) {
    if (merchantId === "") throw new Error("WalletSdk needs a merchant id");
  }
  async requestPayment(request: WalletRequest): Promise<WalletAnswer> {
    console.log(`[wallet] request ${request.amount} ${request.currency}`);
    if (Number(request.amount) > 50) {
      return { approved: false, message: "wallet limit is 50.00 USD" };
    }
    return { approved: true, ref: "wal_1" };
  }
}

Here is the checkout route as it is today, checkout.ts.

import express from "express";
import { PayClient } from "./fakes.ts";
import { WalletSdk } from "./wallet-sdk.ts";

type Order = {
  id: string;
  showId: string;
  buyerEmail: string;
  quantity: number;
  totalCents: number;
  status: "pending" | "paid" | "cancelled" | "refunded";
};

const shows = new Map([
  ["spring", { title: "Songs of Spring", priceCents: 1200 }],
  ["summer", { title: "Summer Lights", priceCents: 1500 }],
]);
const orders = new Map<string, Order>();

export const app = express();
app.use(express.json());

app.get("/payment-options", (_req, res) => {
  res.json(["card", "wallet"]);
});

app.post("/checkout", async (req, res) => {
  const body: unknown = req.body;
  if (
    typeof body !== "object" || body === null ||
    !("showId" in body) || typeof body.showId !== "string" ||
    !("quantity" in body) || typeof body.quantity !== "number" ||
    !("email" in body) || typeof body.email !== "string" ||
    !("provider" in body) || typeof body.provider !== "string"
  ) {
    res.status(400).json({ error: "bad input" });
    return;
  }
  const show = shows.get(body.showId);
  if (show === undefined) {
    res.status(404).json({ error: "no such show" });
    return;
  }
  const fee = body.quantity >= 4 ? 0 : 150;
  const totalCents = show.priceCents * body.quantity + fee;

  let chargeId = "";
  if (body.provider === "card") {
    const card = new PayClient(process.env.CARD_KEY ?? "test-key");
    const charge = await card.charge(totalCents);
    chargeId = charge.id;
  } else if (body.provider === "wallet") {
    const wallet = new WalletSdk(process.env.WALLET_MERCHANT ?? "tinytickets");
    const answer = await wallet.requestPayment({
      amount: (totalCents / 100).toFixed(2),
      currency: "USD",
    });
    if (!answer.approved) {
      console.log(`[log] wallet declined for ${body.email}`);
      res.status(402).json({ error: answer.message ?? "declined by wallet" });
      return;
    }
    chargeId = answer.ref ?? "unknown";
  } else {
    res.status(400).json({ error: `unknown provider ${body.provider}` });
    return;
  }

  const order: Order = {
    id: `ord_${orders.size + 1}`,
    showId: body.showId,
    buyerEmail: body.email,
    quantity: body.quantity,
    totalCents,
    status: "paid",
  };
  orders.set(order.id, order);
  console.log(`[log] order ${order.id} paid by ${body.provider} (${chargeId})`);
  res.status(201).json(order);
});

app.get("/orders/:id", (req, res) => {
  const order = orders.get(req.params.id);
  if (order === undefined) {
    res.status(404).json({ error: "no such order" });
    return;
  }
  res.json(order);
});

The file exports app without starting a server, so a script can start it on a free port. Save demo.ts, which sends four orders and asks for the payment options.

import { once } from "node:events";
import { app } from "./checkout.ts";

const server = app.listen(0);
await once(server, "listening");
const address = server.address();
if (address === null || typeof address === "string") throw new Error("no port");
const base = `http://localhost:${address.port}`;

async function checkout(body: object): Promise<void> {
  const res = await fetch(`${base}/checkout`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  console.log(res.status, await res.text());
}

await checkout({ showId: "spring", quantity: 2, email: "ana@example.com", provider: "card" });
await checkout({ showId: "spring", quantity: 5, email: "ben@example.com", provider: "wallet" });
await checkout({ showId: "summer", quantity: 2, email: "chi@example.com", provider: "wallet" });
await checkout({ showId: "spring", quantity: 1, email: "ana@example.com", provider: "cash" });
const options = await fetch(`${base}/payment-options`);
console.log(options.status, await options.text());
server.close();

app.listen(0) asks the operating system for any free port. once from node:events waits for the listening event. Here is the output of npx tsx demo.ts.

[pay] charged 2550 cents
[log] order ord_1 paid by card (ch_1)
201 {"id":"ord_1","showId":"spring","buyerEmail":"ana@example.com","quantity":2,"totalCents":2550,"status":"paid"}
[wallet] request 60.00 USD
[log] wallet declined for ben@example.com
402 {"error":"wallet limit is 50.00 USD"}
[wallet] request 31.50 USD
[log] order ord_2 paid by wallet (wal_1)
201 {"id":"ord_2","showId":"summer","buyerEmail":"chi@example.com","quantity":2,"totalCents":3150,"status":"paid"}
400 {"error":"unknown provider cash"}
200 ["card","wallet"]

The code works. Figure 2 shows that both providers live inside the handler, in an if chain that creates a new SDK object on every request.

(Buyer) --> [POST /checkout handler]
              check input, find show, add fee
              if card ......... ==> [PayClient]  --> charge(cents)
              else if wallet .. ==> [WalletSdk]  --> requestPayment(dollars)
              else ............ 400
              save order, log, answer 201
[GET /payment-options] .......... ["card", "wallet"], typed by hand

A new provider edits the if-chain and the options list, and brings
its own answer shape into the middle of the handler.

Figure 2: every provider lives inside the handler, so every new provider edits it.

The change requests coming next

  1. Next month, buyers can pay by bank transfer, with the name "bank".
  2. Maya wants tests for checkout that run without any SDK, real or fake.
  3. Every declined payment, from any provider, must answer 402 with the provider’s reason.
  4. The list from GET /payment-options must always match the providers that work.

The test that must pass

The test calls a function, placeOrder, instead of the HTTP route. Its imports tell you which files and exports it expects. Save checkout.test.ts.

import { test } from "node:test";
import assert from "node:assert/strict";
import { placeOrder } from "./checkout.ts";
import type { PaymentProvider } from "./payment.ts";
import { WalletProvider } from "./providers.ts";

function fakeProvider(charged: number[]): PaymentProvider {
  return {
    async charge(amountCents) {
      charged.push(amountCents);
      return { status: "paid", chargeId: "fake_1" };
    },
  };
}

test("a paid order charges the total with the booking fee", async () => {
  const charged: number[] = [];
  const providers = new Map([["card", fakeProvider(charged)]]);
  const input = { showId: "spring", quantity: 2, email: "ana@example.com", provider: "card" };

  const answer = await placeOrder(providers, input);

  assert.equal(answer.status, 201);
  assert.deepEqual(charged, [2550]);
});

test("a new provider needs no change in placeOrder", async () => {
  const charged: number[] = [];
  const providers = new Map([["bank", fakeProvider(charged)]]);
  const input = { showId: "spring", quantity: 4, email: "ben@example.com", provider: "bank" };

  const answer = await placeOrder(providers, input);

  assert.equal(answer.status, 201);
  assert.deepEqual(charged, [4800]);
});

test("a declined payment answers 402 with the reason", async () => {
  const declines: PaymentProvider = {
    async charge() {
      return { status: "declined", reason: "card expired" };
    },
  };
  const input = { showId: "spring", quantity: 1, email: "chi@example.com", provider: "card" };

  const answer = await placeOrder(new Map([["card", declines]]), input);

  assert.deepEqual(answer, { status: 402, error: "card expired" });
});

test("an unknown provider answers 400", async () => {
  const input = { showId: "spring", quantity: 1, email: "ana@example.com", provider: "cash" };
  const answer = await placeOrder(new Map(), input);
  assert.deepEqual(answer, { status: 400, error: "unknown provider cash" });
});

test("the wallet adapter sends dollars and maps the answer", async () => {
  const requests: string[] = [];
  const fakeSdk = {
    async requestPayment(request: { amount: string; currency: "USD" }) {
      requests.push(`${request.amount} ${request.currency}`);
      return request.amount === "25.50"
        ? { approved: true, ref: "wal_9" }
        : { approved: false, message: "wallet limit is 50.00 USD" };
    },
  };
  const wallet = new WalletProvider(fakeSdk);

  assert.deepEqual(await wallet.charge(2550), { status: "paid", chargeId: "wal_9" });
  assert.deepEqual(await wallet.charge(6000), {
    status: "declined",
    reason: "wallet limit is 50.00 USD",
  });
  assert.deepEqual(requests, ["25.50 USD", "60.00 USD"]);
});

fakeProvider returns a plain object with the shape of PaymentProvider, so it needs no class. Against today’s code, the test cannot even load. npx tsc --noEmit -p . reports that checkout.ts has no exported member placeOrder, and that ./payment.ts and ./providers.ts cannot be found.

npx tsx --test checkout.test.ts ends with ℹ pass 0 and ℹ fail 1, because ./providers.ts does not exist. Your goal is to make the test pass, keep npx tsc --noEmit -p . clean, and keep the demo’s output the same.

Pause and predict: write the change map for the four requests before you open a hint. Which lines does each request touch today? Which of them touch the same lines?

Hint 1

Here is the change map.

Change request Code it touches today
Add “bank” the if chain, the options list
Test without SDKs new PayClient and new WalletSdk inside the handler
402 for every decline the card branch (it cannot decline today) and the wallet branch
Options match providers the options list, typed by hand

What changes is the list of providers and how each one charges. What stays the same is the input check, the price, the booking fee and saving the order.

Hint 2

Give every provider the same shape, PaymentProvider. Its charge(amountCents) method returns a PaymentResult union of "paid" and "declined". That is a Strategy, because placeOrder calls whichever provider the request names.

The wallet SDK has a different shape, so it needs an Adapter. That is a class with the PaymentProvider shape that converts cents to dollars and approved to status.

Hint 3

Create every provider once, in one factory function, createPaymentProviders(env). It returns a Map from provider name to provider, so the options route can list the map’s keys.

Move the logic of the handler into placeOrder(providers, input), which returns { status, order } or { status, error }. The route then only reads the body and writes the answer.

Solution

payment.ts holds the contract. PaymentResult and PaymentProvider are the names the whole course uses.

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

export interface PaymentProvider {
  charge(amountCents: number): Promise<PaymentResult>;
}

// Provider names come from the request body, so the key is a plain string
export type Providers = ReadonlyMap<string, PaymentProvider>;

ReadonlyMap is the type of a Map without set or delete. So placeOrder can read the providers but cannot change them. providers.ts holds the providers and the factory.

import { PayClient } from "./fakes.ts";
import type { PaymentProvider, PaymentResult, Providers } from "./payment.ts";
import { WalletSdk } from "./wallet-sdk.ts";

export class CardProvider implements PaymentProvider {
  #client: PayClient;
  constructor(client: PayClient) {
    this.#client = client;
  }
  async charge(amountCents: number): Promise<PaymentResult> {
    const charge = await this.#client.charge(amountCents);
    return { status: "paid", chargeId: charge.id };
  }
}

// Adapter: the wallet SDK wants dollars as text and answers in its own shape
export class WalletProvider implements PaymentProvider {
  #sdk: WalletSdk;
  constructor(sdk: WalletSdk) {
    this.#sdk = sdk;
  }
  async charge(amountCents: number): Promise<PaymentResult> {
    const answer = await this.#sdk.requestPayment({
      amount: (amountCents / 100).toFixed(2),
      currency: "USD",
    });
    if (!answer.approved) {
      return { status: "declined", reason: answer.message ?? "declined by wallet" };
    }
    return { status: "paid", chargeId: answer.ref ?? "unknown" };
  }
}

// Factory: the one place that knows the constructors and their settings
export function createPaymentProviders(env: NodeJS.ProcessEnv): Providers {
  return new Map<string, PaymentProvider>([
    ["card", new CardProvider(new PayClient(env.CARD_KEY ?? "test-key"))],
    ["wallet", new WalletProvider(new WalletSdk(env.WALLET_MERCHANT ?? "tinytickets"))],
  ]);
}

A field whose name starts with # is private in plain JavaScript, so it stays private at run time too. CardProvider turns the card SDK’s { id } into a PaymentResult.

WalletProvider is the Adapter. It converts cents to dollar text on the way in, and approved to status on the way out. createPaymentProviders is the factory, the one place that calls new on an SDK and reads its setting.

checkout.ts keeps the steps that stay the same.

import type { Providers } from "./payment.ts";

export type Order = {
  id: string;
  showId: string;
  buyerEmail: string;
  quantity: number;
  totalCents: number;
  status: "pending" | "paid" | "cancelled" | "refunded";
};
export type CheckoutInput = { showId: string; quantity: number; email: string; provider: string };
export type CheckoutAnswer =
  | { status: 201; order: Order }
  | { status: 400 | 402 | 404; error: string };

const shows = new Map([
  ["spring", { title: "Songs of Spring", priceCents: 1200 }],
  ["summer", { title: "Summer Lights", priceCents: 1500 }],
]);
export const orders = new Map<string, Order>();

export async function placeOrder(providers: Providers, input: CheckoutInput): Promise<CheckoutAnswer> {
  const show = shows.get(input.showId);
  if (show === undefined) return { status: 404, error: "no such show" };
  const provider = providers.get(input.provider);
  if (provider === undefined) return { status: 400, error: `unknown provider ${input.provider}` };

  const fee = input.quantity >= 4 ? 0 : 150;
  const totalCents = show.priceCents * input.quantity + fee;
  const result = await provider.charge(totalCents);
  if (result.status === "declined") {
    console.log(`[log] ${input.provider} declined for ${input.email}`);
    return { status: 402, error: result.reason };
  }
  const order: Order = {
    id: `ord_${orders.size + 1}`, showId: input.showId, buyerEmail: input.email,
    quantity: input.quantity, totalCents, status: "paid",
  };
  orders.set(order.id, order);
  console.log(`[log] order ${order.id} paid by ${input.provider} (${result.chargeId})`);
  return { status: 201, order };
}

placeOrder never names a provider. It asks the map, and an unknown name gets 400. app.ts holds the HTTP part.

import express from "express";
import { orders, placeOrder, type CheckoutInput } from "./checkout.ts";
import type { Providers } from "./payment.ts";

function parseInput(body: unknown): CheckoutInput | undefined {
  if (
    typeof body !== "object" || body === null ||
    !("showId" in body) || typeof body.showId !== "string" ||
    !("quantity" in body) || typeof body.quantity !== "number" ||
    !("email" in body) || typeof body.email !== "string" ||
    !("provider" in body) || typeof body.provider !== "string"
  ) return undefined;
  return { showId: body.showId, quantity: body.quantity, email: body.email, provider: body.provider };
}

export function createCheckoutApp(providers: Providers): express.Express {
  const app = express();
  app.use(express.json());
  app.get("/payment-options", (_req, res) => {
    res.json([...providers.keys()]);
  });
  app.post("/checkout", async (req, res) => {
    const input = parseInput(req.body);
    if (input === undefined) {
      res.status(400).json({ error: "bad input" });
      return;
    }
    const answer = await placeOrder(providers, input);
    if (answer.status === 201) res.status(201).json(answer.order);
    else res.status(answer.status).json({ error: answer.error });
  });
  app.get("/orders/:id", (req, res) => {
    const order = orders.get(req.params.id);
    if (order === undefined) res.status(404).json({ error: "no such order" });
    else res.json(order);
  });
  return app;
}

server.ts is the composition root from Module 6, the one file that wires the real parts together.

import { createCheckoutApp } from "./app.ts";
import { createPaymentProviders } from "./providers.ts";

// Composition root: providers are created once, here
const app = createCheckoutApp(createPaymentProviders(process.env));
app.listen(3000, () => console.log("TinyTickets listening on port 3000"));

In demo.ts, only the first lines change, because the app is now created from the providers. This excerpt shows them.

import { once } from "node:events";
import { createCheckoutApp } from "./app.ts";
import { createPaymentProviders } from "./providers.ts";

const app = createCheckoutApp(createPaymentProviders(process.env));
const server = app.listen(0);

The output of npx tsx demo.ts is the same eleven lines as before, and a diff of the two outputs prints nothing. The test passes.

[log] order ord_1 paid by card (fake_1)
[log] order ord_2 paid by bank (fake_1)
[log] card declined for chi@example.com
✔ a paid order charges the total with the booking fee (0.997ms)
✔ a new provider needs no change in placeOrder (0.116292ms)
✔ a declined payment answers 402 with the reason (0.106083ms)
✔ an unknown provider answers 400 (0.062042ms)
✔ the wallet adapter sends dollars and maps the answer (0.153917ms)
ℹ tests 5
ℹ pass 5
ℹ fail 0

The [log] lines come from placeOrder while the tests run. Figure 3 shows the new structure. Creation happens in one place, and placeOrder depends only on the interface.

[server.ts] --> [createPaymentProviders] NEW                  factory
[createPaymentProviders] ==> [CardProvider] NEW
[createPaymentProviders] ==> [WalletProvider] NEW --> [WalletSdk]
[CardProvider] ..> [PaymentProvider] (I) NEW
[WalletProvider] ..> [PaymentProvider] (I)                    adapter
[server.ts] --> [createCheckoutApp] --> [placeOrder] NEW
[placeOrder] --> [PaymentProvider] (I)                        strategy

Figure 3: the handler no longer creates or names any provider; one factory does.

The cost is five files where there was one. To find the code that charges a wallet, a reader now goes from placeOrder to the map, then to the factory.

The first change request, now. Bank transfer is one new file, bank-provider.ts.

import type { PaymentProvider, PaymentResult } from "./payment.ts";

// A fake bank transfer. It prints instead of calling a real bank.
export class BankTransferProvider implements PaymentProvider {
  async charge(amountCents: number): Promise<PaymentResult> {
    console.log(`[bank] transfer requested for ${amountCents} cents`);
    return { status: "paid", chargeId: "bt_1" };
  }
}

providers.ts gains two lines, marked NEW in this excerpt.

import { BankTransferProvider } from "./bank-provider.ts"; // NEW

    ["bank", new BankTransferProvider()], // NEW

placeOrder, app.ts and the test do not change.

Pause and predict: the demo now also places one bank order. Nobody edited the options route. What does GET /payment-options print?

With one more bank order added to the demo, the new lines of output are these.

[bank] transfer requested for 6000 cents
[log] order ord_3 paid by bank (bt_1)
201 {"id":"ord_3","showId":"summer","buyerEmail":"ben@example.com","quantity":4,"totalCents":6000,"status":"paid"}
200 ["card","wallet","bank"]

The options list grew without an edit, because the route reads the map’s keys.

What this solution does not change, and why.

  • Shows and orders still live in two Maps in checkout.ts. No change request touched storage, and Repository (Module 7) answers a different change.
  • The input check is still written by hand. A schema library, a package that checks data against a shape you declare, is a separate decision with its own cost.
  • A real bank transfer is not paid at once. The fake returns "paid" to keep the union at two cases. A third case, "pending", is the next change when a real bank arrives.

Challenge 2 (intermediate): a notification service with copied retry code

Time: about 60 minutes. Expected patterns: Observer with EventEmitter (Module 5), Decorator (Module 3) and Dependency Injection (Module 6).

Today’s notification code

When an order is paid, TinyTickets tells the buyer on every channel they have. When Leo cancels a show, it tells every buyer of that show. Here is the first part of notifications.ts today.

import { MailClient, PushClient, SmsClient } from "./fakes.ts";

export type BuyerContacts = { name: string; email: string; phone?: string; deviceToken?: string };
export type PaidOrder = { id: string; buyer: BuyerContacts; showTitle: string; quantity: number };

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export async function notifyOrderPaid(order: PaidOrder): Promise<void> {
  const buyer = order.buyer;
  const text = `Hi ${buyer.name}, your ${order.quantity} tickets for ${order.showTitle} are ready.`;

  const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      console.log(`[log] email to ${buyer.email}`);
      await mail.send(buyer.email, text);
      break;
    } catch (err) {
      console.log(`[log] email to ${buyer.email} failed: ${String(err)}`);
      if (attempt === 3) throw err;
      await wait(1000 * attempt);
    }
  }

  if (buyer.phone !== undefined) {
    const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
    for (let attempt = 1; attempt <= 3; attempt++) {
      try {
        console.log(`[log] sms to ${buyer.phone}`);
        await sms.send(buyer.phone, text);
        break;
      } catch (err) {
        console.log(`[log] sms to ${buyer.phone} failed: ${String(err)}`);
        if (attempt === 3) throw err;
        await wait(1000 * attempt);
      }
    }
  }

  if (buyer.deviceToken !== undefined) {
    const push = new PushClient();
    for (let attempt = 1; attempt <= 3; attempt++) {
      try {
        console.log(`[log] push to ${buyer.deviceToken}`);
        await push.send(buyer.deviceToken, text);
        break;
      } catch (err) {
        console.log(`[log] push to ${buyer.deviceToken} failed: ${String(err)}`);
        if (attempt === 3) throw err;
        await wait(1000 * attempt);
      }
    }
  }
}

The rest of the file is shown as an excerpt. notifyShowCancelled copies the email and SMS loops from notifyOrderPaid line for line, with its own text and no push. To run the file, paste those two loops where the comment is.

// Excerpt: the rest of notifications.ts. The two loops are the same as above.
export async function notifyShowCancelled(buyer: BuyerContacts, showTitle: string): Promise<void> {
  const text = `Hi ${buyer.name}, ${showTitle} is cancelled. Your money is on its way back.`;
  // ... the email loop, then the SMS loop if buyer.phone is set ...
  // Push for cancellations is next week's job
}

// checkout.ts and shows.ts call these two
export async function completeOrder(order: PaidOrder): Promise<void> {
  console.log(`[db] order ${order.id} marked paid`);
  await notifyOrderPaid(order); // the buyer's request waits for every message
}

export async function cancelShow(showTitle: string, buyers: BuyerContacts[]): Promise<void> {
  console.log(`[db] ${showTitle} marked cancelled`);
  for (const buyer of buyers) {
    await notifyShowCancelled(buyer, showTitle);
  }
}

So the retry-and-log loop appears five times. Save demo.ts.

import { cancelShow, completeOrder } from "./notifications.ts";

const ana = { name: "Ana", email: "ana@example.com", phone: "+15550100" };
const chi = { name: "Chi", email: "chi@example.com", deviceToken: "device-42" };
const ben = { name: "Ben", email: "ben@example.com", phone: "+15550101" };

await completeOrder({ id: "ord_1", buyer: ana, showTitle: "Songs of Spring", quantity: 2 });
await completeOrder({ id: "ord_2", buyer: chi, showTitle: "Songs of Spring", quantity: 3 });
await cancelShow("Summer Lights", [ben]);

Here is the output of npx tsx demo.ts.

[db] order ord_1 marked paid
[log] email to ana@example.com
[mail] to ana@example.com: Hi Ana, your 2 tickets for Songs of Spring are ready.
[log] sms to +15550100
[sms] to +15550100: Hi Ana, your 2 tickets for Songs of Spring are ready.
[db] order ord_2 marked paid
[log] email to chi@example.com
[mail] to chi@example.com: Hi Chi, your 3 tickets for Songs of Spring are ready.
[log] push to device-42
[push] to device-42: Hi Chi, your 3 tickets for Songs of Spring are ready.
[db] Summer Lights marked cancelled
[log] email to ben@example.com
[mail] to ben@example.com: Hi Ben, Summer Lights is cancelled. Your money is on its way back.
[log] sms to +15550101
[sms] to +15550101: Hi Ben, Summer Lights is cancelled. Your money is on its way back.

Figure 4 shows the structure. Each function creates the clients it needs, and each copy of the loop is a separate place to fix.

[checkout.ts] --> [completeOrder] --> [notifyOrderPaid]
[notifyOrderPaid] ==> [MailClient]     retry + log loop, copy 1
[notifyOrderPaid] ==> [SmsClient]      retry + log loop, copy 2
[notifyOrderPaid] ==> [PushClient]     retry + log loop, copy 3
[shows.ts] --> [cancelShow] --> [notifyShowCancelled]
[notifyShowCancelled] ==> [MailClient], [SmsClient]   copies 4 and 5

Figure 4: the channels are written twice and the retry loop five times, all inside functions that checkout calls directly.

The change requests coming next

  1. A failed SMS must not stop the email or the push. Today, the third failed SMS throws, and push never runs.
  2. Push must not retry. An expired device token fails every time, so three tries only waste time. SMS and email keep three tries.
  3. The buyer’s checkout request must not wait for the messages. Today completeOrder waits for every send.
  4. Leo wants a count of paid orders, and next season a loyalty feature will react to paid orders too. Neither should need an edit in checkout.
  5. Cancellations must also go out by push, as the comment in the code promises.
  6. Tests must run without real clients and without the real one-second and two-second waits.

The test that must pass

Save notifications.test.ts.

import { test } from "node:test";
import assert from "node:assert/strict";
import { setImmediate } from "node:timers/promises";
import { notifyBuyer, wireNotifications } from "./notifications.ts";
import { createOrderEvents } from "./order-events.ts";
import type { Send, Senders } from "./send.ts";
import { withRetry } from "./send-wrappers.ts";

function recordingSenders(sent: string[]): Senders {
  return {
    email: async (to, text) => { sent.push(`email ${to}: ${text}`); },
    sms: async (to, text) => { sent.push(`sms ${to}: ${text}`); },
    push: async (to, text) => { sent.push(`push ${to}: ${text}`); },
  };
}

test("order:paid reaches every channel the buyer has", async () => {
  const sent: string[] = [];
  const events = createOrderEvents();
  wireNotifications(events, recordingSenders(sent), () => {});

  const chi = { name: "Chi", email: "chi@example.com", deviceToken: "device-42" };
  events.emit("order:paid", { id: "ord_2", buyer: chi, showTitle: "Songs of Spring", quantity: 3 });
  await setImmediate(); // let the listener's promises settle; the fakes do no I/O

  assert.deepEqual(sent, [
    "email chi@example.com: Hi Chi, your 3 tickets for Songs of Spring are ready.",
    "push device-42: Hi Chi, your 3 tickets for Songs of Spring are ready.",
  ]);
});

test("a failed SMS does not stop the email or the push", async () => {
  const sent: string[] = [];
  const logs: string[] = [];
  const senders: Senders = {
    ...recordingSenders(sent),
    sms: async () => { throw new Error("sms service down"); },
  };
  const ana = { name: "Ana", email: "ana@example.com", phone: "+15550100", deviceToken: "device-7" };

  await notifyBuyer(senders, ana, "Doors open at 19:00.", (line) => logs.push(line));

  assert.deepEqual(sent, [
    "email ana@example.com: Doors open at 19:00.",
    "push device-7: Doors open at 19:00.",
  ]);
  assert.deepEqual(logs, ["[log] sms to +15550100 gave up: Error: sms service down"]);
});

test("withRetry waits longer each time, with no real waiting", async () => {
  let calls = 0;
  const waits: number[] = [];
  const flaky: Send = async () => {
    calls++;
    if (calls < 3) throw new Error("timeout");
  };

  await withRetry(flaky, 3, async (ms) => { waits.push(ms); })("+15550100", "hi");

  assert.equal(calls, 3);
  assert.deepEqual(waits, [1000, 2000]);
});

test("withRetry gives up after the last attempt", async () => {
  const waits: number[] = [];
  const down: Send = async () => { throw new Error("down"); };
  const send = withRetry(down, 2, async (ms) => { waits.push(ms); });

  await assert.rejects(send("+15550100", "hi"), /down/);
  assert.deepEqual(waits, [1000]);
});

Two details in this test are new. emit calls the listeners at once, but each listener’s sends finish on later promise steps. await setImmediate() from node:timers/promises waits until Node.js has run all pending promise steps. The fakes do no input or output, so every send has finished by then.

The tests of withRetry pass in a sleep function that records the wait and returns at once. So no test waits for real.

Against today’s code, npx tsc --noEmit -p . reports that notifications.ts has no exported member notifyBuyer. npx tsx --test notifications.test.ts reports ℹ fail 1. Your goal is to make the test pass, keep tsc clean, and keep the demo’s output the same.

Pause and predict: write the change map. Which request is about who calls the notifications, which is about the loop, and which is about who creates the clients?

Hint 1

The change map has three groups. Requests 2 and 6 touch the five copies of the loop. Requests 1 and 5 touch the two lists of channels. Requests 3 and 4 touch completeOrder, which calls the notifications directly and waits for them.

Each group points at one pattern.

Hint 2

Make every channel a Send function, (to, text) => Promise<void>, as in Module 1. Then write the loop once, as a wrapper withRetry(send, attempts, sleep) that takes a Send and returns a Send.

Logging is a second wrapper. Wrapping without changing the shape is the Decorator pattern in function form. Push gets the logging wrapper only.

Hint 3

Let completeOrder emit "order:paid" on an event emitter and return. A function wireNotifications(events, senders, log) registers the listeners.

Every dependency comes in as a parameter. One file, main.ts, creates the clients, picks the wrappers and calls wireNotifications, so it is the composition root.

Type the emitter as Module 5 did. That means an OrderEvents map of names and data, and an OrderEmitter interface that accepts only those names.

Solution

send.ts holds the shared types.

export type Channel = "email" | "sms" | "push";
export type Send = (to: string, text: string) => Promise<void>;
export type Senders = Record<Channel, Send>;
export type Log = (line: string) => void;

send-wrappers.ts holds the loop and the logging, each written once.

import type { Log, Send } from "./send.ts";

export type Sleep = (ms: number) => Promise<void>;

// Decorator: logs every attempt, and every failure, around any Send
export function withLogging(name: string, send: Send, log: Log): Send {
  return async (to, text) => {
    log(`[log] ${name} to ${to}`);
    try {
      await send(to, text);
    } catch (err: unknown) {
      log(`[log] ${name} to ${to} failed: ${String(err)}`);
      throw err;
    }
  };
}

// Decorator: tries again after 1 s, 2 s, ...; the caller passes in the sleep
export function withRetry(send: Send, attempts: number, sleep: Sleep): Send {
  return async (to, text) => {
    for (let attempt = 1; ; attempt++) {
      try {
        await send(to, text);
        return;
      } catch (err: unknown) {
        if (attempt >= attempts) throw err;
        await sleep(1000 * attempt);
      }
    }
  };
}

Both functions take a Send and return a Send, so you can put one around the other in either order. order-events.ts names the events and their data.

import { EventEmitter } from "node:events";

export type BuyerContacts = { name: string; email: string; phone?: string; deviceToken?: string };
export type PaidOrder = { id: string; buyer: BuyerContacts; showTitle: string; quantity: number };
export type CancelledShow = { showTitle: string; buyers: BuyerContacts[] };

// Every event name, and the arguments it carries
export type OrderEvents = {
  "order:paid": [order: PaidOrder];
  "show:cancelled": [show: CancelledShow];
};

// The emitter from Module 5, seen through a type that accepts only those names
export interface OrderEmitter {
  on<K extends keyof OrderEvents>(name: K, listener: (...args: OrderEvents[K]) => void): unknown;
  emit<K extends keyof OrderEvents>(name: K, ...args: OrderEvents[K]): boolean;
}

// A plain EventEmitter fits OrderEmitter; the interface does the checking
export function createOrderEvents(): OrderEmitter {
  return new EventEmitter();
}

This is the typed emitter from Module 5, with this challenge’s two events. tsc rejects emit("order:payed", ...), because that name is not a key of OrderEvents. It also rejects emit("order:paid", { id: "x" }), because the order is missing buyer, showTitle and quantity.

BuyerContacts is a buyer with every way to reach them. It is not Module 1’s Buyer, which has one channel and one contact. notifications.ts sends and listens.

import type { BuyerContacts, OrderEmitter } from "./order-events.ts";
import type { Channel, Log, Senders } from "./send.ts";

function contacts(buyer: BuyerContacts): [Channel, string][] {
  const list: [Channel, string][] = [["email", buyer.email]];
  if (buyer.phone !== undefined) list.push(["sms", buyer.phone]);
  if (buyer.deviceToken !== undefined) list.push(["push", buyer.deviceToken]);
  return list;
}

// Sends on every channel the buyer has; one failed channel does not stop the others
export async function notifyBuyer(senders: Senders, buyer: BuyerContacts, text: string, log: Log): Promise<void> {
  await Promise.all(
    contacts(buyer).map(async ([channel, to]) => {
      try {
        await senders[channel](to, text);
      } catch (err: unknown) {
        log(`[log] ${channel} to ${to} gave up: ${String(err)}`);
      }
    }),
  );
}

// Observer: notifications listen; checkout and shows only emit
export function wireNotifications(events: OrderEmitter, senders: Senders, log: Log): void {
  events.on("order:paid", (order) => {
    const { buyer, quantity, showTitle } = order;
    const text = `Hi ${buyer.name}, your ${quantity} tickets for ${showTitle} are ready.`;
    void notifyBuyer(senders, buyer, text, log); // never rejects: it catches every failure
  });
  events.on("show:cancelled", (show) => {
    for (const buyer of show.buyers) {
      const text = `Hi ${buyer.name}, ${show.showTitle} is cancelled. Your money is on its way back.`;
      void notifyBuyer(senders, buyer, text, log);
    }
  });
}

notifyBuyer lists the channels once. Each send catches its own failure, so one channel cannot stop another, and notifyBuyer never rejects.

void in front of a promise says “I chose not to wait for this”. It is safe here because nothing inside can reject. orders.ts is what checkout and the show code call.

import type { BuyerContacts, OrderEmitter, PaidOrder } from "./order-events.ts";

// checkout.ts and shows.ts call these two; they no longer know who listens
export function completeOrder(events: OrderEmitter, order: PaidOrder): void {
  console.log(`[db] order ${order.id} marked paid`);
  events.emit("order:paid", order);
}

export function cancelShow(events: OrderEmitter, showTitle: string, buyers: BuyerContacts[]): void {
  console.log(`[db] ${showTitle} marked cancelled`);
  events.emit("show:cancelled", { showTitle, buyers });
}

main.ts is the composition root, and it also runs the demo.

import { setTimeout as sleep } from "node:timers/promises";
import { MailClient, PushClient, SmsClient } from "./fakes.ts";
import { wireNotifications } from "./notifications.ts";
import { createOrderEvents } from "./order-events.ts";
import { cancelShow, completeOrder } from "./orders.ts";
import type { Log, Senders } from "./send.ts";
import { withLogging, withRetry } from "./send-wrappers.ts";

// Composition root: the only file that creates clients and picks wrappers
const log: Log = (line) => console.log(line);
const mail = new MailClient(process.env.SMTP_HOST ?? "localhost");
const sms = new SmsClient(process.env.SMS_KEY ?? "test-key");
const push = new PushClient();
const senders: Senders = {
  email: withRetry(withLogging("email", (to, text) => mail.send(to, text), log), 3, sleep),
  sms: withRetry(withLogging("sms", (to, text) => sms.send(to, text), log), 3, sleep),
  push: withLogging("push", (to, text) => push.send(to, text), log), // no retry
};
const events = createOrderEvents();
wireNotifications(events, senders, log);

const ana = { name: "Ana", email: "ana@example.com", phone: "+15550100" };
const chi = { name: "Chi", email: "chi@example.com", deviceToken: "device-42" };
const ben = { name: "Ben", email: "ben@example.com", phone: "+15550101" };

completeOrder(events, { id: "ord_1", buyer: ana, showTitle: "Songs of Spring", quantity: 2 });
completeOrder(events, { id: "ord_2", buyer: chi, showTitle: "Songs of Spring", quantity: 3 });
cancelShow(events, "Summer Lights", [ben]);

sleep here is setTimeout from node:timers/promises, which waits for real. The output of npx tsx main.ts is the same fifteen lines as before, and a diff prints nothing. npx tsx --test notifications.test.ts ends with ℹ pass 4 and ℹ fail 0.

Figure 5 shows the new structure. Checkout knows only the emitter, and only main.ts creates clients.

[main.ts] ==> [MailClient], [SmsClient], [PushClient]
[main.ts] ==> senders: withRetry(withLogging(send)) NEW      decorator
[main.ts] --> [wireNotifications] NEW --> [OrderEmitter] (I)  on(...)
[completeOrder] --> [OrderEmitter] (I)   emit("order:paid")   observer
[wireNotifications] --> [notifyBuyer] NEW --> [Senders] (I)
[notifications.test.ts] NEW ==> plain functions ..> [Senders] (I)

Figure 5: checkout emits and returns; the listener, the wrappers and the clients are chosen in main.ts.

completeOrder now returns as soon as emit has called the listeners, before any send finishes. So checkout can answer the buyer while the messages go out, and each channel succeeds or fails alone.

The cost is that no single function shows what happens after a payment. To find out, you search for every on("order:paid" call. A stack trace from a send also passes through two wrappers before it reaches the client.

The next change. Leo’s count of paid orders is two lines in main.ts, marked NEW in this excerpt.

wireNotifications(events, senders, log);
let paidOrders = 0; // NEW: Leo wants a count of paid orders
events.on("order:paid", (order) => log(`[stats] paid orders: ${++paidOrders} (${order.id})`)); // NEW

Checkout does not change. The output gains [stats] paid orders: 1 (ord_1) after Ana’s messages and [stats] paid orders: 2 (ord_2) after Chi’s. They come in that order because the emitter calls listeners in the order they were added.

What this solution does not change, and why.

  • The events stay inside one Node.js process. If the process stops after checkout answers and before a send, that message is lost. A job queue that survives a restart is the next step when lost messages matter. Leo has to decide that it is worth one more process to run.
  • The message texts stay in the listeners. A template system is a different change, and no request asked for one.

Challenge 3 (advanced): a nightly import that holds the whole file

Time: about 90 minutes. Expected patterns: streams and pipeline (Module 8), Repository and Unit of Work (Module 7), Timeout, Retry and Circuit Breaker (Module 9).

Today’s import code

Every night at 02:00, TinyTickets imports a CSV file of shows from organizers. For each show, it asks the seat-map service at https://seats.tinytickets.example how many seats the hall has. The import uses two fakes. Here is seat-map-fake.ts.

// A fake seat-map service. It prints instead of calling
// https://seats.tinytickets.example
export class SeatMapHttpClient {
  async getSeatMap(showId: string, signal?: AbortSignal): Promise<string[]> {
    signal?.throwIfAborted();
    console.log(`[seats] seat map for ${showId}`);
    return Array.from({ length: 200 }, (_, i) => `${showId}-${i + 1}`);
  }
}

And here is db-fake.ts, a table kept in memory.

// A fake database table. It keeps rows in memory instead of PostgreSQL.
export type ShowRow = { id: string; title: string; date: string; priceCents: number; seatCount: number };

const table = new Map<string, ShowRow>();

export const db = {
  async findShow(id: string): Promise<ShowRow | undefined> {
    return table.get(id);
  },
  async insertShow(row: ShowRow): Promise<void> {
    table.set(row.id, row);
  },
  async updateShow(row: ShowRow): Promise<void> {
    table.set(row.id, row);
  },
  allShows(): ShowRow[] {
    return [...table.values()];
  },
};

Both fakes are silent, so the output shows only what the import does. Here is import-shows.ts today.

import { readFile } from "node:fs/promises";
import { db } from "./db-fake.ts";
import { SeatMapHttpClient } from "./seat-map-fake.ts";

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// Runs every night at 02:00 with the CSV file of shows from organizers
export async function importShows(path: string): Promise<void> {
  const text = await readFile(path, "utf8"); // the whole file, in memory
  const lines = text.split(/\r?\n/);
  const header = lines.shift();
  if (header !== "id,title,date,priceCents") {
    throw new Error(`unexpected header: ${header}`);
  }

  const seatMap = new SeatMapHttpClient();
  let imported = 0;
  let lineNo = 1;
  for (const line of lines) {
    lineNo++;
    if (line.trim() === "") continue;
    const [id, title, date, price] = line.split(",");
    const priceCents = Number(price);
    if (!id || !title || !date || !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      throw new Error(`bad line ${lineNo}: ${line}`); // rows before this one are already saved
    }
    if (!Number.isInteger(priceCents) || priceCents < 0) {
      throw new Error(`bad line ${lineNo}: ${line}`);
    }

    let seats: string[] = [];
    for (let attempt = 1; attempt <= 3; attempt++) {
      try {
        seats = await seatMap.getSeatMap(id); // no timeout: a silent service stops the import
        break;
      } catch (err) {
        console.log(`[log] seat map for ${id} failed: ${String(err)}`);
        if (attempt === 3) throw err;
        await wait(5000); // real waiting, the same every time
      }
    }

    const row = { id, title, date, priceCents, seatCount: seats.length };
    const existing = await db.findShow(id);
    if (existing === undefined) {
      await db.insertShow(row); // one write per row, no transaction
    } else {
      await db.updateShow(row);
    }
    imported++;
  }
  console.log(`[log] imported ${imported} shows`);
}

Save a two-row shows.csv.

id,title,date,priceCents
spring,Songs of Spring,2027-03-14,1200
summer,Summer Lights,2027-06-20,1500

Then save run-import.ts, which runs the import and prints the table.

import { db } from "./db-fake.ts";
import { importShows } from "./import-shows.ts";

await importShows("shows.csv");
for (const show of db.allShows()) {
  console.log(`[db] ${show.id} | ${show.title} | ${show.date} | ${show.priceCents} | ${show.seatCount} seats`);
}

Here is the output of npx tsx run-import.ts.

[seats] seat map for spring
[seats] seat map for summer
[log] imported 2 shows
[db] spring | Songs of Spring | 2027-03-14 | 1200 | 200 seats
[db] summer | Summer Lights | 2027-06-20 | 1500 | 200 seats

Figure 6 shows the structure, and the two failures Leo reported.

[run-import.ts] --> [importShows]
[importShows] --> [readFile]          the whole file in one string
[importShows] ==> [SeatMapHttpClient]  --> getSeatMap(id), no signal
[importShows] --> [db]                insert or update, row by row
[importShows] --> [wait]              5 s, real, the same every time

Row 900 is bad: rows 1 to 899 are already in the table.
The seat map accepts the call and never answers: the import waits.

Figure 6: the import reads everything first, writes as it goes, and trusts the seat map to answer.

The change requests coming next

  1. Leo’s largest organizer will send a file with two million rows. readFile puts the whole file into one string, and Node.js limits a string’s length to buffer.constants.MAX_STRING_LENGTH. The import must read the file a piece at a time.
  2. A bad row must leave the table as it was, so the organizer can fix the file and run it again. Today, every row before the bad one is already saved.
  3. Last Tuesday the seat-map service accepted the call and never answered. Each call must give up after 2 seconds.
  4. When the seat-map service is down, each show costs three tries and two waits. After a few shows fail in a row, the import must skip the rest without calling, and report them. Tomorrow’s import tries them again.
  5. Tests must run without a file, without real waiting and without the real clock.

The test that must pass

Save import-shows.test.ts.

import { test } from "node:test";
import assert from "node:assert/strict";
import { Readable } from "node:stream";
import { CircuitBreaker } from "./circuit-breaker.ts";
import { importShows, type ImportDeps, type SeatMapClient } from "./import-shows.ts";
import { InMemoryShowStore } from "./show-store.ts";

const HEADER = "id,title,date,priceCents\n";
const threeSeats: SeatMapClient = { getSeatMap: async (id) => [`${id}-1`, `${id}-2`, `${id}-3`] };

function testDeps(seatMap: SeatMapClient, store = new InMemoryShowStore(), waits: number[] = []): ImportDeps {
  return {
    store,
    seatMap,
    breaker: new CircuitBreaker({ failureThreshold: 3, openMs: 60_000, now: () => 0 }),
    sleep: async (ms) => { waits.push(ms); },
    timeout: () => new AbortController().signal, // never fires
    log: () => {},
  };
}

test("rows split across chunks are imported in one commit", async () => {
  const store = new InMemoryShowStore();
  const chunks = [HEADER + "spring,Songs of Spring,2027-03-14,1200\nsum", "mer,Summer Lights,2027-06-20,1500\n"];

  const report = await importShows(Readable.from(chunks), testDeps(threeSeats, store));

  assert.deepEqual(report, { imported: 2, skipped: 0 });
  assert.deepEqual([...store.table.keys()], ["spring", "summer"]);
  assert.equal(store.table.get("summer")?.seatCount, 3);
});

test("a bad row rolls back the whole import", async () => {
  const store = new InMemoryShowStore();
  const csv = HEADER + "spring,Songs of Spring,2027-03-14,1200\nsummer,Summer Lights,2027-06-20,abc\n";

  await assert.rejects(importShows(Readable.from([csv]), testDeps(threeSeats, store)), /bad line 3/);
  assert.equal(store.table.size, 0); // spring was valid, and it is not saved either
});

test("a seat map that never answers is stopped by the timeout", async () => {
  const waits: number[] = [];
  const silent: SeatMapClient = {
    getSeatMap: (_id, signal) =>
      new Promise<string[]>((_resolve, reject) => {
        if (signal.aborted) reject(signal.reason);
        signal.addEventListener("abort", () => reject(signal.reason));
      }),
  };
  const deps = { ...testDeps(silent, new InMemoryShowStore(), waits), timeout: () => AbortSignal.abort() }; // already expired

  const report = await importShows(Readable.from([HEADER + "spring,Songs of Spring,2027-03-14,1200\n"]), deps);

  assert.deepEqual(report, { imported: 0, skipped: 1 });
  assert.deepEqual(waits, [500, 1000]); // 3 attempts, longer wait each time, no real waiting
});

test("after three failed shows the breaker skips the rest without calling", async () => {
  let calls = 0;
  const down: SeatMapClient = {
    getSeatMap: async () => {
      calls++;
      throw new Error("503 from seat map");
    },
  };
  const rows = ["a", "b", "c", "d", "e"].map((id) => `${id},Show ${id},2027-03-14,1200\n`);

  const report = await importShows(Readable.from([HEADER, ...rows]), testDeps(down));

  assert.deepEqual(report, { imported: 0, skipped: 5 });
  assert.equal(calls, 9); // shows a, b and c: 3 attempts each; d and e: none
});

test("the breaker lets one call through after the cooldown", async () => {
  let now = 0;
  const breaker = new CircuitBreaker({ failureThreshold: 2, openMs: 60_000, now: () => now });
  const fail = async () => { throw new Error("down"); };

  await assert.rejects(breaker.call(fail));
  await assert.rejects(breaker.call(fail));
  assert.equal(breaker.state, "open");
  await assert.rejects(breaker.call(async () => "not called"), /circuit open/);

  now = 60_000; // one minute later, on the fake clock
  assert.equal(breaker.state, "halfOpen");
  assert.equal(await breaker.call(async () => "ok"), "ok");
  assert.equal(breaker.state, "closed");
});

The test controls everything the import depends on. Readable.from from node:stream turns an array of strings into a stream, so no file is needed. The first test splits the word “summer” across two chunks.

sleep records the wait and returns at once. timeout returns a signal that never fires, or one that has already fired (AbortSignal.abort()), so the timeout test needs no real two seconds. The breaker gets a clock, now, that the test sets by hand.

Against today’s code, npx tsc --noEmit -p . reports that ./circuit-breaker.ts cannot be found. npx tsx --test import-shows.test.ts reports ℹ fail 1. Your goal is to make the test pass, keep tsc clean, and keep the output of run-import.ts the same.

Pause and predict: this challenge has five requests and three different problems. Group the requests by problem before you open a hint. Which pattern from Modules 7, 8 and 9 answers each group?

Hint 1

The change map has three groups. Request 1 touches readFile and the split, so it is about how data flows. Request 2 touches the insert and update calls, so it is about which writes belong together. Requests 3 and 4 touch the seat-map loop, so they are about a remote call that is slow or down.

Request 5 touches every new, every wait and the file path, so each of them must become a parameter.

Hint 2

Take the input as AsyncIterable<string>, which is anything you can read with for await. A file stream opened with { encoding: "utf8" } is one, and so is Readable.from([...]).

Pass it through pipeline from node:stream/promises, with two async generator functions, splitLines and parseShows, and a last step that saves. A line can start in one chunk and end in the next. So splitLines keeps the unfinished end of each chunk for the next one.

Hint 3

Write a ShowRepository with findById and save. Then write a UnitOfWork with one method, withTransaction(work), in the function form from Module 7. It hands work a tx object that holds the repository. It keeps every save aside, and copies them into the table only if work finishes without throwing.

For the seat map, wrap each call in three layers. From the inside out, they are a fresh timeout signal for each attempt, retry with growing waits (Module 9), and a CircuitBreaker around the whole retried call. Catch what comes out of the breaker, log it and skip the show.

Solution

show-store.ts holds the Repository, the Unit of Work and an in-memory fake of both.

export type ShowRecord = { id: string; title: string; date: string; priceCents: number; seatCount: number };

// Repository: a collection of shows; callers never see insert or update
export interface ShowRepository {
  findById(id: string): Promise<ShowRecord | undefined>;
  save(show: ShowRecord): Promise<void>;
}

// Unit of Work, in the function form from Module 7: every save inside
// withTransaction() is committed together, or not at all
export interface UnitOfWork {
  withTransaction<T>(work: (tx: { shows: ShowRepository }) => Promise<T>): Promise<T>;
}

// In-memory fake of both; a real one would wrap BEGIN and COMMIT in SQL
export class InMemoryShowStore implements UnitOfWork {
  readonly table = new Map<string, ShowRecord>();

  async withTransaction<T>(work: (tx: { shows: ShowRepository }) => Promise<T>): Promise<T> {
    const pending = new Map<string, ShowRecord>();
    const shows: ShowRepository = {
      findById: async (id) => pending.get(id) ?? this.table.get(id),
      save: async (show) => {
        pending.set(show.id, show);
      },
    };
    const result = await work({ shows }); // if work throws, pending is dropped: a rollback
    for (const show of pending.values()) this.table.set(show.id, show);
    return result;
  }
}

The import never says “insert” or “update”, because save decides. A real version would run BEGIN before work and COMMIT after it in SQL, and ROLLBACK if work throws. csv.ts holds the two stream steps.

export type Show = { id: string; title: string; date: string; priceCents: number };

// Chunks of text in, one line at a time out; a line may span two chunks
export async function* splitLines(chunks: AsyncIterable<string>): AsyncGenerator<string> {
  let rest = "";
  for await (const chunk of chunks) {
    const lines = (rest + chunk).split(/\r?\n/);
    rest = lines.pop() ?? "";
    yield* lines;
  }
  if (rest !== "") yield rest;
}

export async function* parseShows(lines: AsyncIterable<string>): AsyncGenerator<Show> {
  let lineNo = 0;
  for await (const line of lines) {
    lineNo++;
    if (lineNo === 1) {
      if (line !== "id,title,date,priceCents") throw new Error(`unexpected header: ${line}`);
      continue;
    }
    if (line.trim() === "") continue;
    const [id, title, date, price] = line.split(",");
    const priceCents = Number(price);
    if (!id || !title || !date || !/^\d{4}-\d{2}-\d{2}$/.test(date)
      || !Number.isInteger(priceCents) || priceCents < 0) {
      throw new Error(`bad line ${lineNo}: ${line}`);
    }
    yield { id, title, date, priceCents };
  }
}

An async function* is an async generator (Module 8). It hands out values one at a time with yield, and yield* hands out every value of a list. Each generator reads from the step before it with for await. retry.ts is the generic retry from Module 9 in short form.

export type Sleep = (ms: number) => Promise<void>;
export type RetryOptions = { attempts: number; baseMs: number; sleep: Sleep };

// Retry with backoff: waits baseMs, then 2 x baseMs, then 4 x baseMs ...
export async function retry<T>(work: () => Promise<T>, options: RetryOptions): Promise<T> {
  for (let attempt = 1; ; attempt++) {
    try {
      return await work();
    } catch (err: unknown) {
      if (attempt >= options.attempts) throw err;
      await options.sleep(options.baseMs * 2 ** (attempt - 1));
    }
  }
}

2 ** n is 2 to the power n, so the waits are 500 ms, then 1,000 ms. circuit-breaker.ts keeps state, so it is a class.

export type BreakerOptions = { failureThreshold: number; openMs: number; now: () => number };

// Circuit Breaker: after `failureThreshold` failures in a row, fail at once for
// `openMs`; then let calls through again to test the service
export class CircuitBreaker {
  #options: BreakerOptions;
  #failures = 0;
  #openedAt: number | undefined;

  constructor(options: BreakerOptions) {
    this.#options = options;
  }

  get state(): "closed" | "open" | "halfOpen" {
    if (this.#openedAt === undefined) return "closed";
    const waited = this.#options.now() - this.#openedAt;
    return waited >= this.#options.openMs ? "halfOpen" : "open";
  }

  async call<T>(work: () => Promise<T>): Promise<T> {
    if (this.state === "open") throw new Error("circuit open");
    try {
      const result = await work();
      this.#failures = 0;
      this.#openedAt = undefined;
      return result;
    } catch (err: unknown) {
      this.#failures++;
      if (this.state === "halfOpen" || this.#failures >= this.#options.failureThreshold) {
        this.#openedAt = this.#options.now();
      }
      throw err;
    }
  }
}

The breaker has three states.

  • Closed: calls go through.
  • Open: calls fail at once, without calling.
  • Half-open: the cooldown has passed, so the next call goes through to test the service. Success closes the breaker, and failure opens it again.

import-shows.ts puts the pieces together.

import { pipeline } from "node:stream/promises";
import type { CircuitBreaker } from "./circuit-breaker.ts";
import { parseShows, splitLines, type Show } from "./csv.ts";
import { retry, type Sleep } from "./retry.ts";
import type { UnitOfWork } from "./show-store.ts";

export interface SeatMapClient {
  getSeatMap(showId: string, signal: AbortSignal): Promise<string[]>;
}
export type ImportDeps = {
  store: UnitOfWork;
  seatMap: SeatMapClient;
  breaker: CircuitBreaker;
  sleep: Sleep;
  timeout: (ms: number) => AbortSignal; // AbortSignal.timeout in production
  log: (line: string) => void;
};

async function countSeats(id: string, deps: ImportDeps): Promise<number | undefined> {
  const attempt = () => deps.seatMap.getSeatMap(id, deps.timeout(2000)); // Timeout
  const retried = () => retry(attempt, { attempts: 3, baseMs: 500, sleep: deps.sleep });
  try {
    const seats = await deps.breaker.call(retried);
    return seats.length;
  } catch (err: unknown) {
    deps.log(`[log] skipped ${id}: ${String(err)}`); // tomorrow's import tries again
    return undefined;
  }
}

export type ImportReport = { imported: number; skipped: number };

export async function importShows(source: AsyncIterable<string>, deps: ImportDeps): Promise<ImportReport> {
  return deps.store.withTransaction(async (tx) => {
    const report: ImportReport = { imported: 0, skipped: 0 };
    await pipeline(source, splitLines, parseShows, async (rows: AsyncIterable<Show>) => {
      for await (const show of rows) {
        const seatCount = await countSeats(show.id, deps);
        if (seatCount === undefined) report.skipped++;
        else {
          await tx.shows.save({ ...show, seatCount });
          report.imported++;
        }
      }
    });
    deps.log(`[log] imported ${report.imported} shows`);
    return report;
  });
}

SeatMapClient is the course’s shared seat-map interface. The fake SeatMapHttpClient, the name Modules 2 and 3 used, fits it, because its optional signal accepts the signal the interface passes. run-import.ts is the composition root.

import { createReadStream } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import { CircuitBreaker } from "./circuit-breaker.ts";
import { importShows } from "./import-shows.ts";
import { SeatMapHttpClient } from "./seat-map-fake.ts";
import { InMemoryShowStore } from "./show-store.ts";

// Composition root for the nightly import
const store = new InMemoryShowStore();
await importShows(createReadStream("shows.csv", { encoding: "utf8" }), {
  store,
  seatMap: new SeatMapHttpClient(),
  breaker: new CircuitBreaker({ failureThreshold: 3, openMs: 60_000, now: Date.now }),
  sleep: (ms) => sleep(ms),
  timeout: (ms) => AbortSignal.timeout(ms),
  log: (line) => console.log(line),
});
for (const show of store.table.values()) {
  console.log(`[db] ${show.id} | ${show.title} | ${show.date} | ${show.priceCents} | ${show.seatCount} seats`);
}

The output of npx tsx run-import.ts is the same five lines as before, and a diff prints nothing. npx tsx --test import-shows.test.ts ends with ℹ pass 5 and ℹ fail 0.

Figure 7 shows the new structure. Everything the import needs arrives through ImportDeps.

[run-import.ts] ==> [InMemoryShowStore] NEW ..> [UnitOfWork] (I)
[run-import.ts] ==> [CircuitBreaker] NEW, [SeatMapHttpClient]
[run-import.ts] --> [importShows]
[importShows] --> [UnitOfWork] (I) --> [ShowRepository] (I) NEW
[importShows] --> [pipeline] --> [splitLines], [parseShows] NEW
[importShows] --> [countSeats] --> [CircuitBreaker] --> [retry] NEW
[retry] --> [SeatMapClient] (I)     with a new timeout signal each time

Figure 7: the import calls interfaces and receives every resource; run-import.ts creates them.

When parseShows throws on a bad row, pipeline closes the file and rejects with that error. So withTransaction never copies the pending saves, and the table stays as it was.

Figure 8 follows one seat-map call for “summer” on a bad night. The first attempt gets no answer, and the second succeeds.

1  [countSeats] --> [CircuitBreaker]   call(retried); state is closed
2  [CircuitBreaker] --> [retry]        attempt 1 of 3
3  [retry] --> [SeatMapClient]         getSeatMap("summer", 2 s signal)
     ~ await: no answer; the signal fires after 2 s ~
4  [retry]                             the call rejects; sleep(500)
     ~ await ~
5  [retry] --> [SeatMapClient]         attempt 2, with a new 2 s signal
     ~ await: 200 seats arrive ~
6  [CircuitBreaker]                    success: failure count back to 0
7  [countSeats] returns 200            the save step saves "summer"

Figure 8: the timeout limits one attempt, retry limits one show, and the breaker limits the whole night.

With the breaker inside the retry, the three attempts for one slow show could open it. Outside, one show counts as one failure only after all its attempts.

Rule: Put the circuit breaker outside the retry, so it counts failed shows, not failed attempts.

What this solution does not change, and why.

  • The whole file is one unit of work. With a real database, one transaction of two million rows holds locks and log space for a long time. Committing every 1,000 rows is the usual next step, but it gives up “all or nothing”, so Leo has to choose.
  • The seat-map calls stay one at a time. Calling for several shows at once, with a limit, would be faster. That limit is the Bulkhead idea from Module 9, and no request asked for speed.
  • The CSV is split on commas. A title with a comma inside quotes, such as "Songs, Spring", would break a row. A CSV parsing library is the fix on the day an organizer sends one.

The pairs people confuse

Some patterns have the same boxes and arrows and differ in one place. Each pair below has a figure with the same layout on both sides.

Strategy and State

Both patterns give an object an interface with several implementations behind it. In Strategy, the caller picks the implementation from outside, and it stays for the whole call. placeOrder picks WalletProvider because the request said "wallet".

In State, the object changes its own implementation as its situation changes. An order that is paid behaves like a paid order until it is refunded. Figure 9 shows the two with the same layout.

Strategy (Module 4)                   State (Module 4)
+------------------------------+      +------------------------------+
| [placeOrder]                 |      | [Order]                      |
|   --> [PaymentProvider] (I)  |      |   --> [OrderState] (I)       |
| [CardProvider] ..> it        |      | [PendingState] ..> it        |
| [WalletProvider] ..> it      |      | [PaidState] ..> it           |
+------------------------------+      +------------------------------+
Who picks the implementation?         Who picks the implementation?
* the caller, once, from input *      * the object itself, after each
                                        step (pending -> paid) *

Figure 9: Strategy is chosen from outside; State changes from inside.

Signal for State: a switch on order.status appears in several methods, and each method has its own list of allowed statuses.

Adapter, Facade, Decorator and Proxy

All four put a wrapper between the caller and something else. They differ in two things. One is whether the caller sees the same shape as the wrapped object, and the other is what the wrapper adds. Figure 10 lists all four on the same layout.

            caller sees         wraps               the wrapper adds
Adapter     [PaymentProvider]   [WalletSdk]         a different shape *
Facade      [buyTickets()]      price, pay, save    one door to many *
Decorator   [Send]              [Send]              behavior: retry, log
Proxy       [SeatMapClient]     [SeatMapClient]     control: cache, lazy

* the caller sees a different shape from the wrapped object

Figure 10: Adapter and Facade change the shape; Decorator and Proxy keep it, and add behavior or control access.

  • Adapter turns one object’s shape into the shape you need, like WalletProvider in Challenge 1.
  • Facade gives several objects one simple entry point, such as a buyTickets() function over pricing, payment and orders.
  • Decorator keeps the shape and adds behavior, like withRetry in Challenge 2.
  • Proxy keeps the shape and controls access to the real object. It can cache seat maps, create the client only on first use, or check permissions.

Module 3 shows when a plain wrapper is clearer than JavaScript’s built-in Proxy object.

Observer and Publish/Subscribe

Both let one part announce something and many parts react. In Observer, the listeners register on the object that emits, as events.on("order:paid", ...) did in Challenge 2. The emitter holds the list and calls each listener, in the same process.

In Publish/Subscribe, publishers and subscribers know only a channel name. A broker sits between them. It is a program that receives each message and passes it to the subscribers, often in another process. In Redis, for example, subscribers do not know which publishers exist, as the Redis Pub/Sub docs describe.

Observer (Module 5)                  Publish/Subscribe (Module 5)
[completeOrder] --> [events]         [checkout] --> [broker: "orders"]
[events] --> [listener 1]            [broker] --> [subscriber 1]
[events] --> [listener 2]            [broker] --> [subscriber 2]

Listeners hold a reference to        * Neither side holds a reference
the emitter and register on it.        to the other; both know only
Same process, called at once.          a channel name. *

Figure 11: in Observer the listeners know the emitter; in Publish/Subscribe both sides know only a channel.

Signal for Publish/Subscribe: the listener runs in another process or on another server, or it must keep working while the sender is down.

Middleware and Chain of Responsibility

Both pass a request along a chain of handlers. In Chain of Responsibility, as the 1994 Design Patterns book describes it, each handler decides whether the request is its job. The first one that takes it handles it, and the chain usually stops there.

Picture refund requests. A refund under 2,000 cents is approved automatically, a larger one goes to Leo, and a disputed one goes to Maya.

In Express middleware, each function does its part and calls next(), so most requests pass through every step. Any step can still end the request early, as the Express guide to middleware shows.

Middleware (Module 5)                Chain of Responsibility (Module 5)
[json] --> [auth] --> [route]        [autoRefund] --> [leo] --> [maya]

Each step does its part and          Each step asks "is this mine?"
calls next().                        The first that says yes handles
* Most requests pass every step. *   it. * The chain stops there. *

Figure 12: middleware runs a series of steps; a chain looks for the one handler that takes the request.

Express middleware is a variant of Chain of Responsibility, so you will see both names used for it. When you write one, decide whether every step should run, or only the right one.

Repository and Unit of Work

Both sit between your code and the database, and Challenge 3 used them together. A Repository looks like a collection of one kind of object, with methods such as findById and save, and hides the SQL. A Unit of Work keeps track of the writes that belong to one business operation, and commits them together.

A Unit of Work often spans several repositories, as Martin Fowler’s catalog describes.

Repository (Module 7)                Unit of Work (Module 7)
[importShows] --> [ShowRepository]   [importShows] --> [UnitOfWork] (I)
  (I): findById(id), save(show)        withTransaction(work)

* answers "where are the shows,      * answers "which writes belong
  and how do I get one?" *             together?" *
One kind of object.                  Any number of repositories.

Figure 13: a Repository hides where one kind of data lives; a Unit of Work decides which writes succeed or fail together.

Signal for Unit of Work: a business operation saves two or more things, and a failure halfway through leaves data that no one can explain.

Overuse: five signs a pattern is making code worse

Module 1 told the story of six files for one email service. These five signs help you catch the same problem in a code review. Each one says what it looks like in code, and the simpler code to go back to.

  1. An interface with one implementation and no fake. You see interface PaymentGateway and one class CardGateway implements PaymentGateway, and no test passes in another object. Delete the interface and use the class. Add the interface back on the day a second implementation or a test fake needs it.
  2. A factory or registry that only ever makes one thing. You see NotifierFactory.create("email"), and "email" is the only case. Call the constructor in the composition root. A factory earns its place when the caller must not know which class it gets.
  3. You cannot follow the call. “Go to definition” lands on an interface, then on a factory, then on a config file. The stack trace is a column of anonymous arrow functions. A common case is an EventEmitter used where the sender needs an answer, such as an emit of "price:requested" that waits for a "price:answered" event. Call a function and await its result instead, and give wrappers names so stack traces stay readable.
  4. The change still spreads. The code has a Strategy for every payment provider, but each change request adds a field to the order. That field crosses all five provider classes. Go back to step 2 of the method, map the changes that really came, and arrange the code around them.
  5. Ceremony where a function would do. You see a class with one method and no fields, a getInstance() method, or AbstractBaseSomething with one subclass. In TypeScript these are usually a function, an exported const or a plain object. Module 1 showed each of these shorter forms.

So a pattern is wrong when it costs more than the changes it absorbs. Add one when a real change request touches the same code twice, or when you cannot test the code.

Check yourself

  1. Name the six steps of the method in order.
  2. In Challenge 1, which class is the Adapter, and what two things does it convert?
  3. In Challenge 3, why does the circuit breaker sit outside the retry, and not inside it?
  4. A refund request goes to the first handler that accepts it, and the others never see it. Is that middleware or Chain of Responsibility?
  5. Your team’s code has interface ShowImporter with one class, CsvShowImporter, and no test uses another object. Which sign of overuse is this, and what would you do?
Answers
  1. List what is likely to change. Map each change to the code it touches. Pin today’s behavior. Pick the simplest fix. Add a pattern only where a change would otherwise spread. Write down what you chose not to change, and why.
  2. WalletProvider. It converts cents to a dollar string on the way in, and the wallet’s { approved, ref, message } answer to a PaymentResult on the way out.
  3. Outside, one show counts as one failure only after all its attempts. Inside, every attempt counts, so a single slow show could open the breaker after three attempts.
  4. Chain of Responsibility. The first handler that takes the request handles it, and the chain stops.
  5. Sign 1, an interface with one implementation and no fake. Use the class directly, and add the interface back when a second importer or a test fake needs it.

Going deeper

You can skip this section. It covers two retry details the solutions left out, and how a file stream behaves underneath.

Two retry details the solutions skipped

charge in Challenge 1 has no retry, because charging a card twice is worse than failing once. A safe retry needs an idempotency key, a value that lets the provider spot a repeated request. Module 9 covers it.

The retries in Challenges 2 and 3 have no jitter, a small random change to each wait. Jitter matters when many clients retry the same service at the same moment (Module 9). Here one process sends a few messages, and one nightly job is the only caller of the seat map.

How a file stream and pipeline behave

A file stream reads 64 KiB at a time by default, as the fs.createReadStream docs say. With an encoding set, it hands out strings and does not cut a character in half. When a step throws, pipeline destroys the streams and rejects with that error, as the pipeline docs describe.

Course cheat sheet

Every pattern in the course, one line each. The third column repeats the course’s main question, what the pattern lets you change without touching the rest.

Pattern Module Lets you change … without touching … Signal in your code
Factory function, Factory Method 2 which class is created, without touching its callers new with settings, copied in many places
Builder 2 the parts of a complex object, without one huge constructor constructors with many optional arguments
Singleton (module caching) 2 nothing; it gives one shared instance per process getInstance(); in Node.js, an exported const
Adapter 3 a third-party shape, without touching your code SDK shapes leaking into business logic
Facade 3 a group of objects behind one simple entry point every caller repeats the same five calls
Decorator 3 behavior around a call (retry, log), without touching the call the same loop copied around many calls
Proxy, JavaScript Proxy 3 access to an object (cache, lazy, checks), with the same shape every caller checks the cache first
Strategy 4 which algorithm runs, without touching the caller an if chain over kinds that keeps growing
State 4 behavior per state, without a switch in every method switch (status) in many methods
Command 4 when and how a request runs: queue, undo, log a request that must be stored or replayed
Observer, EventEmitter 5 who reacts, without touching the code that announces a function calling every interested module
Chain of Responsibility 5 who handles a request, without the sender knowing an if chain choosing a handler
Middleware (Express, Koa) 5 the steps around every request auth or logging copied into every route
Publish/Subscribe 5 who listens, across processes, through a broker listeners that live in another service
Dependency Injection, composition root 6 which implementation is used, without touching the user new deep inside business logic
Inversion of Control, containers 6 who calls whom: the framework calls your code many classes wired by hand, in a framework
Repository 7 how data is stored, without touching business code SQL inside route handlers
Unit of Work 7 which writes succeed or fail together several saves with no transaction
Iterator, async iterators 8 how items are produced, without touching the loop arrays built only to loop over once
Readable and Transform streams 8 data size, without holding it all in memory readFile on files that keep growing
pipeline and backpressure 8 step order and error handling of a stream chain .pipe() chains with no error handling
Timeout 9 how long you wait, without touching the call a remote call with no AbortSignal
Retry with backoff and jitter 9 how failures are retried, without touching the call a hand-written retry loop with fixed waits
Circuit Breaker 9 when to stop calling a failing service every request waits for a service that is down
No pattern 1 nothing to protect; the change happens once one place to change, and it is easy to test

The modules also name some patterns in short, which this table leaves out. They are Abstract Factory, Prototype, Composite, Template Method, Mediator, Data Mapper and Active Record, Pipes and Filters, Bulkhead and Fallback.

Figure 14 is the decision figure for the whole course. It extends Module 1’s Figure 10. The first three exits are the same, and then it asks what keeps changing.

A change request arrives
  |
  v
Touches one place, and it is easy to test? -- yes --> No pattern needed.
  | no
  v
Will the same kind of change come again? --- no --> Edit it; leave a note.
  | yes
  v
Can a function, an object map or a union absorb it? -- yes --> Use that.
  | no
  v
What keeps changing?
  how and which objects are created ..... Factory, Builder                (2)
  a shape you cannot edit, or too many .. Adapter, Facade                 (3)
  extra behavior around a call .......... Decorator, Proxy                (3)
  which algorithm, or which state ....... Strategy, State                 (4)
  who reacts, or which steps run ........ Observer, Middleware            (5)
  where dependencies come from .......... Dependency Injection,           (6)
                                          composition root
  storage, or writes that go together ... Repository, Unit of Work        (7)
  data too big for memory ............... streams, pipeline               (8)
  a remote call that is slow or fails ... Timeout, Retry, Circuit Breaker (9)

Figure 14: three exits come before any pattern, and then the thing that keeps changing names the module to read.

  • Method: list, map, pin, pick, add a pattern only where a change would otherwise spread, and write down what you left alone.
  • Change map: one row per change request, with the code it touches today. One change that touches many places is the signal.
  • Cost: every pattern adds files and steps between a call and the code that runs. It pays only when it absorbs a change that really comes.
  • Look-alikes: Strategy is picked from outside and State changes from inside. Adapter and Facade change the shape, and Decorator and Proxy keep it.
  • Overuse: an interface with one implementation, a factory with one product, calls you cannot follow, changes that still spread, ceremony where a function would do.
  • Next: take one file you changed three times last month, write its change map from git log, and stop at the first step that solves the problem. To model a whole app around its business rules, try Domain-Driven Design in TypeScript.

Sources