Domain-Driven Design in TypeScript / Module 01

Module 1: Code and Leo Use Different Words

Find where your code and the business use different words, write a glossary, and rename files, types and stored jobs without losing history.

The story so far. TinyTickets sold tickets for Leo and for several other organizers. It ran on one server, with a worker for slow tasks. Nina and Omar joined Maya as developers. The code had grown for three years without a plan.

Read the whole story.

Leo asked for 15-minute holds, so that his regular guests had more time to pay. Nina found RESERVATION_MINUTES in services/reservations.ts, changed 10 to 15, and shipped it on Thursday.

On Friday at 10:00, Leo’s club show went on sale. By 10:30, the club had 203 paid tickets for 200 seats.

“I asked for longer holds,” Leo wrote. “Why did we sell three seats twice?”

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

Nina changed the only constant she could find. The code that frees unpaid seats has its own 10 minutes, under a different name. This module is about that gap between Leo’s words and the code’s words. It starts Domain-Driven Design (DDD) with a shared language and a glossary, and then renames the code to match.

After this module, you can:

  • find every name the code uses for one business idea, and see where those names disagree
  • write a glossary entry with a term’s meaning, its names in the code and the words to stop using
  • sort a business into core, supporting and generic subdomains, and say which part gets the most care
  • rename files, types, job names and stored rows so that tsc, the tests and git log --follow keep working
  • say when a word in the code should stay as it is

Set up TinyTickets in year 3

The whole course refactors one app, TinyTickets, as Build and Deploy a Web App and Background Jobs left it, after a third year of features. Every module starts from the code the previous module left. Module 1 starts from the starter project. These are the versions the course uses in all eleven modules:

Tool Version Where to check
Node.js 26.13.1 (LTS) nodejs.org release index
TypeScript 7.0.2 Announcing TypeScript 7.0
Express 5.3.0 express on npm
pg 8.23.1 node-postgres
PostgreSQL 18.7 PostgreSQL versions

With type stripping, Node.js 26 removes the type annotations from a .ts file and runs the JavaScript that is left, with no build step and no flag. The Node.js docs mark it stable since 25.2.0 and 24.12.0. Type stripping checks nothing, so npm run check runs tsc --noEmit for the types. TypeScript 7.0 (July 2026) made types default to an empty list, so the project’s tsconfig.json lists "types": ["node"].

Get the starter project

The starter project is the code/start/ folder of the course repository. From the repository’s code/ folder, copy it into a folder of its own and make it a Git repository, because this module uses Git history:

cp -R start tinytickets
cd tinytickets
git init -b main
git add .
git commit -m "TinyTickets, year 3"

Start PostgreSQL 18. This is the one docker run command of the course:

docker run -d --rm --name tinytickets-db -e POSTGRES_PASSWORD=tinytickets -p 5546:5432 postgres:18

It runs the official postgres image and maps port 5546 on your laptop to PostgreSQL’s port 5432 in the container. Because of --rm, stopping the container also deletes it and its data. A local PostgreSQL 18 works too; then change the PG... settings in .env and .env.test. Next, create one database for the app and one for the tests:

docker exec tinytickets-db createdb -U postgres tinytickets
docker exec tinytickets-db createdb -U postgres tinytickets_test

Install the packages, create the tables and add the sample data:

cp .env.example .env
npm install
npm run migrate
npm run seed

npm install ends with found 0 vulnerabilities. The other two print this:

> migrate
> node --env-file=.env migrate.ts

Applied 001_create_shows.sql
Applied 002_create_tickets.sql
Applied 003_create_users.sql
Applied 004_create_sessions.sql
Applied 005_create_orders.sql
Applied 006_add_order_to_tickets.sql
Applied 007_create_jobs.sql
Applied 008_add_hold_expires_at_to_orders.sql
Applied 009_create_organizers.sql
Applied 010_add_ticket_kinds.sql
Applied 011_create_door_tickets.sql
Applied 012_create_payouts.sql
The database is up to date.

> seed
> node --env-file=.env seed.ts

Added 12 organizers. Log in as leo@tinytickets.example.

Now check the types and run the tests:

npm run check
npm test

npm run check prints > check and > tsc --noEmit and nothing else, which means no type errors. npm test migrates tinytickets_test and runs 13 tests with the Node.js test runner. Here is the end of its output. The timings come from one run, and yours will differ:

✔ the show page has a form to hold seats (140.849152ms)
✔ a hold leads to the payment page (25.142998ms)
✔ a hold for more seats than are left is refused (4.658589ms)
✔ a webhook without the secret is refused (3.722195ms)
mail: caught an email to ana@tinytickets.example
✔ a paid webhook issues the tickets, and the worker emails them (31.544672ms)
✔ the door admits a ticket once (57.954833ms)
✔ the dashboard shows the organizer's own shows only (41.815038ms)
✔ the dashboard needs a login (1.357571ms)
✔ the site keeps 5% of each ticket (1.271033ms)
✔ the fee is rounded per ticket (0.213215ms)
✔ a $12 ticket costs 1200, 960 for a student, 1700 as VIP (0.909749ms)
✔ one student ticket pays the booking fee (0.181397ms)
✔ four tickets or more pay no booking fee (0.139032ms)
ℹ tests 13
ℹ suites 0
ℹ pass 13
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 592.571938

To try the app in a browser, run three commands in three terminals, as README.md shows. npm run fakes starts the pretend payment and email services, npm run dev starts the web app on port 3000, and npm run worker starts the worker.

