Leo asked for refunds. When an organizer refunds an order, the seats should go back on sale and the buyer should get an email. Maya searched the project for the order:paid event to copy the code that reacts to it, and she found that code in four files.
One file sent the event as order:payed, so Ben, a buyer, never got his receipt. The same week, an order with no email address crashed the server in the middle of a sale.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
Module 1 named the problem of events with no clear owner. This module gives events a typed list of names and one place that connects every reaction to its event. Then it turns to chains, where a request passes through a line of small functions and any one of them can stop it.
After this module, you can:
- give Node.js events a typed list of names, register every reaction in one file, and keep a failing async reaction from crashing the process
- turn a growing
ifchain of order checks into a list of small checks, any of which can stop the order - write Express 5 and Koa middleware, and say where an error goes in each
- tell Observer from Publish/Subscribe and a chain from middleware, and say when a direct function call is enough
Set up the folder for this module
Use the folder from Module 1, or make a new one the same way. Copy fakes.ts from Module 1. As there, the clients in it are fakes that print a line instead of calling a real service. Save types.ts, the shared TinyTickets types file that Module 3 started, with the types this module needs:
// Shared TinyTickets types for this module
export type ShowId = string;
export type OrderStatus = "pending" | "paid" | "cancelled" | "refunded";
export interface Order {
id: string;
showId: ShowId;
buyerEmail: string;
quantity: number;
totalCents: number;
status: OrderStatus;
}
export interface OrderRepository {
findById(id: string): Promise<Order | undefined>;
save(order: Order): Promise<void>;
}
export type Send = (to: string, text: string) => Promise<void>;
An OrderRepository is an object that loads and saves orders. Module 7 teaches it in full, and here you only need its shape.
Observer and EventEmitter: one place that registers the listeners
Three orders and two bugs
Here is the event code that Maya found, gathered into one file, bus-before.ts. It’s the shared bus from Module 1, now with an async function that sends the receipt email. The comments name the files the code came from:
import { EventEmitter } from "node:events";
import { MailClient } from "./fakes.ts";
import type { Order } from "./types.ts";
// bus.ts: one shared emitter that every file imports
const bus = new EventEmitter();
const mail = new MailClient("localhost");
// email.ts: an async listener
bus.on("order:paid", async (order: Order) => {
if (order.buyerEmail === "") throw new Error(`order ${order.id} has no email`);
await mail.send(order.buyerEmail, `Receipt for order ${order.id}`);
});
// seats.ts: a listener that emits a second event
bus.on("order:paid", (order: Order) => bus.emit("seats:changed", order.showId));
// seatmap.ts: a third file listens for the second event
bus.on("seats:changed", (showId: string) => console.log(`[seats] refresh map for ${showId}`));
// checkout.ts: three paid orders
const paid = (id: string, buyerEmail: string): Order =>
({ id, showId: "spring", buyerEmail, quantity: 2, totalCents: 2550, status: "paid" });
bus.emit("order:paid", paid("o-1", "ana@example.com"));
bus.emit("order:payed", paid("o-2", "ben@example.com")); // a typo
bus.emit("order:paid", paid("o-3", "")); // an imported order with no email
console.log("checkout finished");
The bus is an EventEmitter from node:events. Its on method adds a listener, a function that runs when an event with that name happens. Its emit method sends an event, which calls the listeners for that name.
Before you run it, predict the output. Which orders get a receipt line, and does the script print “checkout finished”? Then run it with npx tsx bus-before.ts. Here is the output, with the file paths shortened:
[mail] to ana@example.com: Receipt for order o-1
[seats] refresh map for spring
[seats] refresh map for spring
checkout finished
bus-before.ts:11
if (order.buyerEmail === "") throw new Error(`order ${order.id} has no email`);
^
Error: order o-3 has no email
at EventEmitter.<anonymous> (bus-before.ts:11:38)
at EventEmitter.emit (node:events:526:24)
(four more stack lines cut)
Node.js v24.22.1
Two things went wrong. Ben’s order o-2 was sent as order:payed, so no listener ran, and nothing reported the typo. Order o-3 made the async listener throw.
emit doesn’t wait for an async listener, so nothing caught its rejected promise. A rejected promise that nothing catches is an unhandled rejection. Node.js treats it as an uncaught exception and stops the process by default, as the Node.js command-line docs describe. In a server, that crash ends every request that is still running, not only the bad one.
Leo’s refund request adds a new event, order:refunded, with its own listeners. In this code, that means a new string in a fifth file. It’s one more chance for a typo, and one more async listener that can crash the process.
Pause and predict: you want three things.
- A misspelled event name fails in the TypeScript compiler,
tsc, not at run time.- One file shows every listener.
- A failing listener is logged and doesn’t crash the server.
Which of these can TypeScript give you, and which need code that runs?
The idea: a sign-up sheet at the box office
Observer is a behavioral pattern from the GoF book (Module 1). One object, the subject, keeps a list of listeners and calls each of them when something happens. The subject doesn’t know what the listeners do. In Node.js the subject is an EventEmitter.
Think of a sign-up sheet at the box office that says “call me when Summer Lights goes on sale”. The clerk doesn’t know why each person signed up. When sales open, the clerk calls every number on the sheet, in order. Figure 1 puts the analogy next to the code, with the legend used in every module.
Box office Node.js
(Clerk) [events: EventEmitter]
sheet: "Summer Lights on sale" listeners for "order:paid"
sales open: clerk calls each one emit("order:paid", order)
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: the emitter, like the clerk, calls everyone on the list and doesn’t know why they signed up.
The analogy stops fitting when a call fails, because a clerk hears the failure. emit calls each listener at once, in the order they were added, as the Node.js events docs say. But it doesn’t wait for an async listener’s promise, so it never sees that promise reject.
Node.js uses Observer itself. http.Server is an EventEmitter, and every incoming request arrives as its 'request' event. A plain callback is different, because it’s one function passed to one caller, while a subject keeps a list of many.
What it lets you change without touching the rest: who reacts to an event, while the code that emits it stays the same.
A typed list of event names
The fix has three parts. First, one type lists every event name and the arguments it carries. Save order-events.ts:
import { EventEmitter } from "node:events";
import type { Order, ShowId } from "./types.ts";
// Every event name, and the arguments it carries
export type OrderEvents = {
"order:paid": [order: Order];
"seats:changed": [showId: ShowId];
};
// The emitter, 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;
off<K extends keyof OrderEvents>(name: K, listener: (...args: OrderEvents[K]) => void): unknown;
emit<K extends keyof OrderEvents>(name: K, ...args: OrderEvents[K]): boolean;
listenerCount(name: keyof OrderEvents): number;
}
// A plain EventEmitter fits OrderEmitter; the interface does the checking
export function createOrderEvents(): OrderEmitter {
return new EventEmitter();
}
keyof OrderEvents is the union of the map’s keys, "order:paid" | "seats:changed". In on<K extends keyof OrderEvents>, K is a generic (Module 1) that must be one of those keys. OrderEvents[K] is the argument list stored under the key K. So emit("order:paid", ...) must pass one Order, and emit("order:payed", ...) doesn’t compile.
createOrderEvents returns a plain EventEmitter. It fits OrderEmitter because of structural typing (Module 1), which checks an object’s shape, not its class. Every caller sees only the narrow interface.
One file that registers every listener
Second, the listener code moves into functions that don’t know about the emitter. Save listeners.ts:
import type { Order, Send } from "./types.ts";
// Listener code knows nothing about the emitter
export async function sendReceipt(send: Send, order: Order): Promise<void> {
if (order.buyerEmail === "") throw new Error(`order ${order.id} has no email`);
await send(order.buyerEmail, `Receipt for order ${order.id}`);
}
Third, one function registers every listener, in order. Save wire-listeners.ts:
import type { OrderEmitter } from "./order-events.ts";
import { sendReceipt } from "./listeners.ts";
import type { Send, ShowId } from "./types.ts";
export type ListenerDeps = {
sendEmail: Send;
refreshSeatMap: (showId: ShowId) => Promise<void>;
log: (line: string) => void;
};
// The one place that says who reacts to which event, in order
export function wireListeners(events: OrderEmitter, deps: ListenerDeps): void {
// Run an async listener; log its failure instead of crashing the process
const logErrors = <A extends unknown[]>(name: string, listener: (...args: A) => Promise<void>) =>
(...args: A): void => {
listener(...args).catch((err: unknown) => deps.log(`[log] ${name} failed: ${String(err)}`));
};
events.on("order:paid", logErrors("sendReceipt", (order) => sendReceipt(deps.sendEmail, order)));
events.on("order:paid", (order) => events.emit("seats:changed", order.showId));
events.on("seats:changed", logErrors("refreshSeatMap", deps.refreshSeatMap));
}
logErrors takes an async listener and returns a plain listener that starts it and attaches .catch. So a failure becomes a log line, and the process keeps running. A extends unknown[] lets the wrapper keep the argument types of the listener it wraps. The services the listeners need, such as the mail sender, arrive in deps, so no listener creates its own client.
Now the entry file creates everything and registers the listeners once. Save checkout-after.ts:
import { MailClient } from "./fakes.ts";
import { createOrderEvents } from "./order-events.ts";
import { wireListeners } from "./wire-listeners.ts";
import type { Order } from "./types.ts";
// main: create the emitter and the clients, then wire once
const events = createOrderEvents();
const mail = new MailClient("localhost");
wireListeners(events, {
sendEmail: (to, text) => mail.send(to, text),
refreshSeatMap: async (showId) => console.log(`[seats] refresh map for ${showId}`),
log: (line) => console.log(line),
});
// checkout.ts: three paid orders
const paid = (id: string, buyerEmail: string): Order =>
({ id, showId: "spring", buyerEmail, quantity: 2, totalCents: 2550, status: "paid" });
events.emit("order:paid", paid("o-1", "ana@example.com"));
events.emit("order:paid", paid("o-2", "ben@example.com"));
events.emit("order:paid", paid("o-3", ""));
console.log("checkout finished");
Here is the output of npx tsx checkout-after.ts:
[mail] to ana@example.com: Receipt for order o-1
[seats] refresh map for spring
[mail] to ben@example.com: Receipt for order o-2
[seats] refresh map for spring
[seats] refresh map for spring
checkout finished
[log] sendReceipt failed: Error: order o-3 has no email
For Ana’s order, the lines are the same as before. Ben now gets his receipt, and order o-3 is a log line instead of a crash. The log line comes after “checkout finished” because the rejection arrives after emit has returned. If you put the old typo back, npx tsc --noEmit stops it:
error TS2345: Argument of type '"order:payed"' is not assignable to parameter of type 'keyof OrderEvents'.
Figure 2 shows the structure before and after. The listeners used to register themselves when their file was imported. Now one function registers them all.
Before: four files add listeners; names are any string
[checkout.ts] --> [bus] emit
[email.ts] --> [bus] on
[seats.ts] --> [bus] on, emit
[seatmap.ts] --> [bus] on
After: one file adds every listener; names are keyof OrderEvents
[checkout-after.ts] ==> [events]
[events] ..> [OrderEmitter] (I) NEW
[checkout-after.ts] --> [wireListeners] NEW
[wireListeners] --> [events] on, in order
[wireListeners] --> [sendReceipt]
Figure 2: four files that each added listeners become one wiring function and a typed list of names.
Figure 3 follows Ana’s order through the emitter. The waiting happens inside the listener, never inside emit.
1 [checkout-after.ts] --> [events] emit("order:paid", o-1)
2 [events] --> [logErrors wrapper] starts sendReceipt(o-1)
3 [sendReceipt] --> [sendEmail] receipt to ana@example.com
~ await: sendReceipt waits; emit goes on to the next listener ~
4 [events] --> [listener 2] emit("seats:changed", "spring")
5 [events] --> [logErrors wrapper] starts refreshSeatMap("spring")
6 [events] returns to checkout emit returns true
7 later: sendEmail answers, or logErrors writes "[log] ... failed"
Figure 3: emit runs every listener in order and returns; async work finishes later, outside the caller’s view.
Rule:
emitcalls every listener and returns without waiting, so every async listener needs its own.catch.
Prove it with a test
The test passes fake functions in deps, sends two orders, and checks what the listeners did. Save wire-listeners.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { setImmediate } from "node:timers/promises";
import { createOrderEvents } from "./order-events.ts";
import { wireListeners } from "./wire-listeners.ts";
import type { Order } from "./types.ts";
const paid = (id: string, buyerEmail: string): Order =>
({ id, showId: "spring", buyerEmail, quantity: 2, totalCents: 2550, status: "paid" });
test("a paid order sends a receipt and refreshes the seat map", async () => {
const calls: string[] = [];
const events = createOrderEvents();
wireListeners(events, {
sendEmail: async (to, text) => { calls.push(`email ${to} | ${text}`); },
refreshSeatMap: async (showId) => { calls.push(`seats ${showId}`); },
log: (line) => calls.push(line),
});
events.emit("order:paid", paid("o-1", "ana@example.com"));
events.emit("order:paid", paid("o-3", ""));
await setImmediate(); // the fakes answer at once, so one turn of the event loop is enough
assert.deepEqual(calls, [
"email ana@example.com | Receipt for order o-1",
"seats spring",
"seats spring",
"[log] sendReceipt failed: Error: order o-3 has no email",
]);
});
setImmediate from node:timers/promises returns a promise that settles after the callbacks already waiting in Node.js have run, as the Node.js timers docs describe. By then the fakes have finished and the .catch has logged. Run it with npx tsx --test wire-listeners.test.ts:
✔ a paid order sends a receipt and refreshes the seat map (2.84225ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
The “before” code couldn’t be tested this way. Its listeners created their own MailClient and joined the bus when their file was imported. So a test would need the real client, or a tool that swaps imports for fakes.
The next change: refunds free the seats
Now Leo’s request. When an order is refunded, its seats go back on sale. Two lines change. In order-events.ts, the map gets one new entry (excerpt):
export type OrderEvents = {
"order:paid": [order: Order];
"seats:changed": [showId: ShowId];
"order:refunded": [order: Order]; // NEW
};
In wire-listeners.ts, one line goes at the end of wireListeners (excerpt):
events.on("order:refunded", (order) => events.emit("seats:changed", order.showId)); // NEW
Code that refunds an order now only sends order:refunded, and the seat map refreshes. If someone passes the wrong argument, such as events.emit("order:refunded", "o-1"), tsc reports that a string is not an Order. The lab at the end of this module adds the refund email.
Use it when, skip it when
Use Observer when:
- one action has three or more reactions, and different parts of the code own them
- reactions are added or removed more often than the action itself changes
- the reactions must not slow down or fail the action, like the receipt email after a payment
Skip it when:
- there is one reaction, or two, owned by the same code. Call
sendReceiptand thenrefreshSeatMapdirectly. The order is visible, and errors reach the caller. - the caller needs a result, or must stop if a reaction fails. An event can’t return a value to the emitter, so call a function and check its result.
The cost
You pay for Observer in reading time first. “Go to definition” on emit lands in Node.js, not in the listeners, so you need wireListeners to see who reacts. A stack trace from a listener starts at emit, and an async one often starts at nothing you wrote.
Listeners also cost memory, because the emitter keeps every listener until someone removes it. The common leak is a listener added on every request and never removed. Node.js prints a warning when one event has more than 10 listeners, as the events docs describe. “Going deeper” at the end of this module shows that leak and how to avoid it.
Exercise: count the sales
Leo wants a log line for every sale: [log] sale o-1: 2 tickets. Add it with one line, and say which file changes and where the line appears in the test’s calls array.
Answer
Only wire-listeners.ts changes. Add a sync listener as the last line of wireListeners:
events.on("order:paid", (order) => deps.log(`[log] sale ${order.id}: ${order.quantity} tickets`));
It needs no logErrors, because it isn’t async. Listeners run in the order they were added, so for order o-1 the test’s calls array becomes email ..., seats spring, [log] sale o-1: 2 tickets. The test’s expected array must add that line. No other file changes, and checkout-after.ts doesn’t know the counter exists.
Chain of Responsibility: checks that can stop an order
One function with a flag for every caller
Before TinyTickets takes a payment, it checks the order. Leo set four rules:
- at most 6 tickets per order
- enough seats left
- a promo code that exists
- a fraud check, which calls a slow outside service that scores the buyer’s email
Leo then asked for two changes. Organizers can add guest tickets from the admin page, and those orders skip the ticket limit and the fraud check. Summer Lights also gets a presale, so before May 1, buyers need the code FANS.
Maya did the first change with a flag. Save checks-before.ts:
type OrderRequest = { showId: string; buyerEmail: string; quantity: number; code: string | null };
const seatsLeft = new Map([["spring", 150]]);
const promoCodes = new Set(["SPRING10"]);
// The slow fraud service, faked
async function riskScore(email: string): Promise<number> {
console.log(`[risk] scoring ${email}`);
return email.endsWith("@fraud.example") ? 95 : 10;
}
// Returns why the order is refused, or null when it may go on
async function checkOrder(order: OrderRequest, fromOrganizer: boolean): Promise<string | null> {
if (!fromOrganizer && order.quantity > 6) return "at most 6 tickets per order";
const left = seatsLeft.get(order.showId) ?? 0;
if (order.quantity > left) return `only ${left} seats left`;
if (order.code !== null && !promoCodes.has(order.code)) return "unknown promo code";
if (!fromOrganizer && (await riskScore(order.buyerEmail)) > 80) return "blocked by the fraud check";
return null;
}
const buyerOrders: OrderRequest[] = [
{ showId: "spring", buyerEmail: "ana@example.com", quantity: 2, code: "SPRING10" },
{ showId: "spring", buyerEmail: "ben@example.com", quantity: 8, code: null },
{ showId: "spring", buyerEmail: "chi@example.com", quantity: 1, code: "FREE" },
{ showId: "spring", buyerEmail: "bot@fraud.example", quantity: 4, code: null },
];
for (const order of buyerOrders) {
console.log(order.buyerEmail, "->", (await checkOrder(order, false)) ?? "ok");
}
const guests: OrderRequest = { showId: "spring", buyerEmail: "guests@tinytickets.example", quantity: 8, code: null };
console.log("organizer guests ->", (await checkOrder(guests, true)) ?? "ok");
Output:
[risk] scoring ana@example.com
ana@example.com -> ok
ben@example.com -> at most 6 tickets per order
chi@example.com -> unknown promo code
[risk] scoring bot@fraud.example
bot@fraud.example -> blocked by the fraud check
organizer guests -> ok
The code works, and each line is easy to read. But the shape gets worse with each new caller. fromOrganizer is a boolean parameter, and two of the four if lines now test it. The presale would add a second flag, or a date and a code parameter, to the same function.
So every rule has to know about every caller. No rule can be tested alone, and the order of the rules is hidden in the order of the lines. This code gets one thing right, though. The slow fraud call comes last, so for Ben’s order the cheap ticket limit answered and the fraud service was never called.
Pause and predict: what changes between buyer orders, organizer orders and the presale, and what stays the same? Could each rule be a value, so that each caller picks its own list?
The idea: the staff at the venue door
Chain of Responsibility is another GoF behavioral pattern. A request passes along a line of handlers, functions or objects that each look at the request in turn. Each handler either deals with the request, which ends the chain, or passes it to the next one. Here, “dealing with” an order means refusing it with a reason, and an order that passes every handler goes on to payment.
The analogy is the staff at the door of a venue. One person scans the ticket, the next checks bags, and the last checks the buyer’s age for an 18+ show. Any of them can turn you away and say why, and if all three let you in, you’re inside. Figure 4 lines up the two.
Venue door TinyTickets
staff in a line at the door handlers in [runChecks], in order
anyone can say "no, because..." a handler returns a reason
all let you in: you are inside every handler returns null
Figure 4: each person at the door can stop you; only someone who passes them all gets in.
The analogy stops fitting when callers differ, because a venue’s staff line is the same for every guest. In code, each caller can build its own chain from the same handlers, as the fix shows.
What it lets you change without touching the rest: which checks run, and in what order, while each check and the loop that runs them stay the same.
The fix: handlers as functions, the chain as an array
Each rule becomes an OrderCheck, a function that returns a reason or null. A rule that needs data or a service gets it from a factory function (Module 2), a function that builds and returns the check. Save checks.ts:
export type OrderRequest = { showId: string; buyerEmail: string; quantity: number; code: string | null };
// One handler: a reason stops the chain, null passes the order on
export type OrderCheck = (order: OrderRequest) => Promise<string | null>;
export type RiskScore = (email: string) => Promise<number>;
export const seatLimit = (max: number): OrderCheck => async (order) =>
order.quantity > max ? `at most ${max} tickets per order` : null;
export const seatsAvailable = (seatsLeft: Map<string, number>): OrderCheck => async (order) => {
const left = seatsLeft.get(order.showId) ?? 0;
return order.quantity > left ? `only ${left} seats left` : null;
};
export const knownCode = (codes: Set<string>): OrderCheck => async (order) =>
order.code !== null && !codes.has(order.code) ? "unknown promo code" : null;
export const fraudCheck = (riskScore: RiskScore): OrderCheck => async (order) =>
(await riskScore(order.buyerEmail)) > 80 ? "blocked by the fraud check" : null;
// The chain: ask each handler in order, stop at the first reason
export async function runChecks(checks: OrderCheck[], order: OrderRequest): Promise<string | null> {
for (const check of checks) {
const reason = await check(order);
if (reason !== null) return reason;
}
return null;
}
runChecks is the chain. It asks each handler in order and returns at the first reason, so the later handlers never run. Each caller now builds its own list. Save checks-main.ts:
import { fraudCheck, knownCode, runChecks, seatLimit, seatsAvailable, type OrderCheck,
type OrderRequest, type RiskScore } from "./checks.ts";
// The slow fraud service, faked
const riskScore: RiskScore = async (email) => {
console.log(`[risk] scoring ${email}`);
return email.endsWith("@fraud.example") ? 95 : 10;
};
const seatsLeft = new Map([["spring", 150]]);
// Two chains built from the same handlers; cheap checks first, the slow call last
const buyerChecks: OrderCheck[] = [
seatLimit(6), seatsAvailable(seatsLeft), knownCode(new Set(["SPRING10"])), fraudCheck(riskScore),
];
const organizerChecks: OrderCheck[] = [seatsAvailable(seatsLeft)];
const buyerOrders: OrderRequest[] = [
{ showId: "spring", buyerEmail: "ana@example.com", quantity: 2, code: "SPRING10" },
{ showId: "spring", buyerEmail: "ben@example.com", quantity: 8, code: null },
{ showId: "spring", buyerEmail: "chi@example.com", quantity: 1, code: "FREE" },
{ showId: "spring", buyerEmail: "bot@fraud.example", quantity: 4, code: null },
];
for (const order of buyerOrders) {
console.log(order.buyerEmail, "->", (await runChecks(buyerChecks, order)) ?? "ok");
}
const guests: OrderRequest = { showId: "spring", buyerEmail: "guests@tinytickets.example", quantity: 8, code: null };
console.log("organizer guests ->", (await runChecks(organizerChecks, guests)) ?? "ok");
npx tsx checks-main.ts prints the same seven lines as checks-before.ts. The flag is gone, and the organizer chain is a shorter list. The order of each list is written where you can read it. Figure 5 shows the move.
Before After
[checkout] --> [checkOrder] [checks-main.ts] --> [runChecks] NEW
if !fromOrganizer: limit [runChecks] --> [OrderCheck] (I) NEW
seats left [seatLimit] ..> [OrderCheck] (I)
if code: known code [seatsAvailable] ..> [OrderCheck] (I)
if !fromOrganizer: fraud [knownCode] ..> [OrderCheck] (I)
--> [riskScore] [fraudCheck] ..> [OrderCheck] (I)
[fraudCheck] --> [riskScore]
Figure 5: one function with flags becomes four handlers and a loop; each caller picks its own list.
Figure 6 follows Ben’s order for 8 tickets through the buyer chain. It stops at the first handler, so the fraud service is never called.
1 [checks-main.ts] --> [runChecks] buyerChecks, Ben, 8 tickets
2 [runChecks] --> [seatLimit(6)] 8 > 6: "at most 6 tickets per order"
~ await: no other handler runs ~
3 [runChecks] answers "at most 6 tickets per order"
not called: [seatsAvailable], [knownCode], [fraudCheck] --> [riskScore]
Figure 6: the first handler that refuses ends the chain, and the slow fraud call never happens.
Rule: Put cheap checks first in a chain, so each refusal saves the slower work after it.
Prove it with a test
The test gives fraudCheck a fake riskScore that records every email it scores. Save checks.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { fraudCheck, runChecks, seatLimit, type RiskScore } from "./checks.ts";
test("a failed seat limit stops the chain before the fraud service is called", async () => {
const scored: string[] = [];
const fakeRisk: RiskScore = async (email) => {
scored.push(email);
return 10;
};
const checks = [seatLimit(6), fraudCheck(fakeRisk)];
const order = { showId: "spring", buyerEmail: "ben@example.com", quantity: 8, code: null };
assert.equal(await runChecks(checks, order), "at most 6 tickets per order");
assert.deepEqual(scored, []);
assert.equal(await runChecks(checks, { ...order, quantity: 2 }), null);
assert.deepEqual(scored, ["ben@example.com"]);
});
Output of npx tsx --test checks.test.ts:
✔ a failed seat limit stops the chain before the fraud service is called (0.815417ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
The test proves that a refused order never reaches the slow service. With checkOrder, riskScore was a module-level function, so a test couldn’t replace it without a tool that swaps imports for fakes.
The next change: a presale for Summer Lights
The presale is one new handler and one new line in the buyer chain. Add this handler to the end of checks.ts (excerpt):
// NEW: before the presale ends, a show needs its presale code
export const presale = (showId: string, code: string, endsOn: string, today: string): OrderCheck =>
async (order) =>
order.showId === showId && today < endsOn && order.code !== code ? "presale: code needed" : null;
Then add it to the buyer chain in checks-next.ts, a copy of checks-main.ts with a summer show of 400 seats. Its two orders are for Summer Lights, from Ana with no code and from Ben with FANS. This excerpt shows only the new chain:
const today = "2027-04-02";
const buyerChecks: OrderCheck[] = [
seatLimit(6),
presale("summer", "FANS", "2027-05-01", today), // NEW
seatsAvailable(seatsLeft),
knownCode(new Set(["SPRING10", "FANS"])), // "FANS" is NEW
fraudCheck(riskScore),
];
Output:
ana@example.com -> presale: code needed
[risk] scoring ben@example.com
ben@example.com -> ok
seatLimit, fraudCheck, runChecks and the organizer chain didn’t change. The dates are strings in YYYY-MM-DD form, so < compares them correctly.
Use it when, skip it when
Use Chain of Responsibility when:
- a request goes through several checks or handlers, and any one of them may end it
- different callers need different sets or orders of the same checks
- you see boolean flags like
fromOrganizerthat switch single rules on and off
Skip it when:
- there are two or three rules that every caller shares. A few
iflines in one function are clearer. - every rule must run and you want all the errors, as in a form or a CSV file of shows. Nothing stops early there, so use a list of rules and collect the results (scenario 2 below).
- exactly one handler must be chosen by a key, such as a payment provider. That’s an object map or Strategy (Module 4).
The cost
Each rule is now a named function, and the chain is spread over checks.ts and the file that builds the list. To learn why an order was refused, you read the list, then the handler. The order of the list is now part of the behavior, so if you put fraudCheck first, every order calls the slow service.
Each await in the loop also adds a promise per handler, even for handlers that do no async work. That cost is small, and it buys one handler type for sync and async checks.
Often confused with
- Middleware, the next section: a chain where each handler can also do work after the rest of the chain has answered.
- Decorator (Module 3): a wrapper always calls the object inside it, but a chain handler may stop the request.
- Strategy (Module 4): picks one way to do a job, but a chain asks many handlers, in order.
Exercise: where does the new check go?
Leo wants one more rule: a buyer may hold at most 2 orders per show. The check needs a database query, which is slower than the seat limit but faster than the fraud service. Where in buyerChecks do you put it, and does the organizer chain get it?
Answer
Put it after knownCode and before fraudCheck, so the cheap checks run first, then the database query, then the slowest call. Each refusal then saves the slower work after it. Write it like fraudCheck, as a factory that takes the query function, so a test can pass a fake.
The organizer chain doesn’t get it, because Leo adds guest tickets for many guests at once. With the old code, that decision would be one more flag inside checkOrder.
Middleware in Express and Koa: a chain around every request
The same lines in every route
The examples in this section start a server, send one request and print the answer. A helper does that in one call, and you don’t need to read it closely. Save call.ts:
import { once } from "node:events";
import { createServer, type RequestListener } from "node:http";
export type Reply = { status: number; requestId: string; body: string };
// Starts the app on a free port, sends one request, then stops the server
export async function call(app: RequestListener, method: string, path: string, apiKey = ""): Promise<Reply> {
const server = createServer(app).listen(0);
try {
await once(server, "listening");
const address = server.address();
if (address === null || typeof address === "string") throw new Error("no port");
const res = await fetch(`http://localhost:${address.port}${path}`, {
method,
headers: { "x-api-key": apiKey },
signal: AbortSignal.timeout(2000),
});
const type = res.headers.get("content-type") ?? "none";
const body = type.includes("json") ? await res.text() : `(${type.split(";")[0]})`;
return { status: res.status, requestId: res.headers.get("x-request-id") ?? "none", body };
} finally {
server.close();
}
}
export const show = (reply: Reply): void =>
console.log(`${reply.status} ${reply.requestId} ${reply.body}`);
call waits until the server is ready, and it gives up on a request after 2 seconds. show prints the status, the x-request-id header and the JSON body, or the content type when the body isn’t JSON.
Save a fake orders table as memory-orders.ts. Like a real database, it rejects an id with the wrong format:
import type { Order, OrderRepository } from "./types.ts";
// An in-memory fake of the orders table. Like a real database,
// it rejects an id with the wrong format instead of returning nothing.
export function memoryOrders(rows: Order[]): OrderRepository {
const byId = new Map(rows.map((order) => [order.id, order]));
return {
async findById(id) {
if (!/^o-\d+$/.test(id)) throw new Error(`invalid order id "${id}"`);
return byId.get(id);
},
async save(order) {
byId.set(order.id, order);
console.log(`[db] saved ${order.id} as ${order.status}`);
},
};
}
export const anaOrder = (): Order =>
({ id: "o-1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid" });
Here are two order routes as Maya wrote them, express-before.ts:
import express from "express";
import { call, show } from "./call.ts";
import { anaOrder, memoryOrders } from "./memory-orders.ts";
const orders = memoryOrders([anaOrder()]);
let requestCount = 0;
const app = express();
app.get("/orders/:id", async (req, res) => {
const requestId = `req-${++requestCount}`;
res.set("x-request-id", requestId);
const order = await orders.findById(req.params.id);
if (order === undefined) res.status(404).json({ error: "no such order" });
else res.json({ id: order.id, status: order.status });
console.log(`[log] ${requestId} GET ${req.path} ${res.statusCode}`);
});
app.post("/orders/:id/refund", async (req, res) => {
const requestId = `req-${++requestCount}`;
res.set("x-request-id", requestId);
const order = await orders.findById(req.params.id);
if (req.get("x-api-key") !== "leo-key") res.status(401).json({ error: "organizers only" });
else if (order === undefined) res.status(404).json({ error: "no such order" });
else {
await orders.save({ ...order, status: "refunded" });
res.json({ id: order.id, status: "refunded" });
}
console.log(`[log] ${requestId} POST ${req.path} ${res.statusCode}`);
});
show(await call(app, "GET", "/orders/o-1"));
show(await call(app, "GET", "/orders/o-9"));
show(await call(app, "POST", "/orders/o-1/refund"));
show(await call(app, "POST", "/orders/o-1/refund", "leo-key"));
show(await call(app, "GET", "/orders/abc"));
show(await call(app, "GET", "/ordrs/o-1"));
Output, with the stack trace shortened:
[log] req-1 GET /orders/o-1 200
200 req-1 {"id":"o-1","status":"paid"}
[log] req-2 GET /orders/o-9 404
404 req-2 {"error":"no such order"}
[log] req-3 POST /orders/o-1/refund 401
401 req-3 {"error":"organizers only"}
[db] saved o-1 as refunded
[log] req-4 POST /orders/o-1/refund 200
200 req-4 {"id":"o-1","status":"refunded"}
Error: invalid order id "abc"
at Object.findById (memory-orders.ts:9:38)
at <anonymous> (express-before.ts:12:30)
(eight more stack lines cut)
500 req-5 (text/html)
404 none (text/html)
Leo asked: “When a buyer says ‘something went wrong’, I want the request id from their screen to find the line in the log.” The first four requests work, and the last two show the gaps.
For /orders/abc the route threw, so its log line never ran, and Express’s default error handler sent an HTML page. For the misspelled /ordrs/o-1, no route matched, so there’s no request id at all. To close these gaps, Maya would copy more code into every route, and every new route would need the same copy. The refund route also asks the database before it checks the key.
Pause and predict: which lines are the same in both routes? Where could they run once, for every request, including requests that match no route or throw?
The idea: in through the doors, out through the same doors
Middleware is a function that runs for an HTTP request before, or around, the route handler, and decides whether the request goes on. Express is built on middleware, as the Express middleware guide shows, and express.json() is one you may have used. Middleware is Chain of Responsibility applied to HTTP requests, though the GoF book doesn’t use the word.
Each middleware gets the request and a next function, and it calls next() to pass the request on. If it doesn’t call next(), the chain stops there, and that middleware must answer. Koa is a small web framework from the team behind Express, in which every middleware is an async function. Express and Koa differ in what happens after next().
Think of a venue with an outer gate and an inner door. In Koa, you walk in through the gate and the door, see the show, and leave through the same door and gate, so each one sees you twice. In Express, the staff see you only on the way in. Figure 7 draws the Koa version.
Venue Koa
[outer gate] in: stamp your hand [outer] in: set x-request-id
[inner door] in: check ticket [route] find the order
(Buyer) sees the show set the body
[inner door] out: (nothing) (Koa answers from ctx.body)
[outer gate] out: count you [outer] out: write the log line
Figure 7: in Koa, the code after await next() runs on the way out, like a gate you pass twice.
What it lets you change without touching the rest: what happens to every request (ids, logs, checks, errors), while each route keeps only its own job.
The fix in Express: one job per middleware
In Express 5, next() returns nothing and doesn’t wait for the rest of the chain. So code that must run after the response listens for the response’s finish event, which is the Observer pattern inside middleware. Save middleware.ts:
import type { ErrorRequestHandler, RequestHandler } from "express";
let requestCount = 0;
export const requestId: RequestHandler = (req, res, next) => {
res.set("x-request-id", `req-${++requestCount}`);
next();
};
// next() in Express does not wait for the route, so log when the response ends
export const accessLog: RequestHandler = (req, res, next) => {
const line = `${req.method} ${req.path}`;
res.on("finish", () => console.log(`[log] ${res.get("x-request-id")} ${line} ${res.statusCode}`));
next();
};
export const requireOrganizer: RequestHandler = (req, res, next) => {
if (req.get("x-api-key") === "leo-key") next();
else res.status(401).json({ error: "organizers only" });
};
export const notFound: RequestHandler = (req, res) => {
res.status(404).json({ error: "no such route" });
};
// Four parameters tell Express that this is error-handling middleware
export const onError: ErrorRequestHandler = (err: unknown, req, res, next) => {
if (res.headersSent) {
next(err); // too late to send JSON; let Express close the connection
return;
}
console.log(`[log] ${res.get("x-request-id")} failed: ${String(err)}`);
res.status(500).json({ error: "server error", requestId: res.get("x-request-id") });
};
Error-handling middleware is middleware that Express calls only after something before it failed. Express spots it by its four parameters, so onError keeps all four. When the headers were already sent, it’s too late for a JSON answer, so onError passes the error on, as the Express error-handling guide advises. The request counter lives at module level to keep the output readable, but a real app would use crypto.randomUUID().
The routes now do only their own jobs. Save orders-app.ts:
import express from "express";
import { accessLog, notFound, onError, requestId, requireOrganizer } from "./middleware.ts";
import type { OrderRepository } from "./types.ts";
export function createApp(orders: OrderRepository): express.Express {
const app = express();
app.use(requestId, accessLog);
app.get("/orders/:id", async (req, res) => {
const order = await orders.findById(req.params.id);
if (order === undefined) res.status(404).json({ error: "no such order" });
else res.json({ id: order.id, status: order.status });
});
app.post<{ id: string }>("/orders/:id/refund", requireOrganizer, async (req, res) => {
const order = await orders.findById(req.params.id);
if (order === undefined) {
res.status(404).json({ error: "no such order" });
return;
}
await orders.save({ ...order, status: "refunded" });
res.json({ id: order.id, status: "refunded" });
});
app.use(notFound);
app.use(onError);
return app;
}
The order of the app.use lines is the order of the chain. requestId and accessLog come first, so every request gets them. notFound comes after the routes, so it answers only what no route matched, and onError comes last. requireOrganizer sits in the refund route only.
The <{ id: string }> after app.post tells TypeScript the route’s parameters, and “Going deeper” says why it’s needed. createApp takes the repository as a parameter, as wireListeners took its deps. Save express-after.ts:
import { call, show } from "./call.ts";
import { anaOrder, memoryOrders } from "./memory-orders.ts";
import { createApp } from "./orders-app.ts";
const app = createApp(memoryOrders([anaOrder()]));
show(await call(app, "GET", "/orders/o-1"));
show(await call(app, "GET", "/orders/o-9"));
show(await call(app, "POST", "/orders/o-1/refund"));
show(await call(app, "POST", "/orders/o-1/refund", "leo-key"));
show(await call(app, "GET", "/orders/abc"));
show(await call(app, "GET", "/ordrs/o-1"));
Output:
[log] req-1 GET /orders/o-1 200
200 req-1 {"id":"o-1","status":"paid"}
[log] req-2 GET /orders/o-9 404
404 req-2 {"error":"no such order"}
[log] req-3 POST /orders/o-1/refund 401
401 req-3 {"error":"organizers only"}
[db] saved o-1 as refunded
[log] req-4 POST /orders/o-1/refund 200
200 req-4 {"id":"o-1","status":"refunded"}
[log] req-5 failed: Error: invalid order id "abc"
[log] req-5 GET /orders/abc 500
500 req-5 {"error":"server error","requestId":"req-5"}
[log] req-6 GET /ordrs/o-1 404
404 req-6 {"error":"no such route"}
The first nine lines match the “before” output. The last five are Leo’s change. The error and the unknown route now have a request id, a JSON body and a log line. Figure 8 shows the structure.
Before After
[GET /orders/:id] [app] --> [requestId] NEW
id, lookup, log [app] --> [accessLog] NEW
[POST /orders/:id/refund] [app] --> [GET /orders/:id]
id, key check, lookup, log [app] --> [requireOrganizer] NEW
--> [POST .../refund]
errors and unknown routes: [app] --> [notFound] NEW
Express default (HTML) [app] --> [onError] NEW
Figure 8: the lines copied into every route become middleware that runs once for every request.
The same chain in Koa
Install Koa with its types:
npm install koa
npm install --save-dev @types/koa
In Koa, await next() waits for the rest of the chain. Its promise settles when everything after this middleware has finished. So one middleware can set the id, catch errors from the whole chain, and write the log line after the answer is ready.
Koa has no router built in, so real apps add one such as @koa/router, and this example matches the path by hand. Save koa-after.ts:
import Koa from "koa";
import { call, show } from "./call.ts";
import { anaOrder, memoryOrders } from "./memory-orders.ts";
const orders = memoryOrders([anaOrder()]);
let requestCount = 0;
const app = new Koa();
// Outer layer: request id, errors and the log line, around everything inside
app.use(async (ctx, next) => {
const requestId = `req-${++requestCount}`;
ctx.set("x-request-id", requestId);
try {
await next(); // the rest of the chain runs here
} catch (err: unknown) {
console.log(`[log] ${requestId} failed: ${String(err)}`);
ctx.status = 500;
ctx.body = { error: "server error", requestId };
}
console.log(`[log] ${requestId} ${ctx.method} ${ctx.path} ${ctx.status}`);
});
// Inner layer: the route. Koa has no router, so this matches the path by hand.
app.use(async (ctx) => {
const match = /^\/orders\/([^/]+)$/.exec(ctx.path);
if (ctx.method !== "GET" || match === null) {
ctx.status = 404;
ctx.body = { error: "no such route" };
return;
}
const order = await orders.findById(match[1]);
ctx.status = order === undefined ? 404 : 200;
ctx.body = order === undefined ? { error: "no such order" } : { id: order.id, status: order.status };
});
show(await call(app.callback(), "GET", "/orders/o-1"));
show(await call(app.callback(), "GET", "/orders/o-9"));
show(await call(app.callback(), "GET", "/orders/abc"));
show(await call(app.callback(), "GET", "/ordrs/o-1"));
ctx, the context, holds the request and the response together, and setting ctx.body is how a Koa middleware answers. app.callback() returns the plain Node.js request handler that call needs. Output:
[log] req-1 GET /orders/o-1 200
200 req-1 {"id":"o-1","status":"paid"}
[log] req-2 GET /orders/o-9 404
404 req-2 {"error":"no such order"}
[log] req-3 failed: Error: invalid order id "abc"
[log] req-3 GET /orders/abc 500
500 req-3 {"error":"server error","requestId":"req-3"}
[log] req-4 GET /ordrs/o-1 404
404 req-4 {"error":"no such route"}
Figure 9 follows one Koa request. The outer middleware waits at await next() while the route works. Koa’s docs call this flow cascading.
1 (Buyer) --> [outer] GET /orders/o-1; outer sets req-1
2 [outer] --> [route] await next()
~ await: outer waits until the route has finished ~
3 [route] --> [orders] findById("o-1")
~ await ~
4 [route] sets status 200 and the body
5 [outer] resumes after next() logs "[log] req-1 GET /orders/o-1 200"
6 Koa answers (Buyer) 200 {"id":"o-1","status":"paid"}
Figure 9: in Koa the outer middleware wraps the whole request, so its last line runs after the route.
Where an error goes in Express and Koa
Errors take a different road in each framework. Figure 10 shows where a thrown error goes.
Express 5 Koa
[requestId] --> [accessLog] --> [route] [outer] --> [route]
[route] throws or rejects [route] throws or rejects
Express skips normal middleware the error comes back out of
--> [onError] (four parameters) "await next()" in [outer]
--> 500 JSON with the request id catch --> 500 JSON, then log
no error middleware: no try/catch anywhere:
default handler, HTML page default handler, plain text
Figure 10: Express jumps forward to the error middleware; Koa sends the error back up through the middleware that called next().
Express 5 sends a rejected promise from an async route to the error middleware for you, as its error-handling guide describes. Koa’s default error handler is a try/catch at the start of the chain, as the Koa error-handling docs describe. You replace it by putting your own try/catch first.
Rule: Express sends an error forward to the next error middleware; Koa sends it back up to the
await next()that called the failing code.
Prove it with a test
createApp takes the repository, so a test can pass a fake that always fails. Save orders-app.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { call } from "./call.ts";
import { createApp } from "./orders-app.ts";
import type { OrderRepository } from "./types.ts";
test("a failing database gives a JSON 500 that carries the request id", async () => {
const saved: string[] = [];
const downOrders: OrderRepository = {
findById: async () => {
throw new Error("database is down");
},
save: async (order) => {
saved.push(order.id);
},
};
const app = createApp(downOrders);
const refused = await call(app, "POST", "/orders/o-1/refund");
assert.equal(refused.status, 401);
const failed = await call(app, "POST", "/orders/o-1/refund", "leo-key");
assert.equal(failed.status, 500);
assert.equal(failed.body, `{"error":"server error","requestId":"${failed.requestId}"}`);
assert.deepEqual(saved, []);
});
Output of npx tsx --test orders-app.test.ts:
[log] req-1 POST /orders/o-1/refund 401
[log] req-2 failed: Error: database is down
[log] req-2 POST /orders/o-1/refund 500
✔ a failing database gives a JSON 500 that carries the request id (26.123083ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0
The test checks the whole chain. The key check stops the first request, and the error middleware turns a database failure into JSON with the request id. Nothing was saved. The “before” app couldn’t be tested this way, because its orders table was module-level.
The next change: organizers can cancel orders
Leo wants a DELETE /orders/:id route for organizers. Add it to createApp in orders-app.ts, before app.use(notFound) (excerpt):
// NEW: organizers can cancel an order
app.delete<{ id: string }>("/orders/:id", requireOrganizer, async (req, res) => {
const order = await orders.findById(req.params.id);
if (order === undefined) res.status(404).json({ error: "no such order" });
else {
await orders.save({ ...order, status: "cancelled" });
res.json({ id: order.id, status: "cancelled" });
}
});
Save express-next.ts:
import { call, show } from "./call.ts";
import { anaOrder, memoryOrders } from "./memory-orders.ts";
import { createApp } from "./orders-app.ts";
const app = createApp(memoryOrders([anaOrder()]));
show(await call(app, "DELETE", "/orders/o-1"));
show(await call(app, "DELETE", "/orders/o-1", "leo-key"));
show(await call(app, "DELETE", "/orders/abc", "leo-key"));
Output:
[log] req-1 DELETE /orders/o-1 401
401 req-1 {"error":"organizers only"}
[db] saved o-1 as cancelled
[log] req-2 DELETE /orders/o-1 200
200 req-2 {"id":"o-1","status":"cancelled"}
[log] req-3 failed: Error: invalid order id "abc"
[log] req-3 DELETE /orders/abc 500
500 req-3 {"error":"server error","requestId":"req-3"}
The new route has no id code, no log code and no error code, and it got all three. The key check is one word in its argument list.
Use it when, skip it when
Use middleware when:
- the same lines appear at the start or end of many routes: ids, logs, checks, headers
- something must happen for requests that match no route, or that throw
- a group of routes shares one rule, such as “organizers only”
Skip it when:
- only one route needs the code. Keep it in that route, or in a function the route calls.
- the code needs data that only the route has, such as the loaded order. Middleware would have to pass it through
res.localsin Express orctx.statein Koa, objects that carry data between middleware with weaker types.
The cost
Middleware is code that runs without being named in the route. A newcomer who reads the GET route doesn’t see the request id or the error handling. The order of app.use lines is behavior, so if you move notFound above the routes, every request gets a 404.
Each middleware also adds a function call to every request, and in Koa an await. Stack traces include framework lines between your functions, as the cut traces above show.
Often confused with
Chain of Responsibility is the closest. A handler there either answers or passes on, but middleware can also act after the rest of the chain, as Koa’s outer layer and Express’s finish listener do. Decorator (Module 3) wraps one object or function. Middleware is a list that every request passes through, set up on the app.
Exercise: move the error middleware
What does GET /orders/abc return if you move app.use(onError) to the line after app.use(requestId, accessLog)? Predict the status, the body and the log lines, then try it.
Answer
Express sends an error forward to the next error middleware after the point where it happened. With onError above the routes, there is none, so Express’s default handler answers with status 500, an HTML page, and the stack trace printed by Express. The response still has x-request-id: req-1, because requestId ran first, and accessLog still writes [log] req-1 GET /orders/abc 500. The failed: log line and the JSON body are gone.
Mediator: one object that knows the rules between parts
On a sale night, TinyTickets has three parts that depend on each other. A seat hold timer frees seats that a buyer reserved but didn’t pay for, a waiting list holds buyers who want those seats, and checkout takes payments. When a hold expires, its seats go to the next buyer on the waiting list, and when a payment fails, the hold ends.
Each part calls the others to make that happen. A mediator is an object that holds the rules for how several parts work together, so the parts talk to the mediator and not to each other. Mediator is a GoF behavioral pattern. Figure 11 shows the parts before and after a saleDesk mediator.
Before: each part calls the others After: each part calls saleDesk
[holdTimer] --> [waitingList] [holdTimer] --> [saleDesk] NEW
[holdTimer] --> [checkout] [checkout] --> [saleDesk]
[checkout] --> [holdTimer] [waitingList] --> [saleDesk]
[waitingList] --> [checkout] [saleDesk] --> each part
Figure 11: the rules between the parts move into one place, and the parts stop calling each other.
You need it when three or more parts call each other, and a rule change (“waiting-list buyers get 5 minutes, not 10”) touches all of them. wireListeners from the Observer section is close to a mediator, since one function knows who reacts to what. The cost is that the mediator can grow into the one file everybody edits.
Publish/Subscribe: senders and receivers that never meet
Sometimes the code that sends a message and the code that receives it live in different processes or packages. In Publish/Subscribe (Pub/Sub for short), publishers send messages to a named channel. A broker, a program in the middle, delivers each message to whoever subscribed to that channel. Publishers and subscribers never hold a reference to each other, because both know only the broker and the channel name.
Pub/Sub isn’t in the GoF book; Enterprise Integration Patterns (Hohpe and Woolf, 2003) describes it. Figure 12 puts it next to Observer with the same layout. The one difference is the broker in the middle.
Observer Publish/Subscribe
[checkout] --> [events] [checkout] --> [broker] NEW
[sendReceipt] registered on [events] [mailer] subscribed to [broker]
[events] --> [sendReceipt] [broker] --> [mailer]
listener knows the subject publisher and subscriber know
same process only "orders"; any process
Figure 12: in Pub/Sub a broker sits between the two sides, so neither side knows the other.
Redis is an in-memory data store that runs as a separate server, and it can act as a broker. In Redis Pub/Sub, publishers send to channels across processes, with no knowledge of the subscribers. You need Pub/Sub when the senders and receivers live in different processes or are deployed separately. The cost is a broker to run, and messages that travel outside your TypeScript types, so inside one app the typed emitter from the Observer section is enough.
Side by side
Chain of Responsibility and middleware look the most alike. Figure 13 draws them with the same layout. The one difference, marked DIFFERENT, is that middleware can act again after the rest of the chain answers.
Chain of Responsibility Middleware (Koa)
[runChecks] --> [seatLimit] [app] --> [outer]
[runChecks] --> [seatsAvailable] [outer] --> [route]
[runChecks] --> [fraudCheck] [route] answers
first "no" ends the chain first "no" ends the chain
a handler is done when it answers DIFFERENT: [outer] runs again
after "await next()" returns
Figure 13: both pass a request along until someone stops it; only middleware gets a second turn on the way back.
Figure 14 is this module’s decision figure. It starts from the code in front of you.
Code reacts to something, or passes a request along
|
v
One or two reactions, same owner? -- yes --> No pattern: call the
| no functions directly.
v
Many reactions to "X happened"? -- yes --> In one process: Observer.
| no Across processes: Pub/Sub.
v
Every rule must run, all errors wanted? -- yes --> A list of rules,
| no no chain.
v
Any step may stop the request? -- yes --> HTTP request: middleware.
| no Other: Chain of Responsibility.
v
Parts all call each other? -- yes --> Mediator. -- no --> No pattern.
Figure 14: start from the shape of the problem; two of the exits need no pattern at all.
Check yourself
- Why does
new EventEmitter()alone not catchemit("order:payed", ...), and what in this module catches it? - What happens to a Node.js process when an async listener rejects and nothing handles the rejection, and how does
wireListenersprevent it? - In
runChecks, what makes a handler stop the chain, and why doesfraudCheckcome last inbuyerChecks? - In Express 5, why does
accessLoguseres.on("finish")instead of code afternext()? Where does that code go in Koa? - What is the one difference between Observer and Publish/Subscribe?
Answers
emitaccepts any string, and a name with no listeners only returnsfalse. TheOrderEventsmap with theOrderEmitterinterface catches it, because event names must bekeyof OrderEvents, sotscreports the typo.emitdoesn’t wait for the listener’s promise, so the rejection is unhandled, and by default Node.js stops the process.logErrorsattaches.catchto every async listener and turns the failure into a log line.- A handler stops the chain by returning a reason instead of
null, andrunChecksreturns at the first reason.fraudCheckcalls a slow outside service, so the cheap checks run first and stop most bad orders before that call. - In Express,
next()returns before the route has answered, so code after it runs too early. Thefinishevent fires when the response is done. In Koa,await next()waits for the rest of the chain, so the code goes after it. - Pub/Sub puts a broker between the two sides, so publishers and subscribers don’t know each other. In Observer, listeners register directly on the subject.
Lab: refunds with a chain and an event
Time: about 20 minutes. Put the files next to fakes.ts, types.ts, and the versions of order-events.ts, listeners.ts and wire-listeners.ts from “The next change: refunds free the seats”.
Here is TinyTickets’ refund code, refund.ts:
import { MailClient } from "./fakes.ts";
import type { Order } from "./types.ts";
const mail = new MailClient("localhost");
const showDates = new Map([["spring", "2027-03-14"]]);
// Refunds a paid order, or returns why it cannot
export async function refundOrder(order: Order, today: string): Promise<string> {
if (order.status !== "paid") return `order ${order.id} is ${order.status}, not paid`;
const showDate = showDates.get(order.showId);
if (showDate === undefined) return `no date for show ${order.showId}`;
if (today >= showDate) return "the show has started";
order.status = "refunded";
await mail.send(order.buyerEmail, `Order ${order.id} is refunded`);
console.log(`[seats] refresh map for ${order.showId}`);
return "refunded";
}
Here is run-refund.ts, which refunds Ana’s order:
import { refundOrder } from "./refund.ts";
import type { Order } from "./types.ts";
const order: Order = {
id: "o-1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid",
};
console.log(await refundOrder(order, "2027-03-01"));
Output of npx tsx run-refund.ts:
[mail] to ana@example.com: Order o-1 is refunded
[seats] refresh map for spring
refunded
Leo’s change request has three parts:
- Refunds close 2 days before the show, not when it starts.
- More rules are coming, such as “no refunds for free tickets”.
- The email and the seat refresh become listeners on
order:refunded, so the refund code sends nothing itself.
Refactor refund.ts so that this test file, refund.test.ts, passes:
import { test } from "node:test";
import assert from "node:assert/strict";
import { closesDaysBefore, isPaid, refundOrder, type RefundCheck } from "./refund.ts";
import { createOrderEvents } from "./order-events.ts";
import type { Order } from "./types.ts";
const showDates = new Map([["spring", "2027-03-14"]]);
const checks: RefundCheck[] = [isPaid, closesDaysBefore(2, showDates)];
const paid = (): Order => ({
id: "o-1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid",
});
function listen() {
const events = createOrderEvents();
const heard: string[] = [];
events.on("order:refunded", (order) => heard.push(`${order.id} ${order.status}`));
return { events, heard };
}
test("a paid order is refunded, and listeners hear order:refunded", () => {
const { events, heard } = listen();
assert.equal(refundOrder(paid(), "2027-03-01", checks, events), "refunded");
assert.deepEqual(heard, ["o-1 refunded"]);
});
test("refunds close two days before the show", () => {
const { events, heard } = listen();
assert.equal(refundOrder(paid(), "2027-03-12", checks, events), "refunds close 2 days before the show");
assert.deepEqual(heard, []);
});
test("the first failed check stops the chain", () => {
const { events } = listen();
const cancelled: Order = { ...paid(), status: "cancelled" };
assert.equal(refundOrder(cancelled, "2027-03-13", checks, events), "order o-1 is cancelled, not paid");
});
Run it with npx tsx --test refund.test.ts, and check types with npx tsc --noEmit. Then rewrite run-refund.ts so that it registers the listeners and prints the same three lines as before.
Pause and predict: which part of
refundOrderis a chain, and which part becomes an event? What doesrefundOrderstill need to receive as parameters?
Hint 1
The two if lines that return a reason are handlers in a chain. The email and the seat refresh are reactions to “an order was refunded”. The status change stays in refundOrder.
Hint 2
The test calls refundOrder without await, so it’s now a sync function. The checks do no async work, so RefundCheck can be (order: Order, today: string) => string | null. The loop is the same as runChecks, without await.
Hint 3
closesDaysBefore(2, showDates) is a factory, like seatLimit(6). Compute the cutoff date with Date.parse(showDate) - days * 86_400_000, turn it back into YYYY-MM-DD with toISOString().slice(0, 10), and refuse when today >= cutoff. The refund email is one logErrors line in wireListeners, above the seat line, so the output keeps its order.
Solution
refund.ts:
import type { OrderEmitter } from "./order-events.ts";
import type { Order } from "./types.ts";
// One handler in the chain: a reason stops the refund, null passes it on
export type RefundCheck = (order: Order, today: string) => string | null;
export const isPaid: RefundCheck = (order) =>
order.status === "paid" ? null : `order ${order.id} is ${order.status}, not paid`;
export const closesDaysBefore = (days: number, showDates: Map<string, string>): RefundCheck =>
(order, today) => {
const showDate = showDates.get(order.showId);
if (showDate === undefined) return `no date for show ${order.showId}`;
const cutoff = new Date(Date.parse(showDate) - days * 86_400_000).toISOString().slice(0, 10);
return today >= cutoff ? `refunds close ${days} days before the show` : null;
};
// Runs the checks in order, then tells the listeners; it sends nothing itself
export function refundOrder(order: Order, today: string, checks: RefundCheck[], events: OrderEmitter): string {
for (const check of checks) {
const reason = check(order, today);
if (reason !== null) return reason;
}
order.status = "refunded";
events.emit("order:refunded", order);
return "refunded";
}
In wire-listeners.ts, the refund email goes above the seat line at the end of wireListeners. This excerpt shows the last three lines of the function; the rest is unchanged:
events.on("seats:changed", logErrors("refreshSeatMap", deps.refreshSeatMap));
events.on("order:refunded", logErrors("sendRefundEmail", (order) =>
deps.sendEmail(order.buyerEmail, `Order ${order.id} is refunded`))); // NEW in the lab
events.on("order:refunded", (order) => events.emit("seats:changed", order.showId));
run-refund.ts:
import { MailClient } from "./fakes.ts";
import { createOrderEvents } from "./order-events.ts";
import { closesDaysBefore, isPaid, refundOrder } from "./refund.ts";
import type { Order } from "./types.ts";
import { wireListeners } from "./wire-listeners.ts";
const events = createOrderEvents();
const mail = new MailClient("localhost");
wireListeners(events, {
sendEmail: (to, text) => mail.send(to, text),
refreshSeatMap: async (showId) => console.log(`[seats] refresh map for ${showId}`),
log: (line) => console.log(line),
});
const checks = [isPaid, closesDaysBefore(2, new Map([["spring", "2027-03-14"]]))];
const order: Order = {
id: "o-1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid",
};
console.log(refundOrder(order, "2027-03-01", checks, events));
Output of npx tsx run-refund.ts:
[mail] to ana@example.com: Order o-1 is refunded
[seats] refresh map for spring
refunded
The three tests pass with ℹ pass 3 and ℹ fail 0. The checks are a chain, so “no refunds for free tickets” is one more RefundCheck and one more item in the list. The reactions are listeners registered in one place, and refundOrder no longer imports a mail client. The test proves both with no fake mail client at all, because it only listens for the event.
This solution leaves three things as they were. refundOrder still changes the caller’s order object, because no test asked for a new one. Saving the refund and paying the money back are still missing, and Module 7 covers saving. The refund also has no organizer check, because that belongs in the route’s middleware.
Which pattern, if any?
Scenario 1: one more line after checkout
Here is the end of checkout, scenario-1.ts:
import { MailClient } from "./fakes.ts";
import type { Order, Send } from "./types.ts";
export async function finishCheckout(order: Order, send: Send): Promise<void> {
console.log(`[db] saved ${order.id} as ${order.status}`);
await send(order.buyerEmail, `Your tickets for order ${order.id}`);
}
const mail = new MailClient("localhost");
await finishCheckout(
{ id: "o-1", showId: "spring", buyerEmail: "ana@example.com", quantity: 2, totalCents: 2550, status: "paid" },
(to, text) => mail.send(to, text),
);
Output:
[db] saved o-1 as paid
[mail] to ana@example.com: Your tickets for order o-1
The new requirement: Leo wants one log line per sale, [log] sale o-1: 2 tickets for spring, between the save and the email. Nothing else reacts to a sale in this app, and the same developer owns this file and the log. Which pattern, if any?
Hint 1
Count the reactions and the owners. Then look at the first question in Figure 14.
Hint 2
What would an emitter add here that a function call doesn’t have? What would it take away?
Strong answer
No pattern. Add one line to finishCheckout, and save the file as scenario-1-answer.ts. This excerpt shows only the function; the rest of the file is the same as scenario-1.ts:
export async function finishCheckout(order: Order, send: Send): Promise<void> {
console.log(`[db] saved ${order.id} as ${order.status}`);
console.log(`[log] sale ${order.id}: ${order.quantity} tickets for ${order.showId}`); // NEW
await send(order.buyerEmail, `Your tickets for order ${order.id}`);
}
Output:
[db] saved o-1 as paid
[log] sale o-1: 2 tickets for spring
[mail] to ana@example.com: Your tickets for order o-1
There are two reactions with one owner, and their order matters. An emitter would hide the order, make errors harder to see, and add a wiring file for two lines. Revisit when a third reaction arrives from a different part of the code, or when the email must stop slowing down checkout.
Scenario 2: checking rows in the nightly show import
The nightly show import checks each row of a CSV file of shows. Here is the check, scenario-2.ts:
type ShowRow = { title: string; date: string; priceCents: number };
// Checks one row of the nightly show import; returns every problem found
function validateRow(row: ShowRow): string[] {
const errors: string[] = [];
if (row.title.trim() === "") errors.push("title is empty");
if (!/^\d{4}-\d{2}-\d{2}$/.test(row.date)) errors.push("date must be YYYY-MM-DD");
if (!Number.isInteger(row.priceCents) || row.priceCents < 0) errors.push("price must be whole cents");
return errors;
}
console.log(validateRow({ title: "Songs of Spring", date: "2027-03-14", priceCents: 1200 }));
console.log(validateRow({ title: " ", date: "14/03/2027", priceCents: 12.5 }));
Output:
[]
[
'title is empty',
'date must be YYYY-MM-DD',
'price must be whole cents'
]
The new requirement: festival files have a capacity column, and festival rows must have a capacity of 60,000 or less. Club files have no capacity, and the check must not run for them. Organizers want every problem in a row reported at once, so they can fix all of them in one edit of the file. Which pattern, if any?
Hint 1
The shape looks like the order checks: a list of rules, and different lists for different callers. What is different about what happens after the first problem?
Hint 2
In Chain of Responsibility, the first handler that answers ends the chain. Here, does any rule end the work?
Strong answer
Chain of Responsibility doesn’t fit, because no rule may stop the others. Use a list of rule functions and run them all, with one list per kind of file. Save scenario-2-answer.ts:
type ShowRow = { title: string; date: string; priceCents: number; capacity: number | null };
type RowRule = (row: ShowRow) => string | null;
const title: RowRule = (row) => (row.title.trim() === "" ? "title is empty" : null);
const date: RowRule = (row) => (/^\d{4}-\d{2}-\d{2}$/.test(row.date) ? null : "date must be YYYY-MM-DD");
const price: RowRule = (row) =>
Number.isInteger(row.priceCents) && row.priceCents >= 0 ? null : "price must be whole cents";
const capacity: RowRule = (row) =>
row.capacity !== null && row.capacity <= 60000 ? null : "capacity must be 60000 or less";
// Each kind of file gets its own list; every rule runs, nothing stops early
const rulesFor = { club: [title, date, price], festival: [title, date, price, capacity] };
function validateRow(rules: RowRule[], row: ShowRow): string[] {
return rules.map((rule) => rule(row)).filter((error) => error !== null);
}
console.log(validateRow(rulesFor.club, { title: "Songs of Spring", date: "2027-03-14", priceCents: 1200, capacity: null }));
console.log(validateRow(rulesFor.club, { title: " ", date: "14/03/2027", priceCents: 12.5, capacity: null }));
console.log(validateRow(rulesFor.festival, { title: "Summer Lights", date: "2027-06-20", priceCents: 1500, capacity: 90000 }));
Output:
[]
[
'title is empty',
'date must be YYYY-MM-DD',
'price must be whole cents'
]
[ 'capacity must be 60000 or less' ]
filter((error) => error !== null) returns string[], because TypeScript (since 5.5) reads that arrow function as a type check. This is Idea 1 from Module 1, an object map of rules, and it borrows one idea from the chain, a separate list for each caller. A chain would report only the first error, so the organizer would fix the file one error at a time.
Ask for feedback on your answer
Copy this prompt into an AI assistant, with your answer and the scenario code:
I am learning design patterns in TypeScript and Node.js. Below is a piece
of code, a new requirement, and my answer to "which pattern, if any?".
Review my answer. Tell me: (1) whether the pattern I chose fits, and the
one signal in the code that supports or contradicts it; (2) a simpler
option if one exists; (3) one cost my answer adds. Keep the review under
200 words and do not rewrite my whole answer.
Code:
<paste the scenario code>
Requirement:
<paste the requirement>
My answer:
<paste your answer>
Going deeper
You can skip this section. It covers alternatives and edge cases that the main path left out.
The typed event map in @types/node
@types/node, the type definitions for Node.js, also accepts a map of events, as in new EventEmitter<OrderEvents>(). That form checks the arguments of the names in the map. But in the version used here (26.6), it still accepts names outside the map, so it wouldn’t have caught order:payed. That’s why the fix writes the OrderEmitter interface instead.
Removing listeners, and waiting for one event
To remove a listener, call off(name, listener) with the same function you passed to on. When you wait for one event, once from node:events removes its own listener for you. It accepts an abort signal, an AbortSignal object that a waiting call watches, and it stops waiting when the signal fires. Save long-poll.ts, where buyers wait for a seat change:
import { EventEmitter, once } from "node:events";
import type { OrderEvents } from "./order-events.ts";
// once() needs a real EventEmitter, so this example makes one directly
const events = new EventEmitter<OrderEvents>();
// Leaks: every waiting buyer adds a listener, and nothing removes it
function waitForSeatsLeaky(showId: string): void {
events.on("seats:changed", (changed) => {
if (changed === showId) console.log(`seats changed for ${showId}`);
});
}
for (let i = 0; i < 11; i++) waitForSeatsLeaky("spring");
console.log("listeners after 11 waits:", events.listenerCount("seats:changed"));
events.removeAllListeners("seats:changed");
// Fixed: once() removes its listener when the event comes or the signal fires
async function waitForSeats(signal: AbortSignal): Promise<string> {
try {
const [showId]: unknown[] = await once(events, "seats:changed", { signal });
return `seats changed for ${String(showId)}`;
} catch (err: unknown) {
if (err instanceof Error && err.name === "AbortError") return "no change; stopped waiting";
throw err;
}
}
setTimeout(() => events.emit("seats:changed", "spring"), 10);
console.log(await waitForSeats(AbortSignal.timeout(1000)));
const left = new AbortController();
setTimeout(() => left.abort(), 50); // the buyer closes the page
console.log(await waitForSeats(left.signal));
console.log("listeners left:", events.listenerCount("seats:changed"));
Output:
listeners after 11 waits: 11
(node:21659) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 seats:changed listeners added to [EventEmitter]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
seats changed for spring
no change; stopped waiting
listeners left: 0
events.once returns a promise of the event’s arguments, typed any[]. So the code stores them as unknown[] and converts showId with String. The promise rejects with an AbortError when the signal fires, and an AbortController makes a signal that you fire yourself with abort().
Node.js also has a built-in option for async listener errors, captureRejections. It sends a rejected listener promise to the emitter’s error event, so you then need an error listener, or that event crashes the process too. logErrors keeps the decision visible in the wiring file. A listener that throws synchronously is different, because the error comes out of emit into the caller, and the later listeners don’t run.
The GoF chain of linked objects
The GoF book draws the chain as linked objects. Each handler holds a reference to the next one, and a handler that passes the order on calls the next handler’s method itself. That gives a handler more power, because it could change the order before it passes it on, or act after the next handler answers. Middleware works the same way with its next function.
This course uses the array and the loop instead. They show the order of the chain in one place, and no handler can forget to pass the order on.
Two Express details: route types and a middleware class
In orders-app.ts, the <{ id: string }> after app.post names the route parameters. With more than one handler in the route, the Express types no longer read :id from the path string. Without it, req.params.id would be typed string | string[].
Middleware is almost always a function. A class helps when the middleware keeps state between requests, such as a rate limiter that counts requests per client. Give the class an arrow function stored in a field and pass that to app.use, so this still points to the object when Express calls it. NestJS, which Module 6 shows, writes middleware as a class that implements NestMiddleware, because its classes can receive services through their constructor.
Cheat sheet
| Pattern | The problem it answers | The signal in your code | Cost |
|---|---|---|---|
| Observer (typed EventEmitter) | Many reactions to one action, owned by different code | bus.on(...) in many files; event names as loose strings |
Hidden flow; async errors and leaked listeners to handle |
| Chain of Responsibility | Checks that may stop a request, different per caller | Boolean flags like fromOrganizer that switch rules on and off |
The list order is behavior; one more step to read per check |
| Middleware | The same lines in every route | Copied id, log, key or try/catch code at the top of routes |
Code runs that the route doesn’t name; the order of app.use matters |
| Mediator | Parts that all call each other | A rule change touches three or more files that import each other | The mediator can become the file everyone edits |
| Publish/Subscribe | Senders and receivers in different processes | You want to emit in one service and listen in another | A broker to run; messages travel outside your types |
| No pattern | One or two reactions or rules, one owner | The direct call fits on one line | Revisit when a third reaction or another owner arrives |
- Observer: list every event name in one type, register every listener in one function, and give each async listener a
.catch. - Chain of Responsibility: a handler returns a reason to stop or
nullto pass; each caller builds its own list, cheap checks first. - Express middleware: code after the response goes in a
finishlistener, and errors go forward to four-parameter middleware. - Koa middleware: code after
await next()runs on the way out, and atry/catcharound it catches errors from the whole chain. - No pattern: one or two reactions with one owner are a direct call, and rules that must all run are a list, not a chain.
- Next: Module 6 starts from
wireListeners(events, deps)andcreateApp(orders), which already take what they need as parameters, and names that idea Dependency Injection.
Sources
- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994. Observer, Chain of Responsibility and Mediator, and their behavioral category.
- Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Addison-Wesley, 2003. The Publish-Subscribe Channel.
- Node.js documentation: events, including synchronous calls, capture rejections of promises,
events.onceand default max listeners; unhandled rejections mode;http'request'event; timers promises. - Express: error handling, using middleware.
- Koa: koajs.com, error handling, @koa/router.
- NestJS: middleware.
- Redis: Pub/Sub.
- TypeScript handbook: generics.