On Monday morning, Leo forwarded an email from a buyer. Ana had a ticket for his Saturday show, and she could no longer come. She wanted to give it to her friend Ben.
“Can she do that?” Leo asked. “And then only Ben gets in?”
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
TinyTickets had no way to do it. This module builds ticket transfers by running the whole Domain-Driven Design (DDD) method once more, on one feature. It goes through the words, the board, the context, the aggregate, the event and the read model. Then it steps back from TinyTickets, to say where DDD costs more than it gives, and in what order to bring it into code you already have.
After this module, you can:
- run the method on a new feature in order: split a word in the glossary, put the feature on the board, and choose its context and its aggregate
- build a small aggregate with a value object, a version check and an event that leaves through the outbox
- tell when a delay between two contexts is harmless and when it lets the wrong person in, and close that gap
- say which DDD tools a part of a system needs, from what each tool cost TinyTickets
- plan the order in which to bring DDD into a codebase that has none
Where the code stands
Module 10 gave Leo’s dashboard its own reads. Each context answers for its own shows, and Sales and Door keep small tables of counts for the page. Sales has one aggregate, the Sale, and its events reach Door through the outbox. Figure 1 is the code figure Module 10 ended with.
{Door} {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Sales} --> {Door} the event TicketsIssued, through the outbox
dashboard/ ..> {Shows}, {Sales}, {Door}, {Payouts} one question to each
{Shows}, {Sales}, {Payouts} ..> money/ the shared kernel (#money)
Inside {Sales}: routes/ ..> wiring.ts ..> application/ ..> domain/
db/, jobs/, acl/ ..> application/; db/, jobs/ ..> domain/
domain/ Sale, Order, pricing, the port SaleRepository,
and the event TicketsIssued
application/ salesService; ports WithTransaction,
startPayment
db/ the PostgreSQL adapters; show-sales.ts reads
the read model sales.show_sales
jobs/ count-sales.ts, the projection
routes/ ..> acl/ ACL ..> [Payment provider]
Inside {Door}: routes/ ..> db/tickets.ts: its own list
db/scans.ts: each scan counts itself in door.show_scans
jobs/add-tickets.ts: TicketsIssued as Door reads it
platform/ the pool, the outbox and its relay, the job queue, settings,
page layout, login, email, the payment provider's client.
Every context and dashboard/ ..> platform/.
worker.ts subscribers: TicketsIssued --> send_confirmation,
add_tickets_at_door, count_sales
Figure 1: the contexts as Module 10 left them; Door imports nothing from Sales, and learns of new tickets through the outbox.
Two people behind one ticket
Today a ticket in TinyTickets is a code. The buyer gets it by email, and the door lets in whoever shows it first. So Ana can already forward her email to Ben.
Pause and predict: Ana forwards her ticket email to Ben, and then decides to come after all. Both of them arrive with the same code. What does the door do, and whose name does TinyTickets keep on the ticket?
The door lets in the first one and refuses the second, because door.scans takes each code once. The test suite already checks this, and it passes on Module 10’s code (an excerpt from one run of npm test):
✔ the door admits a ticket once (53.267498ms)
So the door is fair to codes, not to people. Whoever is in the queue first gets in, and the other one hears “already scanned”. Now look for the name:
grep -rn "buyer_name" src migrations
What you should see:
src/sales/db/orders.ts:10: id: number; token: string; show_id: number; buyer_name: string; buyer_email: string;
src/sales/db/orders.ts:22: buyerName: row.buyer_name, buyerEmail: row.buyer_email, lines: row.lines, totalCents: row.total_cents,
src/sales/db/orders.ts:42: `INSERT INTO sales.orders (token, show_id, buyer_name, buyer_email, quantity,
src/sales/db/tickets.ts:13: `INSERT INTO sales.tickets (show_id, order_id, buyer_name, code, kind, price_cents)
src/sales/db/tickets.ts:14: SELECT show_id, id, buyer_name, $2, $3, $4 FROM sales.orders WHERE token = $1`,
src/sales/jobs/send-confirmation.ts:29: const text = `Hello ${order.buyer_name},
migrations/002_create_tickets.sql:4: buyer_name text NOT NULL,
migrations/005_create_orders.sql:5: buyer_name text NOT NULL,
Both sales.orders and sales.tickets have a buyer_name, and insertTickets copies the order’s into every ticket. Until now that was right, because the person who paid and the person who came in were always the same person. Leo’s question pulls them apart.
Changing the name on Ana’s ticket to Ben would answer none of it. Ana’s code would still work, so “only Ben gets in” would be false. And if Leo ever refunds the show, nobody could say whether the money goes to Ana or to Ben. The code has one word where the business now has two people, and one code where Leo wants the old one to stop working.
Ticket transfers, step by step
Each step reuses one tool from an earlier module and names it. Each says why, what to do, the code, and what you should see.
Work in the project folder Module 10 left. The finished code is in the code/module-11/ folder of the course repository. If you kept the exercise from Module 4, your test counts are one higher.
Step 1: Split “buyer” into purchaser and holder
Why: Module 1’s rule is that the code changes when the words change, in the same pull request. So ask Leo two plain questions first: who gets the money back when a ticket moves, and who gets in. His answers name two people.
A purchaser is the buyer who paid for an order; a refund goes back to the purchaser’s payment. A holder is the person who may enter with a ticket. When tickets are issued, the purchaser holds all of them, and a transfer changes only the holder.
What to do: in GLOSSARY.md, replace the entry “Buyer” with these three:
## Buyer
A person who buys tickets for a show. Since tickets can move, a rule about
"the buyer" must say which person it means: the purchaser or the holder.
- Context: Sales.
- Code: none of its own; see "Purchaser" and "Holder".
## Purchaser
The buyer who paid for an order. A refund goes back to the purchaser's
payment, and a transfer never changes the purchaser.
- Context: Sales.
- Code: `buyer_name` and `buyer_email` on `sales.orders`.
- Do not say: holder, for the person who paid.
## Holder
The person who may enter with a ticket. When the tickets are issued, the
purchaser holds all of them. A transfer gives one ticket to a new holder.
- Context: Sales.
- Code: `holder_name` and `holder_email` on `sales.tickets`, `Holder`
(`src/sales/domain/ticket.ts`).
- Do not say: buyer, for the person on a ticket.
“Buyer” stays, because it is Leo’s word and every page uses it. The entry now sends you to the two precise words. The column on the order keeps its name. Renaming sales.orders.buyer_name would touch the order, its mapping and the email for no gain, because the buyer on an order is the purchaser.
The column on the ticket is the one that changes meaning. Save this migration as migrations/027_name_ticket_holders.sql:
-- Year 3: a ticket can move to another person (see "Purchaser" and "Holder"
-- in GLOSSARY.md). The buyer on the order is the purchaser, and stays. The
-- name on a ticket is its holder's, the person who may enter with it.
ALTER TABLE sales.tickets RENAME COLUMN buyer_name TO holder_name;
ALTER TABLE sales.tickets ADD COLUMN holder_email text;
-- Every ticket sold so far is held by its purchaser.
UPDATE sales.tickets SET holder_email = orders.buyer_email
FROM sales.orders WHERE orders.id = tickets.order_id;
ALTER TABLE sales.tickets ALTER COLUMN holder_email SET NOT NULL;
The UPDATE fills the new column before the NOT NULL, so the tickets sold before the migration get their purchaser as holder. Run npm run check and npm test.
What you should see: no tsc errors, and 12 failing tests (an excerpt):
Applied 027_name_ticket_holders.sql
...
✖ a paid webhook issues the tickets, and the worker emails them (11.622099ms)
error: column "buyer_name" of relation "tickets" does not exist
...
ℹ tests 54
ℹ pass 42
ℹ fail 12
tsc cannot help here, because the column name sits inside a SQL string. The tests that pay for an order are the check that does. In src/sales/db/tickets.ts, insertTickets becomes this (an excerpt):
// Writes the tickets of a paid order. The show and the order's row come from
// the order, and its purchaser is the first holder of every ticket.
export async function insertTickets(client: pg.PoolClient, orderToken: string, tickets: NewTicket[]): Promise<void> {
for (const ticket of tickets) {
await client.query(
`INSERT INTO sales.tickets (show_id, order_id, holder_name, holder_email, code, kind, price_cents)
SELECT show_id, id, buyer_name, buyer_email, $2, $3, $4 FROM sales.orders WHERE token = $1`,
[orderToken, ticket.code, ticket.kind, ticket.priceCents],
);
}
}
No test runs sale-day.ts, so fix its ticket insert by hand too (an excerpt):
`INSERT INTO sales.tickets (show_id, order_id, holder_name, holder_email, code, kind, price_cents)
SELECT show_id, id, 'Buyer', 'buyer@tinytickets.example', 'T' || id || '-' || n, 'standard', 1200
Run npm test again.
What you should see (an excerpt):
✔ a paid webhook issues the tickets, and the worker emails them (39.202516ms)
ℹ tests 54
ℹ suites 0
ℹ pass 54
ℹ fail 0
The cost is the cost of Module 1. A new word reached a migration, an adapter and a script, and only the tests and a grep found every place. Commit:
git add -A
git commit -m "Split the buyer into purchaser and holder"
Step 2: Tell the transfer as a story, then put it on the board
Why: Module 2’s board shows events, policies and open questions before anyone writes code. For one feature and one domain expert, a smaller tool comes first.
Domain Storytelling is a way to model one concrete example as numbered sentences, each starting with an actor who does something with a work object. Stefan Hofer and Henning Schwentner wrote the book on it, and the method’s site has a quick start guide. Each story is one scenario, and the notation has no symbol for “if”, so other cases get their own story.
Module 2 named it as an alternative. Figure 2 is Ana’s transfer, told with Leo, in this course’s symbols.
1 (Ana) gives ticket 4F2A91C0 to (Ben)
2 [TinyTickets] gives the ticket a new code, 7B3E0D15
3 [TinyTickets] emails code 7B3E0D15 to (Ben)
4 (Door staff) scan code 7B3E0D15 and let (Ben) in
5 (Door staff) scan code 4F2A91C0 and turn (Ana) away
Figure 2: one transfer as a domain story; sentences 2 and 5 are Leo’s “only Ben gets in”.
Telling it raised questions one sentence at a time, and Leo answered two of them. Ben does not have to accept the ticket first, because it moves at once. And a ticket can move until the doors open, because after that his staff work from the list they have.
Two questions stayed open. The refund for a cancelled show goes to the purchaser, and nobody knows yet whether the holder gets anything. Nobody knows either who can give a ticket back when Ana types the wrong email. These belong to Leo, so the board keeps them as hotspots and the code does not decide them.
One large ticket seller faces the same split. Ticketmaster’s US help pages say the recipient of a transfer gets a new barcode, and the sender’s tickets stop working. They also say a refund goes to the person who bought the tickets directly.
There, the recipient accepts first, and the sender can cancel until then. Leo chose the simpler rule.
What to do: add this section at the end of BOARD.md:
## When a ticket changes hands
(Holder) --> CMD Transfer ticket
OK Must the new holder accept the ticket first? Leo: no, it moves
at once.
OK Until when can a ticket move? Leo: until the doors open.
EVT Ticket transferred
POL Whenever a ticket is transferred, email the new code to the new
holder
POL Whenever a ticket is transferred, the door lets in the new code
and not the old one
!! A refund goes to the purchaser. When a show is cancelled, does
the holder get anything?
!! Ana types the wrong email. Who can give the ticket back?
OK is new notation, a hotspot that is answered. Add it to the notation list, after the line for !!:
OK Answered in Module 7 a hotspot that is answered, and where
Seven older hotspots are answered by now, and the board still says !! for them. Mark each one OK and name the module that answered it, for example:
OK Two buyers hold the last seat at the same moment. Who gets it?
Answered in Module 7: the Sale and its version.
The other six are these:
- the “Held” column, answered in Module 10
- the payment at 10:12, answered in Module 6
- the email job before the paid order, answered in Module 9
- the booking fee on four tickets, answered in Module 5
- the three meanings of “ticket”, answered in Module 3
- the failed payment after a received one, answered in Module 6
The code/module-11/ folder has the whole file. Then list what is still open:
grep -nE '^ (!!|OK) ' BOARD.md
What you should see:
17: !! Who gets the seat? a hotspot, a problem or an open question
18: OK Answered in Module 7 a hotspot that is answered, and where
26: !! No page in the app adds a show. On the laptop, seed.ts does.
31: !! Leo says big sales open at 10:00. The code has no sale time, so
35: OK Two buyers hold the last seat at the same moment. Who gets it?
37: OK The dashboard's "Held" column and the "Hold my seats" button
42: OK A payment came at 10:12 for a hold that ran out at 10:10 (Kofi).
49: OK The email job is saved before the paid order is. If saving the
52: OK The email adds the booking fee to four tickets. The charge does
58: OK "Ticket" means a seat sold, a line of an order and a scan.
64: !! No event for a refund. What happens when a buyer wants the
77: OK A failed payment can come after a received one. Is a paid
85: OK Must the new holder accept the ticket first? Leo: no, it moves
87: OK Until when can a ticket move? Leo: until the doors open.
93: !! A refund goes to the purchaser. When a show is cancelled, does
95: !! Ana types the wrong email. Who can give the ticket back?
Five hotspots are still open, and three of them are older than this module: adding a show, the sale time and refunds. The new refund question joins the old one, so the board says where the next feature would start. Commit:
git add -A
git commit -m "Add the ticket transfer to the board"
Step 3: Keep the transfer in Sales, in an aggregate of its own
Why: two choices come before any code. Which context owns the feature, and which aggregate keeps its rules?
The context is Sales. A holder is a person on a ticket, and Sales owns sales.tickets and issues the codes. Door knows a code, not a person, and Payouts knows prices.
Module 3’s test for a new context is a word that means something else there, and “holder” means nothing anywhere else. Nothing outside TinyTickets is involved, so Module 4’s anticorruption layer has nothing to protect.
One word does collide. Payouts already says “transfer” for the money sent to an organizer (sendTransfer, transfer_id). Two contexts may use one word in two ways, which is Module 3’s point, so the glossary only has to say so (Step 7).
The DDD Crew’s Bounded Context Canvas (version 5), which Module 3 named, asks what a context receives, sends and decides. Figure 3 fills four of its sections for the part of Sales this module adds.
| Canvas section | Sales, for transfers |
|---|---|
| Inbound communication | the command Transfer ticket, from a holder |
| Outbound communication | the event TicketTransferred, to Door and to the email job |
| Business decisions | a new code per holder; no transfer once the doors open; the purchaser never changes |
| Open questions | a refund for the holder when a show is cancelled; a transfer to a wrong email |
Figure 3: four sections of the canvas, filled for transfers; the open questions are the board’s two hotspots.
The aggregate is the harder choice. Module 7 drew the Sale around one rule: the orders never take more seats than the show has. A transfer changes no seat.
If it went through the Sale, each transfer would read every order of the show and move the show’s one version. At 10:00 it would then wait behind the holds, which Module 7’s exercise measured.
So a ticket becomes an aggregate of its own, as small as Vernon advises. Its rules are one holder and one code at a time, and no transfer once the doors are open. It refers to its show by ID, as Module 7’s rule says, and it reads the time the doors open from Shows. Figure 4 puts the two aggregates side by side.
Ticket (an aggregate root) Sale (an aggregate root)
id 41, show 7, standard show 7: its seats and price
code 4F2A91C0 -- transfer --> its orders: held, paid,
7B3E0D15 cancelled
holder Ana -- transfer --> Ben
Rules one holder and one code at a Rule the orders never take
time; no transfer once the more seats than the
doors are open show has
Version the code it was read with Version sales.sales.version
Figure 4: the Ticket and the Sale; a transfer touches only the left one, and the purchaser stays on the Sale’s order.
Two more choices come from Modules 5 and 6. The ticket’s identity is its id, not its code, because the code is what changes. And the code becomes a value object, because people type it into forms, in small letters and with spaces. Module 5’s brand makes tsc keep a code that was parsed apart from any other string.
What to do: save this as src/sales/domain/ticket-code.ts:
// A ticket's code (see "Ticket" in GLOSSARY.md): eight hex digits in capitals,
// such as 4F2A91C0. Whoever knows the code may enter with the ticket, and may
// give the ticket to someone else.
declare const ticketCodeBrand: unique symbol;
export type TicketCode = string & { readonly [ticketCodeBrand]: true };
// The only way to make a TicketCode. Accepts small letters and spaces around
// the code, as people type it, and throws on anything else.
export function parseTicketCode(input: string): TicketCode {
const code = input.trim().toUpperCase();
if (!/^[0-9A-F]{8}$/.test(code)) {
throw new RangeError(`Not a ticket code: ${JSON.stringify(input)}`);
}
return code as TicketCode;
}
Eight hex digits is what randomBytes(4).toString("hex") makes, which is how TinyTickets has made codes since the starter project. Add the event at the end of src/sales/domain/events.ts:
// "Ticket transferred" on the board: a ticket moved to a new holder, with a
// new code. The old code no longer lets anyone in.
export type TicketTransferred = {
readonly type: "TicketTransferred";
readonly showId: number;
readonly ticketId: number;
readonly kind: TicketKind;
readonly oldCode: string;
readonly newCode: string;
readonly holder: { readonly name: string; readonly email: string };
readonly occurredAt: Date;
};
The event carries both codes, because Door must drop one and add the other, and the new holder, because someone must email them. It carries no price and no purchaser, since no reader needs them. Save the aggregate as src/sales/domain/ticket.ts:
import type { TicketTransferred } from "./events.ts";
import type { TicketKind } from "./pricing.ts";
import type { TicketCode } from "./ticket-code.ts";
// The person who may enter with a ticket (see "Holder" in GLOSSARY.md).
export type Holder = { readonly name: string; readonly email: string };
export type TransferOutcome = "transferred" | "too late";
// A ticket in Sales: one seat sold on a paid order, held by one person, who
// enters with its code. It is an aggregate of its own, apart from the Sale,
// because a transfer changes the holder and the code and never a seat. The
// rules it keeps: one holder and one code at a time, and no transfer once the
// doors are open.
export class Ticket {
readonly id: number;
readonly showId: number;
readonly kind: TicketKind;
// The code the ticket had when it was read. A repository saves the ticket
// only if its stored code is still this one, so the code works as a version.
readonly loadedCode: TicketCode;
readonly #doorsOpenAt: Date;
#code: TicketCode;
#holder: Holder;
readonly #events: TicketTransferred[] = [];
private constructor(id: number, showId: number, kind: TicketKind, code: TicketCode, holder: Holder, doorsOpenAt: Date) {
this.id = id;
this.showId = showId;
this.kind = kind;
this.loadedCode = code;
this.#code = code;
this.#holder = holder;
this.#doorsOpenAt = doorsOpenAt;
}
// A ticket read back from storage, with the time its show's doors open.
static restore(id: number, showId: number, kind: TicketKind, code: TicketCode, holder: Holder, doorsOpenAt: Date): Ticket {
return new Ticket(id, showId, kind, code, holder, doorsOpenAt);
}
get code(): TicketCode {
return this.#code;
}
get holder(): Holder {
return this.#holder;
}
// Leo's rules: a ticket moves to a new holder until the doors open, and it
// gets a new code, so the old one stops working. The purchaser stays on the
// order, so a refund still goes to the person who paid.
transfer(to: Holder, newCode: TicketCode, now: Date): TransferOutcome {
if (now >= this.#doorsOpenAt) {
return "too late";
}
const oldCode = this.#code;
this.#code = newCode;
this.#holder = to;
this.#events.push({
type: "TicketTransferred", showId: this.showId, ticketId: this.id, kind: this.kind,
oldCode, newCode, holder: to, occurredAt: now,
});
return "transferred";
}
// What a repository must write when it saves this ticket.
changes(): { events: TicketTransferred[] } {
return { events: [...this.#events] };
}
}
Notice three things:
- It follows the shape of the
Sale: a private constructor,restore, private fields, andchanges()for the repository. The new holder’s code comes in as a parameter, asissueTicketstakesnewCode, so the domain makes no random numbers. loadedCodeis the version. Module 7 added aversioncolumn to the sale, but a ticket already has a value that every transfer changes. Step 5 shows why it matters.Holderis a plain readonly type with no identity, a value. It has no parse function, because only the form route makes one, and the route checks the two fields, as the hold route does.
Then the tests, with no database. Save this as src/sales/domain/ticket.test.ts:
import assert from "node:assert/strict";
import { test } from "node:test";
import { Ticket } from "./ticket.ts";
import { parseTicketCode } from "./ticket-code.ts";
const ana = { name: "Ana", email: "ana@tinytickets.example" };
const ben = { name: "Ben", email: "ben@tinytickets.example" };
const doorsOpen = new Date("2027-03-14T19:00:00Z");
const anasTicket = () => Ticket.restore(41, 7, "standard", parseTicketCode("4F2A91C0"), ana, doorsOpen);
test("a ticket code is eight hex digits, and small letters are read as capitals", () => {
assert.equal(parseTicketCode(" 4f2a91c0 "), "4F2A91C0");
assert.throws(() => parseTicketCode("4F2A"), /Not a ticket code/);
});
test("a transfer gives the ticket a new holder and a new code", () => {
const ticket = anasTicket();
const outcome = ticket.transfer(ben, parseTicketCode("7B3E0D15"), new Date("2027-03-14T18:00:00Z"));
assert.deepEqual([outcome, ticket.holder.name, ticket.code, ticket.loadedCode], ["transferred", "Ben", "7B3E0D15", "4F2A91C0"]);
});
test("a transfer records TicketTransferred with the old and the new code", () => {
const ticket = anasTicket();
const at = new Date("2027-03-14T18:00:00Z");
ticket.transfer(ben, parseTicketCode("7B3E0D15"), at);
assert.deepEqual(ticket.changes().events, [{
type: "TicketTransferred", showId: 7, ticketId: 41, kind: "standard",
oldCode: "4F2A91C0", newCode: "7B3E0D15", holder: ben, occurredAt: at,
}]);
});
test("a ticket does not move once the doors are open", () => {
const ticket = anasTicket();
assert.equal(ticket.transfer(ben, parseTicketCode("7B3E0D15"), doorsOpen), "too late");
assert.deepEqual([ticket.holder.name, ticket.code, ticket.changes().events], ["Ana", "4F2A91C0", []]);
});
Run npm run check and npm run test:fast.
What you should see: no tsc errors, and every fast test passes (an excerpt):
✔ a ticket code is eight hex digits, and small letters are read as capitals (1.463575ms)
✔ a transfer gives the ticket a new holder and a new code (0.822373ms)
✔ a transfer records TicketTransferred with the old and the new code (0.24005ms)
✔ a ticket does not move once the doors are open (0.187496ms)
✔ a context imports another context only through its # entry (14.146404ms)
✔ domain/ and application/ import nothing from the outside world (4.279129ms)
ℹ tests 33
ℹ suites 0
ℹ pass 33
ℹ fail 0
The boundary test from Module 8 passes, because ticket.ts and ticket-code.ts import only domain/. The cost is a second aggregate in Sales, with its own repository to come. A rule that needs a ticket and its order together, such as a refund, now spans two aggregates. Commit:
git add -A
git commit -m "Make the ticket an aggregate with a code and a transfer"
Step 4: Store the ticket through a port
Why: Module 8 keeps PostgreSQL behind a port, one repository per aggregate. The application service loads the ticket, calls its method, and saves it in one transaction.
What to do: save the port as src/sales/domain/ticket-repository.ts:
import type { Ticket } from "./ticket.ts";
import type { TicketCode } from "./ticket-code.ts";
// The port through which Sales stores its tickets as aggregates.
export interface TicketRepository {
// The ticket that has this code now, or undefined when no ticket has it.
ticketOf(code: TicketCode): Promise<Ticket | undefined>;
// Saves the ticket and its events. Throws TicketChangedError when another
// copy of the ticket was saved after this one was loaded.
save(ticket: Ticket): Promise<void>;
}
export class TicketChangedError extends Error {}
The repository finds a ticket by its current code, because the code is all a holder has. A code that a transfer replaced finds nothing, which is Leo’s “only Ben” on the Sales side.
In src/sales/application/sales.ts, import Holder, parseTicketCode, TicketCode and TicketRepository from the new domain files. Then add the repository to the transaction, make new codes through the parser, and add the command (three excerpts):
export type SalesTransaction = {
sales: SaleRepository;
tickets: TicketRepository;
export type TransferResult = "transferred" | "too late" | "no such ticket";
const newTicketCode = () => parseTicketCode(randomBytes(4).toString("hex"));
// The holder of a ticket gives it to someone else. A second transfer of
// the same code finds no ticket, because the first one changed the code.
async transferTicket(code: TicketCode, to: Holder): Promise<TransferResult> {
return inTransaction(async ({ tickets }) => {
const ticket = await tickets.ticketOf(code);
if (ticket === undefined) {
return "no such ticket";
}
const outcome = ticket.transfer(to, newTicketCode(), deps.now());
if (outcome === "transferred") {
await tickets.save(ticket);
}
return outcome;
});
},
Put transferTicket before cancelOrder. issueTickets takes () => string, and a TicketCode is a string, so it takes the new newTicketCode without a change.
Now the PostgreSQL adapter. Write save the way saveOrderState writes an order, with one UPDATE. Save this as src/sales/db/ticket-repository.ts:
import type pg from "pg";
import { writeToOutbox } from "#platform";
import { findShow } from "#shows";
import type { TicketKind } from "../domain/pricing.ts";
import { Ticket } from "../domain/ticket.ts";
import { parseTicketCode } from "../domain/ticket-code.ts";
import type { TicketRepository } from "../domain/ticket-repository.ts";
type TicketRow = { id: number; show_id: number; kind: TicketKind; code: string; holder_name: string; holder_email: string };
// The PostgreSQL adapter for the TicketRepository port, on the client of one
// transaction.
export function postgresTicketRepository(client: pg.PoolClient): TicketRepository {
return {
async ticketOf(code) {
const result = await client.query<TicketRow>(
"SELECT id, show_id, kind, code, holder_name, holder_email FROM sales.tickets WHERE code = $1",
[code],
);
const row = result.rows[0];
if (row === undefined) {
return undefined;
}
// Shows keeps no time zone, so the doors open in the server's local time.
const show = (await findShow(row.show_id, client))!;
const doorsOpenAt = new Date(`${show.show_date}T${show.doors_open}`);
const holder = { name: row.holder_name, email: row.holder_email };
return Ticket.restore(row.id, row.show_id, row.kind, parseTicketCode(row.code), holder, doorsOpenAt);
},
async save(ticket) {
await client.query(
"UPDATE sales.tickets SET code = $2, holder_name = $3, holder_email = $4 WHERE id = $1",
[ticket.id, ticket.code, ticket.holder.name, ticket.holder.email],
);
for (const event of ticket.changes().events) {
await writeToOutbox(client, event.type, event);
}
},
};
}
save writes the events to the outbox on the transaction’s client, as the Sale‘s repository has done since Module 9. findShow reads the doors-open time on the same client, as Module 8 asked. Run npm run check.
What you should see:
src/sales/application/in-memory.ts(32,10): error TS2741: Property 'tickets' is missing in type '{ sales: { saleOf: (showId: number) => Promise<Sale | undefined>; saleOfOrder: (token: string) => Promise<Sale | undefined>; save: (sale: Sale) => Promise<...>; }; saveTickets: (orderToken: string, newTickets: NewTicket[]) => Promise<...>; }' but required in type 'SalesTransaction'.
src/sales/db/transaction.ts(13,31): error TS2741: Property 'tickets' is missing in type '{ sales: SaleRepository; saveTickets: (orderToken: string, tickets: NewTicket[]) => Promise<void>; }' but required in type 'SalesTransaction'.
tsc names the two adapters of WithTransaction, which must now hand out a TicketRepository. In src/sales/db/transaction.ts, import postgresTicketRepository from ./ticket-repository.ts and add it to the work’s object (an excerpt):
sales: postgresSaleRepository(client),
tickets: postgresTicketRepository(client),
In src/sales/application/in-memory.ts, add this before saveTickets (an excerpt):
// shortcut: no ticket aggregates in memory; transfers are tested
// against PostgreSQL in app.test.ts. Add them when a fast test needs one.
tickets: {
ticketOf: async () => {
throw new Error("The in-memory adapter keeps no tickets to transfer.");
},
save: async () => {
throw new Error("The in-memory adapter keeps no tickets to transfer.");
},
},
This is Module 8’s cost of a fake. A real in-memory ticket store would need the shows’ doors-open times, which the fake does not keep. So it throws, instead of answering “no such ticket” and passing a test it should fail. Run npm run check (no errors) and npm test: all 58 pass, with the four new domain tests. Commit:
git add -A
git commit -m "Store tickets through a TicketRepository port"
Step 5: Give holders a page, and let two transfers race
Why: holders need a form. And Module 7’s question returns for the new aggregate: what happens when two requests change the same ticket at once?
What to do: save the page as src/sales/pages/tickets.ts:
import { layout, notice } from "#platform";
export function transferPage(message: string): string {
return layout(
"Give a ticket",
`<h1>Give a ticket to someone else</h1>
<p>The ticket gets a new code, which we email to its new holder. Your code
stops working at once. Tickets can move until the doors open.</p>
${notice(message)}
<form method="post" action="/tickets/transfer">
<label>Your ticket code <input name="code" required></label>
<label>Their name <input name="name" required></label>
<label>Their email <input name="email" type="email" required></label>
<button>Give this ticket</button>
</form>`,
);
}
Write the route in src/sales/routes/tickets.ts, and first pass the form’s text straight to the command (an excerpt of that first version):
const code = formText(request, "code");
const outcome = await sales.transferTicket(code, { name, email });
Run npm run check.
What you should see:
src/sales/routes/tickets.ts(20,46): error TS2345: Argument of type 'string' is not assignable to parameter of type 'TicketCode'.
Type 'string' is not assignable to type '{ readonly [ticketCodeBrand]: true; }'.
This is the brand at work. A code typed as “4f2a91c0 ” would find no ticket, and tsc will not let raw form text reach the command. Parse it once, at the edge, as Module 5 did for money. The route becomes this:
import express from "express";
import { formText } from "#platform";
import { transferPage } from "../pages/tickets.ts";
import { parseTicketCode } from "../domain/ticket-code.ts";
import type { TicketCode } from "../domain/ticket-code.ts";
import { sales } from "../wiring.ts";
export const ticketRoutes = express.Router();
ticketRoutes.get("/tickets/transfer", (request, response) => {
response.send(transferPage(""));
});
ticketRoutes.post("/tickets/transfer", async (request, response) => {
let code: TicketCode;
try {
code = parseTicketCode(formText(request, "code"));
} catch {
response.status(400).send(transferPage("A ticket code has eight letters and digits."));
return;
}
const name = formText(request, "name");
const email = formText(request, "email");
if (name === "" || !email.includes("@")) {
response.status(400).send(transferPage("Enter the name and the email of the new holder."));
return;
}
const outcome = await sales.transferTicket(code, { name, email });
if (outcome === "no such ticket") {
response.status(404).send(transferPage(`No ticket has the code ${code}.`));
return;
}
if (outcome === "too late") {
response.status(409).send(transferPage("The doors are open, so this ticket can no longer move."));
return;
}
response.send(transferPage(`The ticket is now ${name}'s. We are emailing the new code to ${email}.`));
});
Wire it in:
- In
src/sales/index.ts, addexport { ticketRoutes } from "./routes/tickets.ts";after the line forshowRoutes. - In
app.ts, importticketRoutesfrom#saleswith the other Sales routes, and put it afterholdRoutesinapp.use.
Holders also need to find the page. In src/sales/jobs/send-confirmation.ts, import config from #platform with sendEmail, and end the ticket email like this (an excerpt):
Show a code at the door. To give a ticket to someone else, go to
${config.siteUrl}/tickets/transfer before the doors open.
TinyTickets`;
Now the race. Ana opens the page twice, gives the ticket to Ben in one tab and to Cleo in the other, and presses both buttons at once. Add this test at the end of app.test.ts:
// Ana gives her ticket to Ben and to Cleo at the same moment.
test("two transfers of one ticket at once move it once", async () => {
const show = await pool.query<{ id: number }>(
`INSERT INTO shows.shows (organizer_id, name, show_date, doors_open, place, seats, price_cents)
VALUES (1, 'Gift Show', current_date + 30, '19:00', 'Test Club', 10, 1200)
RETURNING id`,
);
await post(`/shows/${show.rows[0]!.id}/hold`, { ...buyer, standard: "1" });
const order = await pool.query("SELECT token, payment_id FROM sales.orders ORDER BY id DESC LIMIT 1");
const { token, payment_id } = order.rows[0];
await webhook({
id: "evt_15",
type: "payment.succeeded",
data: { payment_id, amount_cents: 1350, currency: "usd", metadata: { order_ref: token } },
});
const ticket = await pool.query("SELECT code FROM sales.tickets ORDER BY id DESC LIMIT 1");
const code = ticket.rows[0].code;
const answers = await Promise.all([
post("/tickets/transfer", { code, name: "Ben", email: "ben@tinytickets.example" }),
post("/tickets/transfer", { code, name: "Cleo", email: "cleo@tinytickets.example" }),
]);
const events = await pool.query("SELECT count(*)::int AS count FROM outbox WHERE type = 'TicketTransferred'");
assert.deepEqual([answers.map((answer) => answer.status).sort(), events.rows[0].count], [[200, 404], 1]);
});
Pause and predict: both requests read the ticket with Ana’s code before either one commits. What do Ana’s two tabs say, and how many TicketTransferred events wait in the outbox?
Run npm run check (no errors) and npm test.
What you should see (an excerpt):
✖ two transfers of one ticket at once move it once (31.592547ms)
ℹ tests 59
ℹ pass 58
ℹ fail 1
...
actual: [ [ 200, 200 ], 2 ],
expected: [ [ 200, 404 ], 1 ],
Both tabs said “the ticket is now theirs”, and two events wait to email two new codes. Only one code is in sales.tickets, the one whose UPDATE ran last. So either Ben or Cleo would get a code that never works.
A race can also come out the other way, if one request commits before the other reads, so this test can pass by luck. It failed in every run made for this module.
saveOrderState needs no check, because every order changes through the Sale, and the sale’s version protects it. A ticket now lives outside the Sale, so nothing protects it. Commit the failing test.
The fix is Module 7’s optimistic check, with the old code as the version. Replace save in src/sales/db/ticket-repository.ts, and import TicketChangedError from ../domain/ticket-repository.ts (an excerpt):
// Only if the stored code is still the one this copy read: a second
// transfer of the same ticket fails here, before it writes an event.
async save(ticket) {
const result = await client.query(
"UPDATE sales.tickets SET code = $3, holder_name = $4, holder_email = $5 WHERE id = $1 AND code = $2",
[ticket.id, ticket.loadedCode, ticket.code, ticket.holder.name, ticket.holder.email],
);
if (result.rowCount === 0) {
throw new TicketChangedError(`Ticket ${ticket.id} changed after it was read with code ${ticket.loadedCode}.`);
}
for (const event of ticket.changes().events) {
await writeToOutbox(client, event.type, event);
}
},
Under Read Committed, the second UPDATE waits for the first one’s row lock, as the PostgreSQL docs on isolation describe. After the first commits, PostgreSQL checks the WHERE again against the new row, finds another code, and updates nothing.
Then let inTransaction try again on this error too. In src/sales/application/sales.ts, import TicketChangedError and change its check (an excerpt):
const changed = error instanceof SaleChangedError || error instanceof TicketChangedError;
if (!changed || attempt === ATTEMPTS) {
On the second try, ticketOf looks for Ana’s old code and finds no ticket, so the tab that lost says “No ticket has the code”, with a 404. Run npm run check and npm test.
What you should see: no tsc errors, and every test passes (an excerpt):
✔ two transfers of one ticket at once move it once (32.570706ms)
ℹ tests 59
ℹ suites 0
ℹ pass 59
ℹ fail 0
Commit:
git add -A
git commit -m "Give holders a transfer page, and check the code when a ticket is saved"
Step 6: Publish TicketTransferred, and close the door to the old code
Why: the board has two policies after “Ticket transferred”: email the new holder, and let the door take the new code instead of the old one. Module 9 built the way to do both without Sales knowing who reacts: an event in the outbox, and one job per subscriber.
What to do: save the email job as src/sales/jobs/send-transferred-ticket.ts:
import { findShow } from "#shows";
import { sendEmail } from "#platform";
// The fields this job reads from TicketTransferred.
type TicketTransferred = { showId: number; kind: string; newCode: string; holder: { name: string; email: string } };
// Emails the new code to the ticket's new holder. Like the ticket email, it
// is sent at least once: a crash after the send sends it again.
export async function sendTransferredTicket(event: TicketTransferred): Promise<void> {
const show = (await findShow(event.showId))!;
const text = `Hello ${event.holder.name},
A ticket for ${show.name} on ${show.show_date}, doors open at ${show.doors_open}, ${show.place}, is now yours.
Your ticket code:
${event.newCode} (${event.kind})
Show the code at the door.
TinyTickets`;
await sendEmail(event.holder.email, `A ticket for ${show.name}`, text);
}
Export it from src/sales/index.ts with export { sendTransferredTicket } from "./jobs/send-transferred-ticket.ts";. Door’s side has two parts. Add this to src/door/db/tickets.ts:
// Takes a code off the list, after its ticket moved to a new holder.
export async function removeTicket(code: string): Promise<void> {
await pool.query("DELETE FROM door.tickets WHERE code = $1", [code]);
}
Then save the job as src/door/jobs/move-ticket.ts, and export it from src/door/index.ts with export { moveTicketAtDoor } from "./jobs/move-ticket.ts";:
import { addTickets, removeTicket } from "../db/tickets.ts";
// The fields Door reads from Sales' event TicketTransferred.
type TicketTransferred = { showId: number; kind: string; oldCode: string; newCode: string };
// Whenever a ticket moves to a new holder, Door lets in the new code instead
// of the old one. Both statements are safe to repeat.
export async function moveTicketAtDoor(event: TicketTransferred): Promise<void> {
await removeTicket(event.oldCode);
await addTickets(event.showId, [{ code: event.newCode, kind: event.kind }]);
}
Door writes down the four fields it reads, as add-tickets.ts does, and imports nothing from Sales. A second run deletes nothing and adds nothing, because addTickets skips a code it has. In worker.ts, import the two jobs, subscribe them, and give them handlers (two excerpts):
TicketsIssued: ["send_confirmation", "add_tickets_at_door", "count_sales"],
TicketTransferred: ["send_transferred_ticket", "move_ticket_at_door"],
send_transferred_ticket: sendTransferredTicket,
move_ticket_at_door: moveTicketAtDoor,
Omar wrote the test the second policy asks for. It follows Ana’s ticket to the door, scans her old code right after the transfer, and then Ben’s new code after the worker’s pass. It ends by reading Leo’s dashboard. Add it at the end of app.test.ts:
// Omar's test: once Ana has given her ticket to Ben, her old code must not
// get in, and Ben's new code must.
test("after a transfer the door refuses the old code and admits the new one", async () => {
const cookie = await logIn();
const show = await pool.query<{ id: number }>(
`INSERT INTO shows.shows (organizer_id, name, show_date, doors_open, place, seats, price_cents)
VALUES (1, 'Transfer Show', current_date + 30, '19:00', 'Test Club', 10, 1200)
RETURNING id`,
);
const showId = show.rows[0]!.id;
await post(`/shows/${showId}/hold`, { ...buyer, standard: "1" });
const order = await pool.query("SELECT token, payment_id FROM sales.orders ORDER BY id DESC LIMIT 1");
const { token, payment_id } = order.rows[0];
await webhook({
id: "evt_16",
type: "payment.succeeded",
data: { payment_id, amount_cents: 1350, currency: "usd", metadata: { order_ref: token } },
});
await runWorker();
const ticket = await pool.query("SELECT code FROM sales.tickets ORDER BY id DESC LIMIT 1");
const oldCode = ticket.rows[0].code;
const ben = { name: "Ben", email: "ben@tinytickets.example" };
const transfer = await post("/tickets/transfer", { code: oldCode, ...ben });
const oldCodeAtDoor = await post("/door/tickets", { code: oldCode }, cookie);
await runWorker();
const newCode = emails.at(-1)!.text.match(/^([0-9A-F]{8}) \(standard\)$/m)![1]!;
const newCodeAtDoor = await post("/door/tickets", { code: newCode }, cookie);
const row = (await loadDashboard(1)).find((one) => one.show_id === showId)!;
assert.deepEqual(
[transfer.status, oldCodeAtDoor.status, newCodeAtDoor.status, row.tickets_sold, row.scanned],
[200, 404, 200, 1, 1],
);
});
The new code comes from the email, because that is the only place Ben gets it. Run npm run check (no errors) and npm test.
What you should see (an excerpt):
✖ after a transfer the door refuses the old code and admits the new one (120.818266ms)
ℹ tests 60
ℹ pass 59
ℹ fail 1
...
actual: [ 200, 200, 200, 1, 2 ],
expected: [ 200, 404, 200, 1, 1 ],
One ticket sold, two people in. Ana’s old code worked at the door, and after the worker’s pass Ben’s new code worked too. The dashboard counted both scans, correctly, because two people did get in. Figure 5 shows the moment.
Sales: sales.tickets Door: door.tickets at the door
before 4F2A91C0, Ana 4F2A91C0
transfer 7B3E0D15, Ben COMMIT 4F2A91C0 (Ana) 4F2A91C0: 200
worker 7B3E0D15, Ben 7B3E0D15 (Ben) 7B3E0D15: 200
Figure 5: between the transfer’s commit and the worker’s pass, Door’s list still holds the old code.
This is the eventual consistency of Module 9, unchanged. What changed is its direction. For a new ticket, Door’s lag refuses: a buyer who paid a second ago waits at the door until the worker comes round, which is safe. For a transfer, Door’s lag admits: the code that should be dead still works.
Here the delay between two contexts is a security question, not a display question.
There are three ways to close it:
- Close transfers earlier. A cut-off an hour before the doors open makes the gap rarer, but it only works while the worker is less than an hour behind. A worker that is down or busy at 18:59 lets the old code in.
- Change Door’s list in the transfer’s transaction. Sales would call Door’s code on its own client. Sales would then know who reacts to a transfer, which Module 9 removed, and every new reaction would join the command.
- Let Door ask Sales at each scan. Sales changes the code in the same transaction as the transfer, so its answer never lags. Door still learns new codes through the outbox, where waiting is safe.
TinyTickets takes the third. The answer that must never lag already lives in one aggregate, so the door asks it. Add this to src/sales/db/tickets.ts:
// Door's question at each scan: does a ticket have this code right now? A
// transfer changes the code in the same transaction, so the answer never lags.
export async function isTicketCodeValid(code: string): Promise<boolean> {
const result = await pool.query("SELECT 1 FROM sales.tickets WHERE code = $1", [code]);
return result.rowCount === 1;
}
In src/sales/index.ts, export it with listSoldTicketPrices:
export { isTicketCodeValid, listSoldTicketPrices } from "./db/tickets.ts";
In src/door/routes/door.ts, import it with import { isTicketCodeValid } from "#sales";, and ask it after the check of the organizer and before insertScan (an excerpt):
// Door's own list learns of a transfer when the worker comes round, so it
// asks Sales whether the code still belongs to a ticket.
if (!(await isTicketCodeValid(code))) {
response.status(404).send(doorPage(`Ticket ${code} was given to someone else. Its code no longer works.`));
return;
}
Run npm run check and npm test.
What you should see: no tsc errors, and every test passes (an excerpt):
✔ the door admits a ticket once (67.115837ms)
...
✔ the door lets a new ticket in once the worker has run (94.442321ms)
...
✔ after a transfer the door refuses the old code and admits the new one (123.02124ms)
ℹ tests 60
ℹ suites 0
ℹ pass 60
ℹ fail 0
The door now refuses when either side says no: Door’s list, for a code it has not heard of, and Sales, for a code that moved. The boundary test still passes, because Door imports #sales, the public entry.
The costs are real. Door depends on Sales again, for one yes-or-no question, after Module 9 had removed its last import. Each scan runs one more query, on the unique index of sales.tickets (code).
The question and the scan are two statements, so a transfer that commits between them lets the old code in once. The cut-off keeps that out of a show, but only while staff scan after the doors open, and the code does not check that.
One read model could have changed, and it did not need to. A transfer changes no order, so count_sales counts the same tickets, and each scan still counts itself in door.show_scans. The last number in the test, one scan, is the read model’s answer. Commit:
git add -A
git commit -m "Publish TicketTransferred, and let the door check each code with Sales"
Step 7: Update the glossary, the board, the map and the code figure
Why: the words, the board and the map must match the code on the day of the commit, as Modules 1, 2 and 4 set up.
What to do: in GLOSSARY.md, add these two entries at the end:
## Transfer
The holder of a ticket gives it to someone else, by their name and email,
until the doors open. The ticket gets a new code, the old code stops
working at once, and the new holder gets the new code by email. Nothing is
paid, and the purchaser stays the same.
- Context: Sales. In Payouts, a transfer is the money sent to an organizer
(`sendTransfer`, `transfer_id`); the two meanings never meet in one
context.
- Code: `Ticket.transfer`, `transferTicket`
(`src/sales/application/sales.ts`), the page `GET /tickets/transfer`.
## Ticket transferred
The event that happens when a ticket moves to a new holder.
- Context: Sales records it; Sales and Door react to it.
- Code: type `TicketTransferred` (`src/sales/domain/events.ts`), recorded
by `Ticket.transfer` and saved with the ticket in table `outbox`. The
worker turns it into the jobs `send_transferred_ticket` (Sales) and
`move_ticket_at_door` (Door).
In “Ticket”, the Sales meaning becomes this:
- In Sales: one seat sold on a paid order, with a code, a kind, a price and
a holder. A transfer gives it a new holder and a new code. Code: table
`sales.tickets`, the aggregate `Ticket` (`src/sales/domain/ticket.ts`),
the value `TicketCode` (`src/sales/domain/ticket-code.ts`).
In “Scan”, add this sentence to the end of the code line (an excerpt):
Each scan also adds one to its show's count in `door.show_scans`. Before
it lets anyone in, the door asks Sales whether the code still belongs to a
ticket (`isTicketCodeValid`).
In BOARD.md, write down what Omar’s test found, after the second policy of “When a ticket changes hands”:
OK The door's list changes when the worker comes round, so the old
code still got in (Omar). Answered in Module 11: the door asks
Sales about each code.
In CONTEXT-MAP.md, the event line now names both events, and Door has a new arrow (an excerpt of “Between the contexts”):
{Sales} --> {Door} Published language: the events
TicketsIssued and TicketTransferred, as JSON.
The worker turns them into the jobs
add_tickets_at_door and move_ticket_at_door.
Door writes down the fields it reads (showId,
tickets; showId, kind, oldCode, newCode), and
Sales keeps those fields.
{Door} ..> {Sales} Customer/supplier. Sales answers
isTicketCodeValid, made for Door: at each
scan, whether a ticket has the code right now.
Door's own list lags behind a transfer, and
this answer does not.
The map’s first check prints the new arrow:
grep -roE 'from "#(shows|sales|door|payouts)"' src | awk -F'[/"]' '{print $2, "..>", $(NF-1)}' | sort | uniq -c
1 dashboard ..> #door
1 dashboard ..> #payouts
1 dashboard ..> #sales
1 dashboard ..> #shows
1 door ..> #sales
1 door ..> #shows
1 payouts ..> #sales
2 payouts ..> #shows
7 sales ..> #shows
In README.md, add this paragraph after the one about the outbox:
A ticket's holder can give it to someone else at `/tickets/transfer` until
the doors open. `src/sales/domain/ticket.ts` holds the `Ticket` aggregate:
the transfer gives the ticket a new holder and a new code, and records
`TicketTransferred`. The worker emails the new code to the new holder and
moves the code in Door's list. The door also asks Sales about every code it
scans (`isTicketCodeValid`), so an old code stops working at once, before
the worker comes round.
Then make these edits in the same file:
- Under “Run it”, add a line for holders and
/tickets/transfer. - In the comment of
npm run worker, add “the door’s list”. - In “Files”, change “001 to 026” to “001 to 027”.
The code/module-11/ folder has the whole file.
Figure 6 is the code figure with this module’s changes marked.
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Door} ..> {Sales} isTicketCodeValid, one question at each scan NEW
{Sales} --> {Door} the events TicketsIssued and TicketTransferred NEW,
through the outbox
dashboard/ ..> {Shows}, {Sales}, {Door}, {Payouts} one question to each
{Shows}, {Sales}, {Payouts} ..> money/ the shared kernel (#money)
Inside {Sales}: routes/ ..> wiring.ts ..> application/ ..> domain/
db/, jobs/, acl/ ..> application/; db/, jobs/ ..> domain/
domain/ Sale, Order, pricing, the port SaleRepository,
the event TicketsIssued; Ticket, TicketCode,
the port TicketRepository and the event
TicketTransferred NEW
application/ salesService, with transferTicket NEW;
ports WithTransaction, startPayment
db/ the PostgreSQL adapters, with
ticket-repository.ts NEW; show-sales.ts
reads the read model sales.show_sales
jobs/ count-sales.ts; send-transferred-ticket.ts NEW
routes/ tickets.ts, the transfer page NEW
routes/ ..> acl/ ACL ..> [Payment provider]
Inside {Door}: routes/ ..> db/tickets.ts: its own list; routes/ ..> {Sales}
for each code NEW
db/scans.ts: each scan counts itself in door.show_scans
jobs/add-tickets.ts, jobs/move-ticket.ts NEW: the events
as Door reads them
platform/ the pool, the outbox and its relay, the job queue, settings,
page layout, login, email, the payment provider's client.
Every context and dashboard/ ..> platform/.
worker.ts subscribers: TicketsIssued --> send_confirmation,
add_tickets_at_door, count_sales; TicketTransferred -->
send_transferred_ticket, move_ticket_at_door NEW
Legend
{Name} a bounded context (Module 3)
A ..> B A depends on B in code (an import); for an outside service, on
its API (Module 3, Module 4)
A --> B A's domain event reaches B through the outbox and a job; no
import (Module 9)
ACL an anticorruption layer, inside the context it protects (Module 4)
money/ a shared kernel: one folder of the model that several contexts
import, changed only when they all agree (Module 5)
dashboard/ a page that only reads; it owns no table and no rule (Module 10)
Figure 6: TinyTickets at the end of the course; Door and Sales now talk both ways, with an event one way and one question the other.
Run the checks:
npm run check
npm test
npm run test:fast
What you should see: no tsc errors, 60 tests pass in npm test, and 33 in npm run test:fast. The end of the fast run, from one run:
✔ a context imports another context only through its # entry (12.921498ms)
✔ domain/ and application/ import nothing from the outside world (3.895676ms)
ℹ tests 33
ℹ suites 0
ℹ pass 33
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 349.735955
Commit:
git add -A
git commit -m "Describe transfers in the glossary, the board, the map and the README"
How a transfer works now
Follow Ana’s ticket to Ben, and both of them to the door (Figure 7):
- Ana opens
/tickets/transferand sends her code with Ben’s name and email. The route parses the code into aTicketCodeand checks the two fields. transferTicketopens a transaction.ticketOfreads the ticket by its code fromsales.tickets, and the show’s doors-open time fromshows.shows.Ticket.transferchecks that the doors are not open yet, gives the ticket a new code and Ben as holder, and recordsTicketTransferred.saveupdates the row only if its code is still Ana’s, then writes the event tooutboxon the same client. The transaction commits. A second transfer of Ana’s code would now find no ticket.- If Ana tries her old code at the door, Door’s list still has it, but
isTicketCodeValidaskssales.ticketsand gets no row. The door answers 404. - On its next pass, the worker’s relay turns the event into two jobs,
send_transferred_ticketandmove_ticket_at_door. - The first job emails Ben his new code. The second takes Ana’s code off
door.ticketsand adds Ben’s. - Ben shows his code. Door finds it in its list, Sales confirms it, and
insertScanrecords the scan and counts it indoor.show_scans.
(Ana) --> [Web app] POST /tickets/transfer parseTicketCode
transferTicket BEGIN
ticketOf --> [[sales.tickets]], [[shows.shows]]
Ticket.transfer doors not open yet; new code, Ben NEW
save --> [[sales.tickets]] WHERE code = the old one
--> [[outbox]] TicketTransferred NEW
COMMIT
(Ana) --> [Web app] POST /door/tickets, old code
findTicket --> [[door.tickets]] still there
isTicketCodeValid --> [[sales.tickets]] no row NEW
<-- 404
[Worker] relayEvents: [[outbox]] --> [[jobs]] x 2
[Worker] send_transferred_ticket --> [Email service] --> (Ben)
[Worker] move_ticket_at_door --> [[door.tickets]] old out, new in NEW
(Ben) --> [Web app] POST /door/tickets, new code scan and count
<-- 200
Figure 7: the transfer changes one row and writes one event; the door refuses the old code at once and admits the new one after the worker’s pass.
Between steps 4 and 7, Ben has no code yet, and the old code no longer works. So for a moment nobody can enter with the ticket. That is the safe side of the gap.
Where DDD is too much
The transfer used the tools of Modules 1 to 9 again, checked Module 10’s read models, and skipped some tools on purpose. It needed no new context, no anticorruption layer, no new read model, no saga and no event sourcing. Every tool in this course has a cost. Figure 8 collects them, with the cost each module stated and the case where it said to skip the tool.
| Module | Tool | What it cost TinyTickets | Skip it when |
|---|---|---|---|
| 1 | a glossary, and renames to match it | renames across files, types and stored jobs; a file to keep current | other systems read the word, or nobody will change that code again |
| 2 | an event storming board | a session with Leo and the team; hotspots that someone must act on | one person knows the whole flow, or nobody will act on the questions |
| 3 | one folder and one schema per context | entries, schemas and a boundary test | a word means one thing everywhere, or every change would cross three folders |
| 4 | a context map and an anticorruption layer | a map file; translation code and its test | the outside model is small and its words fit, like the email service |
| 5 | value objects with a brand | parse functions, casts, one more idea for each new developer | one file handles money, in one currency |
| 6 | entities with one type per state | a class, a union, factories, mapping code | the data has no lifecycle rules, like an organizer’s name |
| 7 | aggregates and a version | retries on conflicts; rules that cannot span two aggregates | one database constraint says the whole rule, like a scan’s UNIQUE |
| 8 | ports, adapters and repositories | seven new files in Sales, mapping code, a fake that can drift | a read-only report, or an admin screen that edits a name |
| 9 | domain events and an outbox | a table, a relay, handlers safe to repeat, reactions that arrive later | one reaction in the same context; write its job in the same transaction |
| 10 | read models and projections | a table, a projection, a first fill, a rebuild, a page that can lag | a plain query is fast enough under the real load |
| 11 | a second aggregate, and a question across contexts | a fake that throws; Door depends on Sales again | the rule fits an aggregate you have, or the delay only ever refuses |
Figure 8: what each tool cost, and the case where its module said to skip it.
Strategic tools everywhere, tactical tools in the core
The tools fall into two groups. The strategic ones (a shared language, a board, contexts and a map) cost a file and a meeting. The tactical ones (value objects, entities, aggregates, ports, events and read models) cost code in every feature they touch.
Evans’ Reference (2015) says where the second group belongs. The core domain is the part of the design that should get the most care, and he writes “Make the core small” (p. 40). Everything else is justified by how it supports the core.
For generic subdomains he advises lower priority, and an off-the-shelf solution where one fits (p. 41).
Fowler’s “CQRS” (2011) says CQRS adds risky complexity for most systems. Microsoft’s Event Sourcing pattern (2026) says plain data storage is enough for most systems. Its CQRS pattern page (2025) says not to use CQRS when the domain or its rules are simple.
Vaughn Vernon argues the other way in Domain-Driven Design Distilled (2016). In chapter 1, he calls DDD a set of advanced techniques for complex projects, and adds that it “doesn’t have to hurt” (p. 2).
He argues that skipping design is a false saving. Without design, he writes, business logic ends up in the user interface and in the persistence code (pp. 3 to 6).
The two sides agree once DDD is split. The strategic half is cheap, and it helps wherever one word means two things. The tactical half pays where the rules are complex and the area sets the business apart. In our judgment, that is the line to draw.
A core domain chart for TinyTickets
A core domain chart is a plot of each subdomain by how much it sets the business apart and how complex its model is. The DDD Crew’s Core Domain Charts, which Module 1 named, put business differentiation on one axis and model complexity on the other. Their README says the value is the talk: developers judge complexity, business people judge differentiation, and both are bets. Figure 9 is the team’s chart for TinyTickets.
model complexity
high | {Sales}
| holds, prices,
| transfers
| {Payouts}
| {Door}
| {Shows}
low | [Email] [Payments] [Login]
+--------------------------------------------------
low business differentiation high
Figure 9: where each part of TinyTickets sits; the positions are the team’s judgment, and the horizontal one is Leo’s call.
Transfers moved Sales up, because it gained a second aggregate and a rule across contexts. Whether they moved it right is a question for Leo: does any other ticket site let his regular guests pass tickets to friends?
The chart says how much DDD each part deserves:
- Sales (core): every tool in the course, because its rules are where TinyTickets fails or succeeds.
- Shows, Door, Payouts (supporting): a glossary entry, a context and a schema, but no aggregates unless a rule appears. Door got by with one
UNIQUEconstraint, and Shows is still rows and queries. - Email, payments, login (generic): no model of their own. They are a fake or a provider, kept at the edge.
An organizer profile page, if Leo asks for one, is a form and an UPDATE. It needs a glossary word and nothing from Modules 5 to 10.
What changed recently
Eric Evans has given talks on large language models since 2024. At Explore DDD in March 2024, he urged practitioners to experiment, as InfoQ reported. The report says he suggested treating a fine-tuned model as a bounded context, trained on that context’s language.
His DDD Europe 2026 keynote abstract asks whether AI will amplify DDD or replace it. It answers that models, contexts and language still matter, though the models will look different.
The discovery tools are still maintained. The Bounded Context Canvas is at version 5, and both DDD Crew repositories had commits in 2026. Domain Storytelling became a book in 2021, and the Thoughtworks Technology Radar put it at Trial in October 2024, as a companion to event storming.
Vlad Khononov’s Balancing Coupling in Software Design (2024) is a book about coupling in modular systems. Its chapters are named Integration Strength, Distance and Volatility.
Bringing Domain-Driven Design into code you already have
TinyTickets in Module 1 was such a codebase. It had three names for a hold, a seat rule in a route handler and money in dollars and cents. The course did not rewrite it. Each module moved one part and left the rest running.
Eric Evans’ paper “Getting Started with DDD When Surrounded by Legacy Systems” (2013) warns against the two obvious starts. Applying DDD’s tactical patterns inside the legacy code rarely pays off, he writes (p. 1). He calls a big project to replace the legacy system a bad strategy in most cases, and worse when it also brings new methods (pp. 1 and 2).
He advises starting small, like a pilot.
This is an order of steps that his paper and Fowler’s recent articles support. The end of each step says where this course did it at TinyTickets.
- Pick one area that is core and changing now. Not the whole codebase (Evans 2013, pp. 1 and 2; Evans 2015, p. 40). At TinyTickets, Sales.
- Learn its language with the people who run it. A glossary, then a board or a domain story. Modules 1 and 2, and Step 2 here.
- Draw the boundary. In one app, a folder and a schema, and translation at its edge. Modules 3 and 4.
- Put a seam where the old code calls the area, and route the calls through it. Module 8’s ports.
- Move behavior behind the seam one use case at a time, with tests at the seam first. Modules 5 to 7, one rule each.
- Give the area its own data only when it needs data the old tables lack, and keep it in step by events. Modules 9 and 10.
- Stop when what is left is stable and not core.
The next two sections explain the tools behind steps 3, 4 and 6.
Start with a bubble
A bubble context is a small bounded context with an anticorruption layer around it (Evans 2013, pp. 1 to 8). A small team that keeps its discipline sets it up for one modest but tricky business problem. It keeps using the legacy database, so it has no copy of the data to keep in step.
Its repository reads the legacy tables and translates each row into the bubble’s model, with no tables of its own (pp. 5 and 6). Evans warns that a translator should only translate, and that business logic inside it is a trap (p. 5). The translation layer is real software, so budget for it (p. 7).
Most bubbles burst, he writes (p. 8). Someone reads a legacy table past the layer, the discipline lapses, and the old code takes the new code back in. The value the bubble delivered stays, though.
An autonomous bubble has its own data in its own model, and can run for a while cut off from the other systems (pp. 9 to 12). A synchronizing ACL feeds it, copying and translating data from the other systems after the fact, with an agreed delay. Evans names a nightly batch script as the simple version and messages carrying domain events as the more elaborate one.
Door has worked this way since Module 9. It keeps its own list, fed by events after the commit. This module found that setup’s limit: when a rule cannot wait, the bubble must ask the system that owns the answer.
For growing a bubble, Evans adds a rule: bring in only the data you use, because each new field is a modeling job (pp. 18 to 20).
Move behavior behind a seam
Michael Feathers’ book Working Effectively with Legacy Code (2004) defines a seam. Martin Fowler’s “Legacy Seam” (2024) quotes it:
“a place where you can alter behavior in your program” (Feathers, quoted in Fowler, “Legacy Seam”)
You change the behavior without editing the code at that place. The place where you choose which behavior runs is the seam’s enabling point. Fowler’s examples include TypeScript-style module seams, and he lists three uses: tests, watching calls, and moving behavior out of the legacy code bit by bit.
TinyTickets has had a seam since Module 8. salesService takes its ports as one object, and src/sales/wiring.ts is the enabling point, the one file that picks the adapters (an excerpt):
export const sales = salesService({
withTransaction,
async startPayment(orderToken, amountCents) {
const payment = await createPayment(amountCents, orderToken);
await savePayment(orderToken, payment.id, payment.payUrl);
return payment.payUrl;
},
now: () => new Date(),
});
A test passes other functions to the same seam, and Step 4 of this module added a repository to it without touching a route.
A strangler fig is a way to replace a legacy system by building the new one around it, part by part, until the old one can be removed. Fowler’s “Strangler Fig Application” (rewritten in 2024) lists four activities, from Cartwright, Horn and Lewis. You understand the outcomes you want, break the problem into parts, deliver the parts, and change the organization so the work continues.
He admits that teams resist the code that lets old and new run side by side, because it is deleted later. He argues it is worth its cost. He also notes that legacy systems rarely have parts you can swap out as they stand, which is why you look for seams.
Inside one app, the same idea works at the level of a module. Branch by abstraction replaces one module of an app through an abstraction, as Fowler’s article (2014) describes. You put the abstraction over the old code, move the callers onto it, build the new code behind it, switch, and remove the old code. Module 8’s SaleRepository is such an abstraction, with two adapters behind it.
When to stop
Evans also makes the case for leaving code alone. When a legacy system is stable, is not core, and its data can be reached, he asks, “why not let it be?” (p. 17).
At TinyTickets, Shows is that case. It is a set of rows that organizers edit, with no rule that has gone wrong. The course gave it a folder, a schema and an entry, and nothing more. Nick Tune and Jean-Georges Perrin’s Architecture Modernization (Manning, 2024) treats the larger version of this work, across teams and systems.
Check yourself
- Why did “buyer” become two words in this module, and which column changed its name?
Answer
A transfer separates the person who paid from the person who may enter, so the glossary gained “purchaser” (refunds go back to them) and “holder” (they get in). sales.tickets.buyer_name became holder_name, with a new holder_email. sales.orders.buyer_name stayed, because the buyer on an order is the purchaser.
- Why is
Ticketan aggregate of its own instead of part of theSale, and what stops two transfers of one ticket from both succeeding?
Answer
The Sale keeps the seat rule, and a transfer changes no seat. Inside the Sale, each transfer would read every order of the show and move its one version, and wait behind the holds at 10:00. Two transfers at once are stopped by the UPDATE ... WHERE id = $1 AND code = $2: the second one updates no row, throws TicketChangedError, and on its retry finds no ticket with the old code.
- Module 9 accepted that Door learns of new tickets late. Why was the same delay not acceptable for a transfer, how does the door close it, and what does that cost?
Answer
For a new ticket, the delay refuses someone who should get in, which is safe. For a transfer, it admits an old code that should be dead, so one ticket let two people in. The door now asks Sales at each scan with isTicketCodeValid, because Sales changes the code in the transfer’s own transaction. It costs a new Door ..> Sales dependency, one more query per scan, and a small gap between the question and the scan.
- Leo asks for a page where organizers edit their name and payout account. Which tools from this course would you use for it, and why?
Answer
A glossary word, and the existing Shows context and schema, and none of the tactical tools. The data has no lifecycle rules and no rule across rows, so a form and an UPDATE say everything (Modules 6 and 7 name this case). Shows is a supporting subdomain on the core domain chart, and the tactical tools belong in the core.
- You join a team with a large codebase and no DDD. What do you do first, what does Evans warn against, and why do most bubbles burst?
Answer
Pick one area that is core and changing now, and learn its language with the people who run it. Evans warns against applying the tactical patterns inside the legacy code and against a big replacement project. Bubbles burst when people read the legacy data past the anticorruption layer and the discipline lapses, so the old code absorbs the new.
Cheat sheet
Cheat sheet
- Words first: a new feature can split a word; give each person a word and each word a column.
- Board: tell one example as a domain story, then add its events, policies and hotspots; keep the business’s questions open.
- Context: stay in the context whose words the feature uses; a word may mean something else in another context.
- Aggregate: draw it around the rule; a transfer changes no seat, so the ticket is its own aggregate.
- Version: any value that every change replaces can be the version, like the ticket’s code.
- Events: a delay is safe when it refuses, and a security gap when it admits; ask the owner when it must not lag.
- How much DDD: strategic tools everywhere, tactical tools in the core.
- Older code: one core area, its language, a boundary, a seam, then one use case at a time.
- Stop: leave stable code that is not core alone.
Figure 10 is the whole method on one feature.
Words purchaser, holder GLOSSARY.md, migration 027
Board domain story, then the board BOARD.md, two hotspots open
Context Sales; no new context, no ACL the canvas: in, out, decisions
Aggregate Ticket: code, holder, doors open version = the code
Port TicketRepository, transferTicket in one transaction
Event TicketTransferred --> outbox email job, Door's list
Door asks Sales at each scan the old code fails at once
Read model unchanged one scan, one ticket sold
Figure 10: each step of the method, and what it produced for ticket transfers.
The code now lets a holder give a ticket away until the doors open. The door refuses the old code at once, and admits the new one after the worker’s pass. TinyTickets’ next stage, when Leo books an arena, is on the story page.
Sources
- Eric Evans, Domain-Driven Design Reference, Domain Language, 2015 (CC BY 4.0): Core Domain (p. 40), Generic Subdomains (p. 41).
- Eric Evans, “Getting Started with DDD When Surrounded by Legacy Systems”, Domain Language, 2013: pp. 1 to 12 and 17 to 20.
- Vaughn Vernon, Domain-Driven Design Distilled, Addison-Wesley, 2016, chapter 1.
- Martin Fowler: “Strangler Fig Application”, 2024; “Legacy Seam”, 2024; “Branch By Abstraction”, 2014; “CQRS”, 2011.
- Michael Feathers, Working Effectively with Legacy Code, Prentice Hall, 2004, chapter 4, “The Seam Model”.
- Microsoft, Azure Architecture Center: “CQRS pattern”, 2025; “Event Sourcing pattern”, 2026.
- Stefan Hofer and Henning Schwentner, Domain Storytelling, the quick start guide, and the book Domain Storytelling, Addison-Wesley, 2021.
- DDD Crew: Bounded Context Canvas (version 5) and Core Domain Charts.
- Thoughtworks Technology Radar, “Domain storytelling”, October 2024.
- Thomas Betts, “Eric Evans Encourages DDD Practitioners to Experiment with LLMs”, InfoQ, 2024; DDD Europe 2026, opening keynote by Eric Evans.
- Vlad Khononov, Balancing Coupling in Software Design, Addison-Wesley, 2024 (table of contents only).
- PostgreSQL 18 docs: transaction isolation.
- Nick Tune with Jean-Georges Perrin, Architecture Modernization, Manning, 2024.
- Ticketmaster US help: “What is Ticket Transfer?” and “Can I get a refund if I receive a ticket through Ticket Transfer?”.