These are the files you’ll work in. The tests, fakes.ts, migrate.ts and seed.ts sit beside them:

app.ts  server.ts  worker.ts  config.ts  passwords.ts
routes/      door  holds  organizer  requests  shows  webhooks
services/    email  orders  payments  payouts  pricing  reservations
db/          dashboard  jobs  orders  payouts  pool  shows  tickets  users
jobs/        expire-pending-orders  pay-organizers  send-confirmation
pages/       layout  organizer  shows
migrations/  001_create_shows.sql to 012_create_payouts.sql

Where the code stands

TinyTickets is one Express app and one worker on one server, and both use one PostgreSQL database, where the jobs table is the job queue. Inside, the code is sorted by technical layer: routes, services, SQL queries, worker jobs and pages, about 920 lines in all. Nothing in those folder names says what the business does. Figure 1 shows the parts, and it stays the same for the whole course.

(Buyers)     --+
(Organizers) --+--> [Web app] -----> [[PostgreSQL + job queue]]
(Door staff) --+    [Worker] -------^

Legend, the same in every module
(Name)     people
[Name]     a program or a server
[[Name]]   a place where data is stored
-->        a request, in the direction it travels

Figure 1: one web app and one worker share one database, and every course module changes only the code inside them.

One hold, three names in the code

Leo calls the 10 minutes a buyer gets to pay a hold. Search the code for that idea under each name it might have. This loop lists the files that contain each word:

for word in reservation "pending.?order" hold; do
  echo "== $word"
  grep -rilE "$word" *.ts db jobs migrations pages routes services | sort
done
== reservation
db/orders.ts
pages/shows.ts
routes/holds.ts
services/reservations.ts
== pending.?order
jobs/expire-pending-orders.ts
migrations/008_add_hold_expires_at_to_orders.sql
worker.ts
== hold
app.test.ts
app.ts
db/orders.ts
migrations/008_add_hold_expires_at_to_orders.sql
pages/shows.ts
routes/holds.ts
services/orders.ts

The route and the page say “hold”. The service and the queries say “reservation”. The worker says “pending order”.

Here is how each of the three decides when a hold ends. First, services/reservations.ts (an excerpt, lines 8 and 25):

const RESERVATION_MINUTES = 10;
    expiresAt: new Date(Date.now() + RESERVATION_MINUTES * 60_000),

The route that counts free seats, routes/holds.ts (an excerpt, lines 38 to 43):

  // Seats are taken by paid orders and by holds that have not run out.
  const now = new Date();
  const holds = await listReservationsForShow(show.id);
  const taken = holds
    .filter((hold) => hold.status === "paid" || (hold.status === "pending" && hold.hold_expires_at > now))
    .reduce((sum, hold) => sum + hold.quantity, 0);

And the worker’s job, all of jobs/expire-pending-orders.ts:

import { pool } from "../db/pool.ts";

// A pending order that nobody paid for gives its seats back.
export async function expirePendingOrders(): Promise<void> {
  await pool.query(
    `UPDATE orders SET status = 'cancelled', cancelled_at = now()
     WHERE status = 'pending' AND created_at < now() - interval '10 minutes'`,
  );
}

Pause and predict: Nina sets RESERVATION_MINUTES to 15. A buyer holds a seat at 10:00 and pays at 10:12. What is the order’s status at 10:11, and does the route count that seat as taken?

At 10:11 the order is cancelled. The worker runs every minute and counts 10 minutes from created_at, so it never reads hold_expires_at. The route then sees a cancelled order, so the seat counts as free, and a second buyer holds it. At 10:12 the payment webhook arrives, and markOrderPaid marks the cancelled order paid.

The comment on line 20 of services/orders.ts says that last part is on purpose, and Module 6 changes it. Figure 2 shows the minutes in order.

10:00  (Buyer A)  holds 1 seat         hold_expires_at = 10:15
10:10  [Worker]   cancels A's order    created_at + 10 minutes
10:11  (Buyer B)  holds 1 seat         the route counts A's seat as free
10:12  (Buyer A)  pays                 the webhook marks A's order paid
10:13  (Buyer B)  pays                 two paid tickets, one seat

Figure 2: with 15-minute holds, the worker ends a hold at minute 10, and the seat is sold twice.

Nina searched for the word in the code she was reading, and she found one of the two clocks. Maya set the constant back to 10 that afternoon. The second clock is still there, and the next person who changes the hold will meet the same bug. Before you fix it, the team needs words that mean one thing.

Leo’s words are the domain

The domain is the business, and the model is the part the code keeps

A domain is the area of knowledge and work that a program serves. For TinyTickets, it is selling seats for organizers’ shows, letting buyers in at the door and paying the organizers. This is a different “domain” from tinytickets.example, the DNS name the site runs on.

A domain expert is a person who knows the domain from doing the work. Leo is one, because he has sold tickets for years and knows what a hold is for. Nina and Omar know Express and PostgreSQL, but not why a regular guest needs time to pay.

A model is a chosen set of ideas about the domain that the code uses to solve problems in it. The definition comes from Eric Evans’ Domain-Driven Design Reference (2015, p. vi). A model leaves things out on purpose. TinyTickets’ model has shows, holds, orders and payouts, and nothing about the band’s songs.

This is a different “model” from an ORM model class or a machine learning model.

In TypeScript, the model is the types and functions that carry business meaning. status: "pending" | "paid" | "cancelled" on the order type is a piece of the model, and so is the 10 in RESERVATION_MINUTES. The model costs nothing extra to have, because every app has one. The cost is in making it right, and that takes time with the domain expert.

One language for Leo, the team and the code

A ubiquitous language is a set of words that the team and the domain experts use with the same meaning in speech, in writing and in the code. Evans’ Reference (pp. 3 and 4) describes the problem it solves. Experts speak their jargon, developers speak in design terms, and the code uses neither, so every conversation needs a translation that loses detail. Nina translated “hold” into “reservation”, and she never saw the “pending order” code.

The language works because it makes search work. When Leo says “hold”, a developer can grep for hold and find every rule about holds. Evans says no group’s dialect wins by default. The expert objects to awkward words, and the developers object to words that are ambiguous.

Evans also ties the words to the design:

“Recognize that a change in the language is a change to the model.” (Evans, Domain-Driven Design Reference, pp. 3 and 4)

So a new word is a change to the code, and a rename is part of the method. Figure 3 shows what the starter code does instead.

(Leo)  "A hold is the 10 minutes a buyer gets to pay."

routes/holds.ts                hold           reads hold_expires_at
services/reservations.ts       reservation    sets hold_expires_at
db/orders.ts                   Reservation    the type of every order row
jobs/expire-pending-orders.ts  pending order  counts from created_at

Figure 3: one idea from Leo has three names in the code, and one of them uses a different clock.

The language has a price. A rename touches code, tests, SQL and docs at once, and a long-lived branch will conflict with it. The words also drift unless someone keeps them up to date.

And one word can still mean different things in different parts of the business. “Ticket” means one thing at the door and another in an order, and Module 3 deals with that.

Not every part of TinyTickets needs the same care

A subdomain is one part of the domain with its own job, such as selling seats or paying organizers. Subdomains come in three kinds, and the kind decides how much care a part gets:

  • A core subdomain is the part that makes the business worth having, the reason customers choose it over others.
  • A supporting subdomain is a part the business needs and has to build for itself, but that is not why customers choose it.
  • A generic subdomain is a problem that many businesses share, so a product or a standard solution can handle it.

Figure 4 sorts TinyTickets. Leo built it because his old ticket service took a fee from every ticket and could not hold seats for his regular guests. Selling, with holds, is the reason the site exists.

CORE        Sales: holds, orders, prices
            why Leo left his old ticket service
SUPPORTING  Shows: an organizer's shows and seats
            Door: scanning tickets at the door
            Payouts: paying organizers five days after the show
GENERIC     Payments (a payment provider), email, login and passwords

Figure 4: Sales is core, so the hold gets the team’s best attention; payments are generic, so a provider handles them.

Evans’ Reference (pp. 40 and 41) gives the reasoning. Keep the core small and put the strongest developers on it. For generic parts, consider ready-made solutions and keep them free of your own special cases. This module fixes the hold first because it sits in the core.

The cost is that the sorting is a judgment, and it can be wrong. You could argue that Payouts is core for organizers, because getting paid fast and correctly is why they stay. The DDD Crew’s Core Domain Charts README admits the scoring is “usually quite subjective”.

In TypeScript, nothing changes yet. The four names (Shows, Sales, Door and Payouts) are words for now, and Module 3 turns them into folders.

A glossary file next to the code

A glossary is the written form of the language. No DDD source prescribes a format. The DDD Crew’s Bounded Context Canvas has a “Ubiquitous Language” box that asks for the key terms and what they mean. This course gives each entry four parts:

  1. the term, as Leo says it
  2. one or two sentences of meaning, in Leo’s words
  3. every name the code uses for it: types, functions, files, columns, job kinds
  4. the words to stop using

Words the team has not agreed on yet go under “Open questions”. That keeps a known problem visible without fixing it today.

The file lives in the repository, beside the code, so a rename and its glossary change go into the same pull request. A glossary costs upkeep, and a stale one is worse than none, because people trust it. Evans puts the weight on speech and code, not on documents. So treat the file as an index into the code, and keep it short.

A rename is a change to the model

After the team agrees on a word, Evans’ Reference (pp. 3 and 4) says to refactor the code to match, renaming classes, methods and modules. In a TypeScript app, a word lives in more places than names, and different tools find it in each place (Figure 5).

Where the old word lives Example in TinyTickets What finds it
A type, function or constant Reservation, createReservation tsc: every old use is an error
An import path "../services/reservations.ts" tsc: error TS2307
A string in the code "expire_pending_orders" in worker.ts grep
Rows already stored a queued job with the old kind a migration; at run time, the worker’s error
Docs and comments README.md, code comments grep
A migration already applied 008_add_hold_expires_at_to_orders.sql grep, and then leave it alone

Figure 5: tsc finds every name and import, but strings, stored rows and docs need grep and a migration.

Git history is one more place where a name lives. Git sees a moved file as a deleted file and an added one, and it calls the pair a rename when enough of the file is unchanged. The similarity index is the share of the file that stayed the same, and the default limit is 50% (git diff -M). git log --follow uses it to show a file’s history across a rename (git log).

So if one commit moves a file and changes most of its lines, Git may see a deleted file and a new one. Then --follow stops at the move. Figure 6 compares the two ways for this module’s files and for a small test file.

File Move and new words in one commit Move first, words in a second commit
services/holds.ts (30 lines) 59% similar 100% in the move commit
jobs/expire-holds.ts (9 lines) 63% similar 100% in the move commit
A 7-line file where every line changes under 50%: --follow shows only the last commit 100% in the move commit

Figure 6: moving a file in a commit of its own keeps it 100% similar, so the history survives however many words change.

The first two numbers come from this module’s own commits. The last row comes from a separate test with Git 2.50.1, on a file where every line named the old word. Both TinyTickets files would pass in one commit, at 59% and 63%, close to the 50% limit. So the module moves them first.

Rule: Move a file in one commit and change the words inside it in the next, then let tsc find the names and grep find the strings.

Rename the hold, step by step

Each step says why, what to do, the code, and what you should see. Commit hashes in the outputs come from one run, and yours will differ.

Step 1: Write the glossary

Why: the renames need a target. Maya asked Leo what a hold is, and his answer is the first entry.

What to do: save this file as GLOSSARY.md in the project folder, then commit it.

# TinyTickets glossary

The words Leo and the other organizers use, what each one means, and the
names the code uses for it. When a word changes here, the code changes in
the same pull request.

## Show

Something an organizer sells tickets for, on one date, in one place, with a
number of seats.

- Code: table `shows`, type `Show` (`db/shows.ts`).
- Do not say: event, concert.

## Organizer

A person or a club that sells shows on TinyTickets. Leo is one of 12.

- Code: table `organizers`.

## Buyer

A person who buys tickets for a show.

- Code: `buyer_name` and `buyer_email` on `orders`.

## Hold

The 10 minutes a buyer gets to pay for the seats they chose. While the hold
lasts, nobody else can take those seats. A hold ends when the buyer pays or
when the 10 minutes run out.

- Code: `orders.hold_expires_at`; `HOLD_MINUTES` and `createHold`
  (`services/holds.ts`); the job `expire_holds` (`jobs/expire-holds.ts`).
- Do not say: reservation, pending order.

## Order

What one buyer asks for at one time: one show, a number of tickets of each
kind, and the price. An order starts with a hold. Then it is paid, or it is
cancelled.

- Code: table `orders`, type `Order` (`db/orders.ts`).

## Fee

The 5% of each ticket's price that TinyTickets keeps.

- Code: `SITE_FEE` (`services/payouts.ts`).

## Booking fee

$1.50 that an order of fewer than four tickets pays.

- Code: `orderTotalCents` (`services/pricing.ts`).

## Payout

The money an organizer gets five days after a show: the price of every
ticket sold, minus the fee.

- Code: table `payouts`, `jobs/pay-organizers.ts`.

## Open questions

- **Ticket.** The code uses "ticket" for three things: a row in `tickets`
  (one seat sold, with a code), one line of an order (`Ticket` in
  `services/pricing.ts`, the column `orders.tickets`), and a scan at the
  door (`door_tickets`). Leo means the first one. Not renamed yet.
- **Money.** `shows.price_in_dollars` and `orders.amount_in_dollars` are in
  dollars. Every other amount is in cents. Not changed yet.
git add GLOSSARY.md
git commit -m "Add the glossary"

What you should see:

[main 24065d3] Add the glossary
 1 file changed, 71 insertions(+)
 create mode 100644 GLOSSARY.md

The “Hold” entry already names the code as it will be after Step 6. The two open questions stay open for now. Module 3 settles “ticket”, and Module 5 settles money.

Step 2: Move the files, and let tsc find the imports

Why: a commit with only moves keeps each file 100% similar, so Git can follow its history (Figure 6).

What to do: move the two files whose names use the old words, and type-check.

git mv services/reservations.ts services/holds.ts
git mv jobs/expire-pending-orders.ts jobs/expire-holds.ts
npm run check

What you should see: two errors, one for each file that imports a moved file.

> check
> tsc --noEmit

routes/holds.ts(8,35): error TS2307: Cannot find module '../services/reservations.ts' or its corresponding type declarations.
worker.ts(3,37): error TS2307: Cannot find module './jobs/expire-pending-orders.ts' or its corresponding type declarations.

Fix only the two import paths. In routes/holds.ts, line 8 becomes:

import { createReservation } from "../services/holds.ts";

In worker.ts, line 3 becomes:

import { expirePendingOrders } from "./jobs/expire-holds.ts";

The names inside stay old for now. Run npm run check again (no errors) and npm test (13 pass), then commit:

git add -A
git commit -m "Move the hold files to the glossary's names"
[main ff0c83f] Move the hold files to the glossary's names
 4 files changed, 2 insertions(+), 2 deletions(-)
 rename jobs/{expire-pending-orders.ts => expire-holds.ts} (100%)
 rename services/{reservations.ts => holds.ts} (100%)

(100%) is the similarity index. The moved files did not change at all; only their importers did.

Step 3: Rename the type, and read what tsc says

Why: Reservation is the type of every row in orders, paid and cancelled rows too. In the glossary, that is an order, and a hold is only its first 10 minutes. Renaming the declaration first shows you every place that depends on the old name.

What to do: in db/orders.ts, change line 5, and only line 5, to this:

export type Order = {

Then run npm run check.

What you should see:

> check
> tsc --noEmit

db/orders.ts(15,13): error TS2304: Cannot find name 'Reservation'.
db/orders.ts(16,35): error TS2304: Cannot find name 'Reservation'.
db/orders.ts(34,72): error TS2304: Cannot find name 'Reservation'.
db/orders.ts(35,35): error TS2304: Cannot find name 'Reservation'.
db/orders.ts(42,12): error TS2304: Cannot find name 'Reservation'.
db/orders.ts(43,37): error TS2304: Cannot find name 'Reservation'.
pages/shows.ts(1,15): error TS2305: Module '"../db/orders.ts"' has no exported member 'Reservation'.
pages/shows.ts(42,6): error TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ pending: string; paid: string; cancelled: string; }'.

Seven errors point at an old name, and the last one follows from the import error above it. With Reservation gone, order in orderPage has no type, so order.status is any. Strict mode, on by default in TypeScript 7, refuses to use an any value as a key. Fix the import, and that error goes too.

The editor’s “Rename Symbol” command does this whole step in one action. The tsc run is the check that works in any editor.

Step 4: Rename the rest of the words

Why: every name should now say what the glossary says.

What to do: make these renames, by hand or with your editor.

File Old name New name
db/orders.ts Reservation (all uses) Order
db/orders.ts insertReservation insertOrder
db/orders.ts listReservationsForShow listOrdersForShow
pages/shows.ts Reservation (lines 1 and 37) Order
services/holds.ts RESERVATION_MINUTES HOLD_MINUTES
services/holds.ts createReservation, the variable reservation createHold, order
routes/holds.ts the imports, holds and hold the new names, orders and order

services/holds.ts now reads:

import { randomBytes } from "node:crypto";
import { insertOrder, savePayment } from "../db/orders.ts";
import type { Show } from "../db/shows.ts";
import { createPayment } from "./payments.ts";
import { orderTotalCents } from "./pricing.ts";
import type { Ticket } from "./pricing.ts";

const HOLD_MINUTES = 10;

// Stores the order with its hold and asks the payment service for a payment page.
export async function createHold(
  show: Show,
  buyer: { name: string; email: string },
  tickets: Ticket[],
): Promise<string> {
  const totalCents = orderTotalCents(show.price_in_dollars, tickets);
  const order = await insertOrder({
    token: randomBytes(16).toString("hex"),
    showId: show.id,
    buyerName: buyer.name,
    buyerEmail: buyer.email,
    quantity: tickets.reduce((sum, ticket) => sum + ticket.quantity, 0),
    tickets,
    amountInDollars: totalCents / 100,
    expiresAt: new Date(Date.now() + HOLD_MINUTES * 60_000),
  });
  const payment = await createPayment(totalCents, order.token);
  await savePayment(order.id, payment.id, payment.payUrl);
  return payment.payUrl;
}

In routes/holds.ts, lines 2 and 8 import the new names, and lines 38 to 43 now read (an excerpt):

  // Seats are taken by paid orders and by holds that have not run out.
  const now = new Date();
  const orders = await listOrdersForShow(show.id);
  const taken = orders
    .filter((order) => order.status === "paid" || (order.status === "pending" && order.hold_expires_at > now))
    .reduce((sum, order) => sum + order.quantity, 0);

The old code called this list holds, but it contains paid orders too. With the glossary’s words, the code now says what the comment above it says, that paid orders and holds that have not run out take seats.

What you should see: npm run check prints no errors.

Step 5: Rename the job

Why: the worker’s job is the third name for a hold, and it is a string as well as a function.

What to do: in jobs/expire-holds.ts, rename the function and its comment:

// A hold that has run out gives its seats back.
export async function expireHolds(): Promise<void> {

In worker.ts, rename the import, the handler’s key and the string the worker queues every minute (an excerpt, lines 3, 7 to 11 and 34):

import { expireHolds } from "./jobs/expire-holds.ts";

const handlers: Record<string, (payload: any) => Promise<void>> = {
  send_confirmation: sendConfirmation,
  expire_holds: expireHolds,
  pay_organizers: payOrganizers,
};

  setInterval(() => enqueue("expire_holds", {}), 60 * 1000).unref();

What you should see: npm run check prints no errors. But tsc would print no errors with the old strings either. handlers is a Record<string, ...> and enqueue takes any string, so the key and the queued kind can disagree and still type-check.

A union type such as "send_confirmation" | "expire_holds" | "pay_organizers" on enqueue would let tsc check the code’s strings. It still could not check the rows that are already in the jobs table, and the next step shows why that matters.

Step 6: Watch a queued job fail under its old name

Why: when you deploy, jobs queued by the old worker are still in the table with the old kind. No type can see them, so cause the failure on purpose.

What to do: queue one job under the old name, start the worker, and stop it with Ctrl+C after a few seconds. Then look at the table.

docker exec tinytickets-db psql -U postgres tinytickets -c "INSERT INTO jobs (kind) VALUES ('expire_pending_orders')"
npm run worker
docker exec tinytickets-db psql -U postgres tinytickets -c "SELECT kind, attempts, last_error FROM jobs"

What you should see: the worker prints the error at every attempt (an excerpt; the stack traces are cut, and your job number may differ):

> worker
> node --env-file=.env worker.ts

Worker started.
Job 2 (expire_pending_orders), attempt 1, failed: Error: No handler for jobs of kind expire_pending_orders.
Job 2 (expire_pending_orders), attempt 2, failed: Error: No handler for jobs of kind expire_pending_orders.

And the job waits in the table for its next try:

         kind          | attempts |                        last_error                         
-----------------------+----------+-----------------------------------------------------------
 expire_pending_orders |        2 | Error: No handler for jobs of kind expire_pending_orders.
(1 row)

The runtime check is the throw in runOneJob, and tsc has no part in it. After five attempts, the job becomes a dead job. Here the harm is small, because the new worker queues expire_holds every minute. A renamed send_confirmation job would be worse, because each lost job is a buyer’s lost email.

Step 7: Rename the stored jobs in a migration

Why: the rows need the new kind, and the change must ship with the code that expects it.

What to do: save this as migrations/013_rename_expire_pending_orders_jobs.sql:

-- Year 3: the job that ends holds is now named expire_holds (see GLOSSARY.md).
-- Jobs queued under the old name before the deploy keep working.
UPDATE jobs SET kind = 'expire_holds' WHERE kind = 'expire_pending_orders';

Run the migration, start the worker again for a few seconds, and look at the table:

npm run migrate
npm run worker
docker exec tinytickets-db psql -U postgres tinytickets -c "SELECT kind, attempts, last_error FROM jobs"

What you should see:

> migrate
> node --env-file=.env migrate.ts

Applied 013_rename_expire_pending_orders_jobs.sql
The database is up to date.

> worker
> node --env-file=.env worker.ts

Worker started.
 kind | attempts | last_error 
------+----------+------------
(0 rows)

The renamed job ran and was deleted. On the server, the migration, the web app and the worker must ship in one deploy. A worker left on the old code would queue expire_pending_orders again.

Step 8: Find the strings and docs that are left

Why: tsc passes, but strings and docs still carry the old words.

What to do: search the whole project, Markdown included:

grep -rniE "reservation|pending.?order" README.md GLOSSARY.md *.ts db jobs migrations pages routes services

What you should see:

GLOSSARY.md:35:- Do not say: reservation, pending order.
README.md:82:services/   pricing, reservations, orders, payments, payouts, email
README.md:84:jobs/       what the worker runs: send-confirmation, expire-pending-orders, pay-organizers
migrations/013_rename_expire_pending_orders_jobs.sql:3:UPDATE jobs SET kind = 'expire_holds' WHERE kind = 'expire_pending_orders';
migrations/008_add_hold_expires_at_to_orders.sql:1:-- Year 2: a pending order holds its seats for a limited time.

The glossary and migration 013 name the old words on purpose. Migration 008 has already run on every database, and migrate.ts skips it by name, so leave it as it is. Only README.md needs a change. In its “Files” block, the lines for services/, jobs/ and migrations/ change, and one line is added (an excerpt):

services/   pricing, holds, orders, payments, payouts, email
jobs/       what the worker runs: send-confirmation, expire-holds, pay-organizers
migrations/ 001 to 013, in the order the app grew
GLOSSARY.md the words Leo uses, and their names in the code

Run npm run check (no errors) and npm test. The test run applies migration 013 to the test database first, and all 13 tests pass:

> test
> node --env-file=.env.test migrate.ts && node --env-file=.env.test --test

Applied 013_rename_expire_pending_orders_jobs.sql
The database is up to date.

Commit the words, and then ask Git for the history of the service file:

git add -A
git commit -m "Use the glossary's words for holds and orders"
git log --oneline --follow -- services/holds.ts
3bab637 Use the glossary's words for holds and orders
ff0c83f Move the hold files to the glossary's names
b900293 TinyTickets, year 3

The history reaches back to the starter commit, when the file was still services/reservations.ts. Without --follow, git log stops at the move commit.

Step 9: Read the worker with the glossary open, and break it

Why: with one word for one idea, the bug from Figure 2 is easy to read. The glossary says a hold ends when its 10 minutes run out, and hold_expires_at stores that moment. expireHolds never reads hold_expires_at.

What to do: write a test that ends a hold without waiting 10 minutes. It moves only hold_expires_at into the past, so it passes only if the worker reads that column. Nina’s 15 minutes showed the same gap from the other side, because the worker ended holds before hold_expires_at. In app.test.ts, import the job next to the other imports:

import { expireHolds } from "./jobs/expire-holds.ts";

Then add this test at the end of the file:

test("the worker ends a hold when its time runs out", async () => {
  await post(`/shows/${leoShow}/hold`, { ...buyer, standard: "1" });
  await pool.query("UPDATE orders SET hold_expires_at = now() - interval '1 minute' WHERE status = 'pending'");
  await expireHolds();
  const pending = await pool.query("SELECT count(*)::int AS count FROM orders WHERE status = 'pending'");
  assert.equal(pending.rows[0].count, 0);
});

What you should see: npm test fails one test (an excerpt; the stack trace is cut):

✖ the worker ends a hold when its time runs out (10.66244ms)
ℹ tests 14
ℹ suites 0
ℹ pass 13
ℹ fail 1

✖ failing tests:

test at app.test.ts:150:1
✖ the worker ends a hold when its time runs out (10.66244ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

  1 !== 0

The hold has ended, but the order is still pending, because it was created less than 10 minutes ago.

Step 10: End a hold when hold_expires_at has passed

Why: one hold should have one clock. The route already reads hold_expires_at, so the worker should read it too.

What to do: change the WHERE clause in jobs/expire-holds.ts. The whole file now reads:

import { pool } from "../db/pool.ts";

// A hold that has run out gives its seats back.
export async function expireHolds(): Promise<void> {
  await pool.query(
    `UPDATE orders SET status = 'cancelled', cancelled_at = now()
     WHERE status = 'pending' AND hold_expires_at < now()`,
  );
}

What you should see: npm run check prints no errors, and npm test passes all 14 tests:

✔ the show page has a form to hold seats (127.854611ms)
✔ a hold leads to the payment page (25.763779ms)
✔ a hold for more seats than are left is refused (4.710103ms)
✔ a webhook without the secret is refused (2.46813ms)
mail: caught an email to ana@tinytickets.example
✔ a paid webhook issues the tickets, and the worker emails them (35.460526ms)
✔ the door admits a ticket once (58.635067ms)
✔ the dashboard shows the organizer's own shows only (42.205394ms)
✔ the dashboard needs a login (1.425304ms)
✔ the worker ends a hold when its time runs out (11.194955ms)
✔ the site keeps 5% of each ticket (1.474769ms)
✔ the fee is rounded per ticket (0.199314ms)
✔ a $12 ticket costs 1200, 960 for a student, 1700 as VIP (0.87395ms)
✔ one student ticket pays the booking fee (0.174508ms)
✔ four tickets or more pay no booking fee (0.156886ms)
ℹ tests 14
ℹ suites 0
ℹ pass 14
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 593.896958

Commit it:

git add -A
git commit -m "End a hold when hold_expires_at has passed"
[main ea1363a] End a hold when hold_expires_at has passed
 2 files changed, 10 insertions(+), 1 deletion(-)

If Leo asks for 15-minute holds again, HOLD_MINUTES is now the one place to change.

Two problems from Figure 2 remain. The worker still runs once a minute, so a hold can stay pending for up to a minute after it ends. And a payment that arrives after the hold has ended still marks the order paid. Module 6 handles that.

How a hold works now

Follow one buyer who holds two seats for Leo’s show, through the renamed code (Figure 7):

  1. The buyer fills in the form on /shows/:id and presses “Hold my seats”. The browser sends POST /shows/:id/hold, which routes/holds.ts handles.
  2. The route checks the form, then reads every order of the show with listOrdersForShow. It counts the seats in paid orders and in pending orders whose hold_expires_at is still in the future.
  3. If two seats are free, the route calls createHold in services/holds.ts. It prices the order and calls insertOrder, which stores a pending order with hold_expires_at set HOLD_MINUTES from now.
  4. createHold asks the payment service for a payment page, and the route redirects the buyer there with a 303.
  5. Every minute, the worker queues an expire_holds job and runs expireHolds. It cancels every pending order whose hold_expires_at has passed.
(Buyer) --> [Web app] routes/holds.ts       counts paid orders and holds
                      services/holds.ts     createHold, HOLD_MINUTES = 10
                      db/orders.ts          insertOrder --> [[orders]]
                                                            hold_expires_at
            [Worker]  jobs/expire-holds.ts  expireHolds --> [[orders]]
                      every minute          ends holds past hold_expires_at

Figure 7: the route and the worker both read hold_expires_at, so one hold has one clock and one name.

Going deeper

What Evans wrote, and what came after

Evans’ Reference opens with a three-point summary of DDD (p. 1). Focus on the core domain. Explore models with the people who know the domain. Speak a ubiquitous language within a boundary that is drawn explicitly.

This module covered the first and the third point. Module 2 covers the second, and Module 3 draws the boundary.

Evans names two kinds of subdomain as patterns: the core domain (p. 40) and generic subdomains (p. 41). “Supporting” appears in his Reference only as a plain adjective, for parts that support the core (pp. 40 and 45). The three named kinds are later practice.

They are usually credited to Vaughn Vernon’s Implementing Domain-Driven Design (2013). Vlad Khononov’s Learning Domain-Driven Design (2021) compares the three kinds in its first chapter. The DDD Crew’s Bounded Context Canvas uses the same three in its “Strategic Classification”. It describes them as a key strategic bet, a part that is needed but does not set the business apart, and a capability that many businesses have.

Evans’ Reference also says when the language breaks inside one team. Its Continuous Integration pattern (p. 5) warns that a team of three or four people can already drift apart, and asks for frequent merges and automated tests to catch it. Maya, Nina and Omar are three people, and Step 9’s test is that kind of check.

Rename everything now, or rename at the edges

This module renamed every file and name in one pull request. That fits TinyTickets: about 920 lines, three developers and one deploy for the web app and the worker. In a large codebase with many teams, a single rename across everything conflicts with every open branch.

The alternative is to rename at the edges first. New code uses the new word, a thin mapping layer translates to the old names, and the old names go away over several releases. This is often called “expand and contract”. It costs more code for a while and two names in the codebase until the end.

In PostgreSQL, a column rename faces the same choice. ALTER TABLE ... RENAME has no effect on the stored data, so it is fast. It does take an ACCESS EXCLUSIVE lock, and every running program that still uses the old name fails at once (PostgreSQL 18, ALTER TABLE). This module needed no column rename, because orders.hold_expires_at already used Leo’s word.

What changed recently

  • Evans’ 2015 Reference marks three patterns as new since his book: Domain Events, Partnership and Big Ball of Mud (p. iii).
  • The three named kinds of subdomain are now the default way to teach the split. Microsoft’s Azure Architecture Center page “Use domain analysis to model microservices” (updated February 2026) defines core, supporting and generic that way.
  • Sorting subdomains has moved toward shared visual tools. The DDD Crew’s Core Domain Charts plot each subdomain by how much it sets the business apart and how complex its model is. Both DDD Crew repositories had commits in 2026.
  • On the tool side, TypeScript 7.0 (July 2026) turned strict on by default, which is why Step 3 printed TS7053, and Node.js 26 became LTS in October 2026 (release index).

When a word should stay as it is

Keep the old word, and add it to the glossary, when other systems read it. The payment provider’s field names, a public API, or a table another team queries all fall in this group. Renaming them breaks someone you cannot deploy with. Module 4 shows how to keep such words at the edge of your code.

Skip the rename too when the word appears in a handful of lines that nobody will change again, such as an old migration or a finished one-off script. And leave a word alone while the team still disagrees about it. “Ticket” stays an open question here, because renaming it now would pick a meaning before Module 3 shows there are three.

Check yourself

  1. Which three names does the starter code use for Leo’s “hold”, and which two disagree about when it ends?
Answer

“Hold” (the route and the page), “reservation” (the service and the queries) and “pending order” (the worker). The service sets hold_expires_at from RESERVATION_MINUTES, but the worker counts 10 minutes from created_at.

  1. What does each entry in GLOSSARY.md hold?
Answer

The term as Leo says it, its meaning in Leo’s words, every name the code uses for it, and the words to stop using. Words the team has not agreed on go under “Open questions”.

  1. Which TinyTickets subdomain is core, and why are payments generic?
Answer

Sales, with holds, orders and prices, because selling with holds is why Leo built TinyTickets. Payments are a problem many businesses share, so a payment provider handles them.

  1. Why do you move a file in one commit and change the words inside it in the next?
Answer

Git finds renames by comparing files, and it counts a pair as a rename only if at least 50% is unchanged by default. A move with no edits is 100% similar, so git log --follow keeps the file’s history however much the next commit changes.

  1. Name one place where tsc cannot find a renamed word, and one case where you would keep the old word.
Answer

Strings such as the job kind "expire_pending_orders", rows already stored in the jobs table, SQL text, and docs. Keep the old word when another system reads it, such as the payment provider’s field names or a public API.

Exercise: give the door scan a glossary entry

Door staff type a ticket’s code on the /door page and press “Scan”. Write a glossary entry for “Scan” in the four-part format. Use grep to find every name the code uses for a scan, and decide which subdomain from Figure 4 it belongs to. Don’t rename anything, because the entry is the whole change.

Solution

One search finds the names:

grep -rniE "scan|door_?ticket" *.ts db jobs migrations pages routes services
app.test.ts:26:    `TRUNCATE door_tickets, payouts, tickets, orders, sessions, users, shows,
db/dashboard.ts:5:  tickets_sold: number; gross_cents: number; seats_held: number; scanned: number;
db/dashboard.ts:16:       count(door_tickets.id) AS scanned,
db/dashboard.ts:23:     LEFT JOIN door_tickets ON door_tickets.ticket_code = tickets.code
db/tickets.ts:38:// A door ticket is the stub the door staff tear off: one row per scan.
db/tickets.ts:39:export async function insertDoorTicket(code: string, userId: number): Promise<boolean> {
db/tickets.ts:41:    `INSERT INTO door_tickets (ticket_code, scanned_by) VALUES ($1, $2)
routes/door.ts:2:import { findTicketByCode, insertDoorTicket } from "../db/tickets.ts";
routes/door.ts:26:  if (!(await insertDoorTicket(code, user.id))) {
routes/door.ts:27:    response.status(409).send(doorPage(`Ticket ${code} was already scanned.`));
migrations/011_create_door_tickets.sql:1:-- Year 3: door staff scan tickets with their phones.
migrations/011_create_door_tickets.sql:2:CREATE TABLE door_tickets (
migrations/011_create_door_tickets.sql:5:  scanned_by integer NOT NULL REFERENCES users (id),
migrations/011_create_door_tickets.sql:6:  scanned_at timestamptz NOT NULL DEFAULT now()
pages/organizer.ts:25:  <td>${row.scanned}</td><td>${row.payout_cents === null ? "not yet" : dollars(row.payout_cents)}</td></tr>`,
pages/organizer.ts:45:  <button>Scan</button>

The entry:

## Scan

Door staff enter a ticket's code at the door, and the buyer comes in. A
ticket can be scanned once.

- Code: table `door_tickets` (`scanned_by`, `scanned_at`), `insertDoorTicket`
  (`db/tickets.ts`), the route `POST /door/tickets`, the dashboard column
  `scanned`.
- Do not say: door ticket.

Scanning belongs to Door, a supporting subdomain, because the site needs it but no organizer chooses TinyTickets for it. The code calls a scan a “door ticket”, so this is the third meaning of “ticket” from the open questions. That’s why the entry renames nothing yet.

Cheat sheet

Cheat sheet

  • Domain and model: the business the code serves, and the part of it that the code keeps.
  • Ubiquitous language: one word with one meaning, in the expert’s speech, the glossary and the code.
  • Subdomains: core (why customers come), supporting (needed and your own), generic (shared, so buy it).
  • Glossary entry: the term, its meaning in the expert’s words, its names in the code, the words to stop using.
  • Old words: tsc finds names and imports; grep finds strings, SQL and docs.
  • Stored data: rename it in a migration that ships with the code.
  • Git: git mv in a commit of its own, new words in the next, then check with git log --follow.
  • Keep the old word when another system reads it.

Figure 8 is the whole module in one picture.

Leo says   GLOSSARY.md      Names in the code   What checks them
"hold"     meaning          HOLD_MINUTES        tsc: names, imports
           words to stop    createHold          grep: strings, docs
                            expire_holds        migration: stored jobs
                            hold_expires_at     git mv first: history

Figure 8: one word from the domain expert becomes one glossary entry and one set of names in the code.

The code now has a glossary, one name each for a hold and an order, and one clock for a hold. Next, Module 2 follows a 10:00 sale from the first hold to the payout, because nobody on the team can tell that whole path yet.

Sources