On Wednesday, Nina wrote a load test for Kofi Asante’s sale on Saturday at 10:00. It sent 50 holds at once for a test show with one seat left, and 31 of them got the seat.
“One seat, thirty-one holds,” Nina told Maya. “Every request checked the seats first.”
“So which buyer sits in it?” Leo asked.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
No buyer saw it, because the show was a test show and the sale was three days away. Every request did check the seats. But many of them checked before the others had saved their holds, so each of those saw a free seat.
This module moves the seat rule into an aggregate: one object that owns the seats of a show and every order for them. It is the only way to change them. Then it saves that object with a version number, so two requests that start from the same seats cannot both save.
After this module, you can:
- find the data that one business rule needs at the same moment, and draw an aggregate around it, with one root as the only way in
- explain why a check and an insert in one transaction still give the last seat away twice in PostgreSQL, and show it with a load test
- save an aggregate with a version column, turn “0 rows updated” into a conflict, and run the command again on fresh data
- refer to another aggregate, or to another context’s object, by its ID, and change one aggregate per transaction
- say what a version per show costs when a crowd arrives at 10:00, and when a row lock is the better choice
Where the code stands
Module 6 made the order an entity with three states. The seat rule is still in the hold route. It reads every order of the show, adds up the seats they take, and then inserts the new order, with no transaction and no lock. Figure 1 is the code figure from Module 6.
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Shows}, {Sales}, {Payouts} ..> money/ the shared kernel (#money)
Inside {Sales}: services/, db/ ..> domain/ the Order entity: held, paid,
cancelled; it imports nothing
routes/, services/, jobs/ ..> acl/ ACL ..> [Payment provider]
Only acl/ knows the provider's webhook body.
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client, the organizer dashboard.
Every context ..> platform/. platform/ ..> money/.
app.ts and worker.ts ..> each #.
Figure 1: the contexts as Module 6 left them; the seat rule lives in routes/holds.ts, outside domain/.
Fifty buyers and one seat
Here is the seat rule, in src/sales/routes/holds.ts (an excerpt, lines 37 to 45):
const now = new Date();
const orders = await listOrdersForShow(show.id);
const taken = orders
.filter((order) => orderFromRow(order).holdsSeats(now))
.reduce((sum, order) => sum + order.quantity, 0);
if (taken + quantity > show.seats) {
response.status(409).send(showPage(show, `Sorry, only ${show.seats - taken} seats are left.`));
return;
}
After the check, the route calls createHold, which inserts the order. The existing test “a hold for more seats than are left is refused” passes, because it sends one request at a time. Nina’s load test sends many at once. Add it at the end of app.test.ts:
// A small load test. Fifty buyers have the show page open, and all of them
// ask for the last seat at the same moment.
test("fifty buyers at once get the last seat 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, 'Last Seat Show', current_date + 30, '19:00', 'Test Club', 2, 1200)
RETURNING id`,
);
const page = `/shows/${show.rows[0]!.id}`;
await post(`${page}/hold`, { ...buyer, standard: "1" });
const buyers = Array.from({ length: 50 }, () => buyer);
const opened = await Promise.all(buyers.map(() => fetch(`${site}${page}`)));
await Promise.all(opened.map((answer) => answer.text()));
const answers = await Promise.all(buyers.map((one) => post(`${page}/hold`, { ...one, standard: "1" })));
const held = answers.filter((answer) => answer.status === 303).length;
const refused = answers.filter((answer) => answer.status === 409).length;
assert.deepEqual({ held, refused }, { held: 1, refused: 49 });
});
The show has two seats, and one buyer holds the first. Then 50 buyers open the show page and press “Hold my seats” together. A hold that succeeds answers 303, to the payment page, and a refused one answers 409.
The test opens the page 50 times first for a reason. fetch keeps those 50 connections open, so the 50 holds that follow reach the server together. Without those two lines, the holds reach the server one connection at a time, and the test passes even on this code.
Pause and predict: one seat is left, and 50 requests run the check above. How many get the seat?
npm test
What you should see (an excerpt from one run; your numbers will differ from run to run):
✖ fifty buyers at once get the last seat once (192.809754ms)
...
ℹ tests 31
ℹ suites 0
ℹ pass 30
ℹ fail 1
...
+ actual - expected
{
+ held: 44,
+ refused: 6
- held: 1,
- refused: 49
}
Forty-four buyers hold a seat that exists once. Another run gave 49. The number changes because it depends on how the requests interleave. Any number above one is the bug.
Figure 2 shows two of the requests.
Request A Request B
SELECT the orders: 1 of 2 seats taken
SELECT the orders: 1 of 2 seats taken
1 + 1 <= 2, so hold
1 + 1 <= 2, so hold
INSERT order A
INSERT order B
3 of 2 seats taken
Figure 2: each request checks the seats before the other one has inserted its order.
The check is correct, and the rule exists once in the code. What is missing is a unit of data that one request owns while it checks and saves. That unit is what this module builds.
The rule needs one show’s seats and all of its orders
An aggregate is the data one rule needs at once
Start from the rule, in Leo’s words: the orders that take seats never take more seats than the show has. Module 6 called such a rule an invariant, a rule that holds every time code outside an object can look at it.
To check it, the code needs three things at the same moment. It needs the show’s number of seats, every order of that show that takes seats, and the new order. If any of them changes between the check and the save, the check is worth nothing.
An aggregate is a group of entities and value objects that the code loads, changes and saves as one unit, so that its invariants hold after every change. Evans, in the Domain-Driven Design Reference (2015, p. 16), groups objects into aggregates for this reason. A rule is hard to keep true when any object can change any other.
The aggregate root is the one entity in the aggregate that outside code may hold and call. Every change goes through its methods, so the root can check the invariant on every change. Evans lets the root pass an inner object out for one operation only.
TinyTickets gets one aggregate per show, the Sale. The glossary already has the word: Leo says “the sale opens at 10:00”. In the code, a sale is the root, and the orders of the show are entities inside it.
+-- the Sale of show 7 (one aggregate) ------------------------+
| |
| Sale (the root) showId 7, seats 200, version 4 |
| hold(token, seats, now) pay(token, now) |
| cancel(token, now) seatsLeft(now) |
| |
| Order a1f3... 2 seats paid |
| Order 9c0e... 1 seat held until 10:10 |
| Order 77b2... 3 seats cancelled |
| |
| Invariant: the seats of paid orders and of holds that have |
| not run out <= seats |
+--------------------------------------------------------------+
showId 7 ..> {Shows}: Show 7, by its ID only
Figure 3: the box is the aggregate. Outside code calls the root, and the root reaches the orders.
This is not the “aggregate” of SQL, such as count() or sum(). The two words are the same, and the ideas are different.
The boundary is set by the rule, not by the tables
A consistency boundary is the line around the data that must agree with one rule inside one transaction. Vernon, in “Effective Aggregate Design, Part I” (2011, p. 3), uses the two names for one thing:
“aggregate is synonymous with transactional consistency boundary.” (Vernon, Part I, p. 3)
So the question for each piece of data is whether the seat rule needs it. The show’s seats and the orders that take seats are in. The buyer’s email, the order’s lines and its total are not, so they stay on the row, as in Module 6.
Payments are less obvious. Paying never adds an order, so it looks as if a payment cannot break the seat rule. But it can change how long an order takes seats.
Suppose a buyer’s hold runs out at 10:10. Her payment arrives at 10:09:59, so pay makes the order paid, and the order now takes its seats forever. If that transaction commits at 10:10:01, a hold that loaded the sale at 10:10:00 saw an expired hold and free seats. Both would commit, and the show would sell one seat too many.
So payments and failed payments change the sale too, and they go through its root. That costs something. At 10:00, payments for a show wait for, or conflict with, holds for the same show, because they share one aggregate.
Vernon calls rules that developers invent, without a business reason, “false invariants”. In Part I (p. 2) they make one large aggregate fail under concurrent use. The test for each part of a boundary is a real rule that needs it, and here the rule is Leo’s.
Refer to other aggregates by ID
A Sale needs the number of seats, which belongs to the Shows context. It does not hold a Show object. It holds showId and copies the number of seats in when it loads.
Reference by identity means that an aggregate stores only the ID of another aggregate, never the object. Vernon, in “Effective Aggregate Design, Part II” (2011, p. 8), gives the reason in one line: if you hold no reference, you cannot change another aggregate by accident. The aggregate also loads less.
For TinyTickets, the reference crosses a context boundary as well. Shows owns the show; Sales asks findShow through #shows and keeps only what its rule needs. The cost is a second lookup in every command, and a view that needs the show’s name and the sale’s seats must ask both. Vernon (Part II, p. 8) points to a separate read model for such views, which Module 10 builds.
One aggregate per transaction
Vernon (Part I, p. 4) asks that one transaction change one aggregate instance. He calls it a rule of thumb, and in Part II (p. 9 to 11) he lists four reasons to break it.
In TinyTickets the rule falls out of the boundary. A hold adds an order to one sale. A payment changes one order in one sale. Each command changes one aggregate, so it has one version to check.
PostgreSQL could commit two aggregates in one transaction without trouble, because TinyTickets has one database. The reason to keep one is contention. Two aggregates in one transaction must both be free of conflicts at the same moment, so the transaction fails more often.
Vernon gives a test for what belongs in the same transaction. He asks whose job it is to make the data consistent (Part II, p. 9). Holding a seat is the buyer’s job, so the seat rule must hold at once. Emailing the tickets and paying the organizer are the system’s job, and they can follow later, which Module 9 builds.
Why the transaction alone is not enough
Wrapping the check and the insert in BEGIN and COMMIT looks like the fix. It does not work, and Step 3 shows it.
Read Committed is PostgreSQL’s default isolation level: each statement sees the rows that were committed before the statement began (PostgreSQL 18, 13.2.1). Request B’s SELECT cannot see request A’s order until A commits. So both check against the same seats, both insert, and both commit.
The PostgreSQL docs say that under Read Committed, a business rule that reads several rows is very difficult to enforce. The view of the data shifts from statement to statement (PostgreSQL 18, 13.4). They offer Serializable transactions or explicit locks. This module uses a third tool, the version column, and compares all three in Going deeper.
Optimistic concurrency with a version column
Optimistic concurrency lets two requests read the same data without a lock, and finds out at save time that one of them saved first. That one wins, and the other starts again. The tool for it is a version column: a number on the root’s row that goes up by one with every save.
Each command loads the sale with its version, say 4. It saves with this statement:
UPDATE sales.sales SET version = version + 1 WHERE show_id = $1 AND version = $2
The first command to save matches the row and moves it to version 5. The second still asks for version 4, so its UPDATE matches no row. PostgreSQL does not raise an error for that; pg returns rowCount 0. The code must turn 0 into a conflict, roll back, load the sale again and run the command again.
If the second UPDATE runs while the first transaction is still open, it does not read the old row. It waits for the first transaction’s row lock. When the first commits, PostgreSQL checks the WHERE clause again against the new row, and version 5 does not match 4 (PostgreSQL 18, 13.2.1).
Request A Request B
BEGIN; load the sale: version 4, 1 seat left
BEGIN; load the sale: version 4, 1 seat left
sale.hold: held
UPDATE ... AND version = 4: 1 row (now 5)
sale.hold: held
UPDATE ... AND version = 4
waits for A's row lock
INSERT order A; COMMIT
checks version = 4 again: 0 rows
ROLLBACK; load again: version 5, 0 seats
sale.hold: sold out, so 409
Figure 4: the second save waits, then matches no row, and the command runs again on fresh data.
Rule: the aggregate says what must stay consistent; the version check on its root is what stops two copies of it from both being saved.
So “optimistic” covers the time between the load and the save. The save itself takes a row lock in PostgreSQL. The costs are a retry path in every command, and failures under a crowd: at 10:00, many buyers load the same version, one wins, and the rest start again. The exercise measures that cost.
TypeScript has no part in this check. No type can stop two requests from passing the same if at the same moment, because both are correct at the moment they run. The run-time check is the WHERE version = $2 in the database.
Put the seat rule in the Sale, step by step
Each step says why, what to do, the code, and what you should see. Work in the project folder Module 6 left, with the load test from the problem section. The finished code is in the code/module-07/ folder of the course repository. If you kept the exercise from Module 4, your test counts are one higher.
Step 1: Give the order its number of seats
Why: the Sale adds up the seats its orders take. Module 6 kept the order lean, with only its token and its state, because no rule needed more. The seat rule needs the number of seats.
What to do: in src/sales/domain/order.ts, add a seats field, and take it in the constructor and both factories (an excerpt):
readonly token: string;
readonly seats: number;
#state: OrderState;
private constructor(token: string, seats: number, state: OrderState) {
this.token = token;
this.seats = seats;
this.#state = state;
}
// A new order starts with a hold of HOLD_MINUTES.
static hold(token: string, seats: number, now: Date): Order {
return new Order(token, seats, { status: "held", holdExpiresAt: new Date(now.getTime() + HOLD_MINUTES * 60_000) });
}
// An order that already exists, read back from storage.
static restore(token: string, seats: number, state: OrderState): Order {
return new Order(token, seats, state);
}
Run npm run check.
What you should see:
src/sales/db/orders.ts(20,20): error TS2554: Expected 3 arguments, but got 2.
src/sales/db/orders.ts(22,20): error TS2554: Expected 3 arguments, but got 2.
src/sales/db/orders.ts(24,20): error TS2554: Expected 3 arguments, but got 2.
src/sales/domain/order.test.ts(9,23): error TS2554: Expected 3 arguments, but got 2.
src/sales/domain/order.test.ts(15,23): error TS2554: Expected 3 arguments, but got 2.
src/sales/domain/order.test.ts(21,23): error TS2554: Expected 3 arguments, but got 2.
src/sales/domain/order.test.ts(28,23): error TS2554: Expected 3 arguments, but got 2.
src/sales/domain/order.test.ts(35,23): error TS2554: Expected 3 arguments, but got 2.
src/sales/services/holds.ts(16,23): error TS2554: Expected 3 arguments, but got 2.
tsc lists every place that makes an order. In src/sales/db/orders.ts, pass the row’s quantity in orderFromRow (an excerpt):
case "held":
return Order.restore(row.token, row.quantity, { status: "held", holdExpiresAt: row.hold_expires_at });
case "paid":
return Order.restore(row.token, row.quantity, { status: "paid", paidAt: row.paid_at! });
case "cancelled":
return Order.restore(row.token, row.quantity, { status: "cancelled", cancelledAt: row.cancelled_at! });
The number of seats now lives in the order, so insertOrder should write it from there, and stop taking quantity as a separate field (two excerpts):
export async function insertOrder(order: Order, r: {
showId: number; buyerName: string; buyerEmail: string; lines: OrderLine[]; totalCents: Cents;
}): Promise<OrderRow> {
[order.token, r.showId, r.buyerName, r.buyerEmail, order.seats,
In src/sales/domain/order.test.ts, give each of the five orders two seats: Order.hold("t1", tenOClock) becomes Order.hold("t1", 2, tenOClock), and the same for t2 to t5. In src/sales/services/holds.ts, count the seats before the factory, and drop the quantity line from the call to insertOrder (an excerpt):
const seats = lines.reduce((sum, line) => sum + line.quantity, 0);
const order = Order.hold(randomBytes(16).toString("hex"), seats, new Date());
const row = await insertOrder(order, {
showId: show.id,
buyerName: buyer.name,
buyerEmail: buyer.email,
lines,
totalCents,
});
Run npm run check and npm test.
What you should see: no tsc errors, and the same single failure as before, the load test, with a different number of holds. Commit:
git add -A
git commit -m "Give an order its number of seats"
Step 2: Write the Sale aggregate
Why: the seat rule needs one home that sees the seats and every order, and every change must go through it.
What to do: save this as src/sales/domain/sale.ts:
import { Order } from "./order.ts";
import type { FailureOutcome, PaymentOutcome } from "./order.ts";
// What code outside the sale may use of one of its orders. It can read the
// order; it changes the order only through the sale.
export type OrderView = Pick<Order, "token" | "seats" | "state">;
export type HoldOutcome =
| { readonly result: "held"; readonly order: OrderView }
| { readonly result: "sold out"; readonly seatsLeft: number };
// The sale of one show in Sales (see "Sale" in GLOSSARY.md): its seats and
// every order for it. The rule it keeps: the orders that take seats never
// take more seats than the show has.
export class Sale {
readonly showId: number;
readonly seats: number;
readonly version: number;
readonly #orders: Order[];
private constructor(showId: number, seats: number, version: number, orders: Order[]) {
this.showId = showId;
this.seats = seats;
this.version = version;
this.#orders = orders;
}
// A sale read back from storage, with the version it had then.
static restore(showId: number, seats: number, version: number, orders: Order[]): Sale {
return new Sale(showId, seats, version, [...orders]);
}
seatsLeft(now: Date): number {
const taken = this.#orders
.filter((order) => order.holdsSeats(now))
.reduce((sum, order) => sum + order.seats, 0);
return this.seats - taken;
}
// A buyer asks for seats. The new order is held only if the seats are free.
hold(token: string, seats: number, now: Date): HoldOutcome {
const seatsLeft = this.seatsLeft(now);
if (seats > seatsLeft) {
return { result: "sold out", seatsLeft };
}
const order = Order.hold(token, seats, now);
this.#orders.push(order);
return { result: "held", order };
}
// Paying keeps an order's seats after its hold would have run out, so a
// payment changes the sale, and goes through it.
pay(token: string, now: Date): PaymentOutcome {
return this.#find(token).pay(now);
}
cancel(token: string, now: Date): FailureOutcome {
return this.#find(token).cancel(now);
}
order(token: string): OrderView {
return this.#find(token);
}
#find(token: string): Order {
const order = this.#orders.find((one) => one.token === token);
if (order === undefined) {
throw new Error(`Order ${token} is not in the sale of show ${this.showId}.`);
}
return order;
}
}
Notice four things:
holdis the seat rule, moved from the route. It counts the seats withholdsSeats, the rule Module 6 gave the order, and only then makes the new order withOrder.hold.payandcancelpass the order’s own rules through. The root adds no new check here; it makes every change to an order a change to the sale.versionis the number the sale had when it was loaded. The domain never changes it; Step 4 checks it when the sale is saved.order(token)returns anOrderView, the order’s token, seats and state without its methods. Evans lets an inner object leave the root only to be used; heretsclets a caller read the order and not change it.
The sale takes no time from the clock and touches no database, so its tests are plain functions. Save this as src/sales/domain/sale.test.ts:
import assert from "node:assert/strict";
import { test } from "node:test";
import { Order } from "./order.ts";
import { Sale } from "./sale.ts";
const tenOClock = new Date("2027-03-01T10:00:00Z");
const minutesLater = (minutes: number) => new Date(tenOClock.getTime() + minutes * 60_000);
test("a sale holds seats until it has none left", () => {
const sale = Sale.restore(1, 3, 0, []);
assert.equal(sale.hold("a", 2, tenOClock).result, "held");
assert.deepEqual(sale.hold("b", 2, tenOClock), { result: "sold out", seatsLeft: 1 });
assert.equal(sale.hold("c", 1, tenOClock).result, "held");
assert.equal(sale.seatsLeft(tenOClock), 0);
});
test("a hold that ran out gives its seats to the next buyer", () => {
const sale = Sale.restore(1, 2, 0, [Order.hold("a", 2, tenOClock)]);
assert.equal(sale.hold("b", 2, minutesLater(9)).result, "sold out");
assert.equal(sale.hold("c", 2, minutesLater(10)).result, "held");
});
test("a paid order keeps its seats after its hold would have run out", () => {
const sale = Sale.restore(1, 2, 0, [Order.hold("a", 2, tenOClock)]);
assert.equal(sale.pay("a", minutesLater(5)), "paid");
assert.equal(sale.hold("b", 1, minutesLater(30)).result, "sold out");
});
test("two copies of one sale both give away its last seat", () => {
const first = Sale.restore(1, 1, 7, []);
const second = Sale.restore(1, 1, 7, []);
assert.equal(first.hold("a", 1, tenOClock).result, "held");
assert.equal(second.hold("b", 1, tenOClock).result, "held");
});
The last test records a limit. Two requests that load the same rows get two copies of one sale, and each copy is correct on its own. Both copies say version 7, and that is what Step 4 uses to save only one of them. Run the domain tests alone:
node --test src/sales/domain/sale.test.ts
What you should see (an excerpt):
✔ a sale holds seats until it has none left (1.44712ms)
✔ a hold that ran out gives its seats to the next buyer (0.184657ms)
✔ a paid order keeps its seats after its hold would have run out (0.221885ms)
✔ two copies of one sale both give away its last seat (0.142772ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
Now check that the root is the only way in. Save this as src/sales/domain/try-sale.ts:
import { Order } from "./order.ts";
import { Sale } from "./sale.ts";
const sale = Sale.restore(1, 1, 7, [Order.hold("a", 1, new Date())]);
sale.#orders.push(Order.hold("b", 1, new Date()));
sale.version = 8;
sale.order("a").pay(new Date());
Run npm run check.
What you should see:
src/sales/domain/try-sale.ts(5,6): error TS18013: Property '#orders' is not accessible outside class 'Sale' because it has a private identifier.
src/sales/domain/try-sale.ts(6,6): error TS2540: Cannot assign to 'version' because it is a read-only property.
src/sales/domain/try-sale.ts(7,17): error TS2339: Property 'pay' does not exist on type 'OrderView'.
Line 5 cannot add an order behind the root’s back, line 6 cannot move the version, and line 7 cannot pay an order without the sale. These are checks at compile time only.
A cast such as (sale.order("a") as Order).pay(new Date()) compiles and runs, because #find returns the real order. What protects the data from a careless caller is the save in Step 4, which goes through the sale’s version whatever the caller did. Delete the file, and commit:
rm src/sales/domain/try-sale.ts
git add -A
git commit -m "Add the Sale aggregate"
Step 3: Hold seats through the Sale, in one transaction
Why: the route still checks the seats itself. The hold should load the sale, ask its root, and save the new order, all inside one transaction.
What to do: the sale needs a row of its own, the root’s row. Save this as migrations/019_create_sales.sql:
-- Year 3: the sale of each show is an aggregate in Sales (see "Sale" in
-- GLOSSARY.md). This row is its root. The seats stay in shows.shows, and the
-- orders in sales.orders.
CREATE TABLE sales.sales (
show_id integer PRIMARY KEY REFERENCES shows.shows (id),
version integer NOT NULL DEFAULT 0
);
The row holds only the show’s ID and the version. The seats stay in Shows, so the foreign key points from Sales to Shows, the same way as the import arrow. The tests empty the tables before they start, and TRUNCATE refuses to empty shows.shows while another table points at it. So in app.test.ts, add sales.sales to the list (an excerpt):
`TRUNCATE door.scans, payouts.payouts, sales.tickets, sales.orders, sales.sales,
shows.shows, shows.organizers, sessions, users, jobs RESTART IDENTITY`,
Save this as src/sales/db/sales.ts. Step 4 adds the save to it.
import type pg from "pg";
import { findShow } from "#shows";
import type { Show } from "#shows";
import { pool } from "#platform";
import { Sale } from "../domain/sale.ts";
import { orderFromRow } from "./orders.ts";
import type { OrderRow } from "./orders.ts";
async function loadSale(show: Show, client: pg.PoolClient): Promise<Sale> {
// The first hold of a show adds its row.
await client.query("INSERT INTO sales.sales (show_id) VALUES ($1) ON CONFLICT DO NOTHING", [show.id]);
const sale = await client.query<{ version: number }>(
"SELECT version FROM sales.sales WHERE show_id = $1",
[show.id],
);
const orders = await client.query<OrderRow>("SELECT * FROM sales.orders WHERE show_id = $1", [show.id]);
return Sale.restore(show.id, show.seats, sale.rows[0]!.version, orders.rows.map(orderFromRow));
}
// Loads the sale of one show and runs one command on it, in one transaction.
export async function changeSale<T>(
showId: number,
command: (sale: Sale, client: pg.PoolClient) => Promise<T>,
): Promise<T> {
// findShow takes its own connection from the pool, so it runs before this
// command takes one. Otherwise many waiting commands could use up the pool.
const show = await findShow(showId);
if (show === undefined) {
throw new Error(`There is no show ${showId}.`);
}
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await command(await loadSale(show, client), client);
await client.query("COMMIT");
return result;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
changeSale is the one way to change a sale. It loads the sale inside the transaction and hands the root to a command. The comment about findShow matters under load. If findShow runs inside the transaction, the load test hangs.
Each waiting command holds one pool connection and waits for a second one, which no command releases. The show’s seats come from Shows through #shows, so the Sale refers to the show by its ID and copies only the number. Module 8 moves loading and saving into a repository; here they are two functions.
In src/sales/db/orders.ts, insertOrder must take the transaction’s client and accept the view that hold returns (an excerpt, with a new import under the others):
import type { OrderView } from "../domain/sale.ts";
export async function insertOrder(order: OrderView, r: {
showId: number; buyerName: string; buyerEmail: string; lines: OrderLine[]; totalCents: Cents;
}, client: pg.PoolClient | pg.Pool = pool): Promise<OrderRow> {
const result = await client.query<OrderRow>(
Delete listOrdersForShow from the same file; loadSale reads the orders now. Then replace src/sales/services/holds.ts with this, the Step 3 version:
import { randomBytes } from "node:crypto";
import { insertOrder, savePayment } from "../db/orders.ts";
import { changeSale } from "../db/sales.ts";
import type { Show } from "#shows";
import { createPayment } from "#platform";
import { orderTotalCents } from "./pricing.ts";
import type { OrderLine } from "./pricing.ts";
export type HoldResult =
| { result: "held"; payUrl: string }
| { result: "sold out"; seatsLeft: number };
// Holds seats through the sale of the show, then asks the payment service for
// a payment page.
export async function holdSeats(
show: Show,
buyer: { name: string; email: string },
lines: OrderLine[],
): Promise<HoldResult> {
const totalCents = orderTotalCents(show.price_cents, lines);
const seats = lines.reduce((sum, line) => sum + line.quantity, 0);
const held = await changeSale(show.id, async (sale, client) => {
const outcome = sale.hold(randomBytes(16).toString("hex"), seats, new Date());
if (outcome.result === "sold out") {
return outcome;
}
const row = await insertOrder(outcome.order, {
showId: show.id, buyerName: buyer.name, buyerEmail: buyer.email, lines, totalCents,
}, client);
return { result: "held", row } as const;
});
if (held.result === "sold out") {
return held;
}
// The payment service is called after the commit, so no transaction stays
// open while it answers.
const payment = await createPayment(totalCents, held.row.token);
await savePayment(held.row.id, payment.id, payment.payUrl);
return { result: "held", payUrl: payment.payUrl };
}
createHold is gone; holdSeats replaces it. The call to the payment service stays outside the transaction, because it is a request over the network. Inside, it would keep the transaction open, and in Step 4 the sale’s row lock, for as long as the provider takes to answer.
Last, the route. In src/sales/routes/holds.ts, remove the import from ../db/orders.ts, import holdSeats instead of createHold, and replace everything after the check of the name and email with this (two excerpts):
import { holdSeats } from "../services/holds.ts";
const hold = await holdSeats(show, { name, email }, lines);
if (hold.result === "sold out") {
response.status(409).send(showPage(show, `Sorry, only ${hold.seatsLeft} seats are left.`));
return;
}
response.redirect(303, hold.payUrl);
The route now reads the form and answers. It knows nothing about seats.
Pause and predict: the rule lives in one method now, and the check and the insert run in one transaction. How many of the 50 buyers get the last seat?
Run npm run check and npm test.
What you should see: no tsc errors. The migration runs, the four new domain tests pass, and the load test still fails (an excerpt from one run):
Applied 019_create_sales.sql
...
✖ fifty buyers at once get the last seat once (163.198592ms)
ℹ tests 35
ℹ suites 0
ℹ pass 34
ℹ fail 1
...
actual: { held: 9, refused: 41 },
expected: { held: 1, refused: 49 },
Fewer buyers get the seat than before, and still more than one. Each transaction now holds a pool connection from BEGIN to COMMIT, so fewer of them run at the same moment. But a transaction that overlaps another reads the orders before the other commits, as Read Committed promises. So it sees a free seat, inserts, and commits.
The rule is in the right place now, and the data is still not protected. Commit anyway, so the next step is one small diff:
git add -A
git commit -m "Hold seats through the Sale aggregate"
Step 4: Save the sale with a version check
Why: two copies of one sale must not both be saved. The version tells them apart.
What to do: in src/sales/db/sales.ts, add the save, and let changeSale try again when the save finds a newer version. Replace changeSale with this (an excerpt; loadSale and the imports stay as they are):
export class SaleChangedError extends Error {}
// Stores that the sale changed, before the command writes its orders. If
// another command saved the sale after this one loaded it, the version in
// the table has moved on, the UPDATE matches no row, and the command fails.
export async function saveSale(sale: Sale, client: pg.PoolClient): Promise<void> {
const result = await client.query(
"UPDATE sales.sales SET version = version + 1 WHERE show_id = $1 AND version = $2",
[sale.showId, sale.version],
);
if (result.rowCount === 0) {
throw new SaleChangedError(`The sale of show ${sale.showId} changed after version ${sale.version}.`);
}
}
const ATTEMPTS = 3;
// Loads the sale of one show and runs one command on it, in one transaction.
// When another command saved the sale first, it runs again on fresh data.
export async function changeSale<T>(
showId: number,
command: (sale: Sale, client: pg.PoolClient) => Promise<T>,
): Promise<T> {
// findShow takes its own connection from the pool, so it runs before this
// command takes one. Otherwise many waiting commands could use up the pool.
const show = await findShow(showId);
if (show === undefined) {
throw new Error(`There is no show ${showId}.`);
}
for (let attempt = 1; ; attempt++) {
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await command(await loadSale(show, client), client);
await client.query("COMMIT");
return result;
} catch (error) {
await client.query("ROLLBACK");
if (!(error instanceof SaleChangedError) || attempt === ATTEMPTS) {
throw error;
}
} finally {
client.release();
}
}
}
saveSale is the first write of every command. So the loser waits on the sale’s row and finds 0 rows before it writes anything else, and the rollback has nothing else to undo. A retry runs the whole command again, from the load, because the old copy of the sale is out of date. Three attempts is our choice; the exercise shows what it costs.
In src/sales/services/holds.ts, import saveSale and call it before the insert (two excerpts):
import { changeSale, saveSale } from "../db/sales.ts";
await saveSale(sale, client);
const row = await insertOrder(outcome.order, {
A refused hold does not call saveSale, because it changes nothing. In the route, a sale that changed three times in a row becomes a page that asks the buyer to try again, instead of an error (two excerpts):
import { SaleChangedError } from "../db/sales.ts";
let hold;
try {
hold = await holdSeats(show, { name, email }, lines);
} catch (error) {
if (!(error instanceof SaleChangedError)) {
throw error;
}
response.status(503).send(showPage(show, "Many buyers are holding seats right now. Please try again."));
return;
}
Run npm run check and npm test.
What you should see: no tsc errors, and all 35 tests pass (an excerpt):
✔ fifty buyers at once get the last seat once (151.363839ms)
...
ℹ tests 35
ℹ suites 0
ℹ pass 35
ℹ fail 0
One buyer holds the last seat, and the other 49 see “Sorry, only 0 seats are left.” The losers of the first round load the sale again, see version 2 and no free seat, and answer 409 without saving. You can see the check on its own in psql. After the tests, show 3 is the load test’s show; your versions may differ:
docker exec tinytickets-db psql -U postgres -d tinytickets_test -c "SELECT show_id, version FROM sales.sales ORDER BY show_id"
docker exec tinytickets-db psql -U postgres -d tinytickets_test -c "UPDATE sales.sales SET version = version + 1 WHERE show_id = 3 AND version = 2" -c "UPDATE sales.sales SET version = version + 1 WHERE show_id = 3 AND version = 2"
What you should see:
show_id | version
---------+---------
1 | 5
2 | 9
3 | 2
(3 rows)
UPDATE 1
UPDATE 0
The second UPDATE asks for a version that is gone, and changes nothing. That UPDATE 0 is the rowCount 0 that saveSale turns into SaleChangedError. Commit:
git add -A
git commit -m "Save the sale with a version check, and try again on a conflict"
Step 5: Send payments through the Sale
Why: Module 6 left one race open. markOrderPaid loads an order with no lock and no version, so two webhooks for the same payment can both pay the same held order. The concepts section showed a second reason: a payment changes the seats an order takes.
What to do: first, break it. Add this test at the end of app.test.ts:
test("two webhooks for one payment at once issue its tickets once", async () => {
const { token, payment_id } = await holdOneTicket();
const paid = {
id: "evt_8",
type: "payment.succeeded",
data: { payment_id, amount_cents: 2150, currency: "usd", metadata: { order_ref: token } },
};
await Promise.all([webhook(paid), webhook(paid)]);
const tickets = await pool.query(
`SELECT count(*)::int AS count
FROM sales.tickets JOIN sales.orders ON orders.id = tickets.order_id
WHERE orders.token = $1`,
[token],
);
assert.equal(tickets.rows[0].count, 1);
});
A provider may send a webhook again when the first try does not get through, so two copies of one payment can arrive close together. Run npm test.
What you should see (an excerpt):
✖ two webhooks for one payment at once issue its tickets once (19.980044ms)
ℹ tests 36
...
ℹ pass 35
ℹ fail 1
...
2 !== 1
Both webhooks loaded a held order, both called pay, and both inserted a ticket. The order took one seat, and the buyer got two tickets. Now replace src/sales/services/orders.ts with this:
import { randomBytes } from "node:crypto";
import type { Cents } from "#money";
import { enqueue } from "#platform";
import { findOrderByToken, saveOrderState } from "../db/orders.ts";
import { changeSale, saveSale } from "../db/sales.ts";
import { findShow } from "#shows";
import { insertTicket } from "../db/tickets.ts";
import { ticketPriceCents } from "./pricing.ts";
// A payment in Sales' words (see "Payment" in GLOSSARY.md).
export type Payment = { orderToken: string; paymentId: string; amountCents: Cents };
export async function markOrderPaid(payment: Payment): Promise<void> {
const row = await findOrderByToken(payment.orderToken);
if (row === undefined) {
return;
}
const outcome = await changeSale(row.show_id, async (sale, client) => {
const outcome = sale.pay(row.token, new Date());
await saveSale(sale, client);
await saveOrderState(sale.order(row.token), client);
if (outcome !== "paid") {
return outcome;
}
await enqueue("send_confirmation", { payment });
const show = (await findShow(row.show_id))!;
for (const line of row.lines) {
for (let i = 0; i < line.quantity; i++) {
await insertTicket(client, {
showId: show.id, orderId: row.id, buyerName: row.buyer_name, kind: line.kind,
code: randomBytes(4).toString("hex").toUpperCase(),
priceCents: ticketPriceCents(show.price_cents, line.kind),
});
}
}
if (payment.amountCents !== row.total_cents) {
throw new Error(`Order ${row.token}: paid ${payment.amountCents} cents, expected ${row.total_cents}.`);
}
return outcome;
});
if (outcome === "too late") {
console.error(`Order ${row.token} was cancelled before payment ${payment.paymentId} came. Refund it by hand.`);
}
}
export async function cancelOrder(payment: Payment): Promise<void> {
const row = await findOrderByToken(payment.orderToken);
if (row === undefined) {
return;
}
await changeSale(row.show_id, async (sale, client) => {
if (sale.cancel(row.token, new Date()) === "cancelled") {
await saveSale(sale, client);
await saveOrderState(sale.order(row.token), client);
}
});
}
The row is read first, outside the transaction, only to find the order’s show; its show_id, lines and total never change after the insert. The decision comes from the sale loaded inside the transaction. The log line moved after the commit, so a retry cannot print it twice. cancelOrder now has a transaction too, which Module 6 listed as missing.
The rest is unchanged on purpose. The email job is still queued on another connection, before the tickets, and the amount check still comes last; Module 9 fixes both. Then let saveOrderState accept the view that sale.order returns, in src/sales/db/orders.ts (an excerpt):
export async function saveOrderState(order: OrderView, client: pg.PoolClient | pg.Pool = pool): Promise<void> {
Run npm run check and npm test.
What you should see: no tsc errors, and all 36 tests pass (an excerpt):
✔ fifty buyers at once get the last seat once (146.580007ms)
✔ two webhooks for one payment at once issue its tickets once (21.825931ms)
...
ℹ tests 36
ℹ suites 0
ℹ pass 36
ℹ fail 0
The second webhook’s saveSale waited for the first, found 0 rows and ran again. On the second try, it loaded a paid order, pay returned "already paid", and it issued nothing. Commit:
git add -A
git commit -m "Send payments and failed payments through the Sale"
Step 6: Update the glossary, the README and the code figure
Why: “Sale” in the glossary still says “Code: none”, and the code now has an aggregate with that name.
What to do: in GLOSSARY.md, replace the “Sale” entry with this:
## Sale
The sale of one show: the time when buyers can hold its seats, the seats,
and every order for them. Big sales open at 10:00. The orders that take
seats (paid orders, and holds that have not run out) never take more seats
than the show has. A hold, a payment or a failed payment changes the sale,
and two of them never change the same sale at once.
- Context: Sales.
- Code: the aggregate `Sale` (`src/sales/domain/sale.ts`), with `hold`,
`pay`, `cancel` and `seatsLeft`; its orders are `Order` entities. Table
`sales.sales`, one row per show with a `version`; `changeSale` and
`saveSale` (`src/sales/db/sales.ts`). A show is on sale as soon as its row
is in `shows.shows` (see the hotspot under "Sale opened" in `BOARD.md`).
- Do not say: sale, for one order.
In the “Hold” entry, the code line names Sale.hold and holdSeats instead of createHold:
- Code: `sales.orders.hold_expires_at`; `HOLD_MINUTES` and `Order.hold`
(`src/sales/domain/order.ts`); `Sale.hold` (`src/sales/domain/sale.ts`);
`holdSeats` (`src/sales/services/holds.ts`); the job `expire_holds`
(`src/sales/jobs/expire-holds.ts`).
In the “Order” entry, the code line gets one sentence, “An order belongs to the sale of its show, and the web app changes it only through Sale.”:
- Code: the entity `Order` (`src/sales/domain/order.ts`), with `pay`,
`cancel` and `holdsSeats`. An order belongs to the sale of its show, and
the web app changes it only through `Sale`. Table `sales.orders`, read
and written through `orderFromRow` and `saveOrderState`
(`src/sales/db/orders.ts`); the CHECK `orders_one_state` keeps one state
per row. The lines: column `sales.orders.lines`, type `OrderLine`
(`src/sales/services/pricing.ts`).
In README.md, add this paragraph after the one about the Order entity. In the “Files” block, change 001 to 018 to 001 to 019.
`src/sales/domain/sale.ts` holds the `Sale` aggregate: the seats of one show
and its orders, with the rule that the orders never take more seats than the
show has. Holds and payments change a sale through `changeSale`
(`src/sales/db/sales.ts`), which checks the sale's `version` when it saves,
and tries again when another request saved the same sale first.
CONTEXT-MAP.md does not change, because Sales already depended on Shows. Figure 5 is the code figure with the new parts marked.
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Shows}, {Sales}, {Payouts} ..> money/ the shared kernel (#money)
Inside {Sales}: routes/, services/ ..> db/ ..> domain/
domain/ the Sale aggregate NEW: root Sale, its Order
entities; it imports nothing outside domain/
db/sales.ts NEW changeSale, saveSale: one sale per
transaction, saved with its version;
..> {Shows} for the number of seats, by show ID
routes/, services/, jobs/ ..> acl/ ACL ..> [Payment provider]
Only acl/ knows the provider's webhook body.
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client, the organizer dashboard.
Every context ..> platform/. platform/ ..> money/.
app.ts and worker.ts ..> each #.
Figure 5: the arrows between contexts did not change; inside Sales, only db/ imports domain/, and the seat rule lives in the Sale.
Run the checks:
npm run check
npm test
What you should see: npm run check prints no errors, and npm test passes all 36 tests. The end of its output, from one run:
✔ a hold takes seats until it runs out (0.196995ms)
✔ a sale holds seats until it has none left (1.910411ms)
✔ a hold that ran out gives its seats to the next buyer (0.23244ms)
✔ a paid order keeps its seats after its hold would have run out (2.162485ms)
✔ two copies of one sale both give away its last seat (0.249004ms)
✔ a $12 ticket costs 1200, 960 for a student, 1700 as VIP (1.180757ms)
✔ one student ticket pays the booking fee (0.284861ms)
✔ four tickets or more pay no booking fee (0.193977ms)
✔ a context imports another context only through its # entry (11.52752ms)
ℹ tests 36
ℹ suites 0
ℹ pass 36
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
Commit:
git add -A
git commit -m "Describe the Sale in the glossary"
How two buyers and the last seat work now
Follow two buyers, Ana and Ben, who press “Hold my seats” for the last seat of show 7 at 10:00 (Figure 6):
- Both requests reach
holdRoutes, which reads the form and callsholdSeats.holdSeatsadds up the seats and callschangeSale(7, command). - Each
changeSaleasks Shows for show 7 throughfindShow, which returns 200 seats. Then each takes its own connection and runsBEGIN. - Each
loadSalereads version 4 fromsales.salesand the orders of show 7 fromsales.orders, and builds aSalewithSale.restore. - Each command calls
sale.hold(token, 1, now). Both copies see one free seat, so both return"held"with a new heldOrder. - Ana’s command runs
saveSalefirst: version 4 becomes 5, and the row stays locked until her commit. It inserts her order and commits. Her payment page is created after the commit. - Ben’s
saveSalewaits for that lock, then matches no row. It throwsSaleChangedError, andchangeSalerolls back. changeSaleruns Ben’s command again. It loads version 5 and Ana’s order, andholdreturns"sold out"with 0 seats left. Nothing is saved, and the route answers 409.
(Ana) --> [Web app] {Sales} routes/holds.ts --> services/holds.ts holdSeats
{Sales} db/sales.ts changeSale ..> {Shows} findShow(7): 200 seats
BEGIN
loadSale <-- [[sales.sales]] version 4, [[sales.orders]] of show 7
{Sales} domain/sale.ts Sale.hold --> "held", Order.hold
saveSale --> [[sales.sales]] version 4 --> 5 (row locked)
insertOrder --> [[sales.orders]]
COMMIT
createPayment --> [Payment provider] after the commit
(Ana) <-- 303 to the payment page
(Ben) --> ... the same, until saveSale: version 4 is gone, 0 rows
ROLLBACK, then again: loadSale version 5 --> Sale.hold --> "sold out"
(Ben) <-- 409 "Sorry, only 0 seats are left."
Figure 6: both buyers pass the check in memory; only one save matches the version.
A payment follows the same path with sale.pay in step 4, and it waits for or retries against the holds of the same show. The worker’s expireHolds does not go through the sale. It still cancels holds that ran out with one SQL UPDATE, and it does not move the version. That stays safe for the seat rule, because it only cancels holds that every Sale already counts as free.
Going deeper
A version, a row lock, Serializable or a constraint
TinyTickets saves the sale with a version. Figure 7 compares it with the other ways PostgreSQL can stop the second hold.
| Way to stop the second hold | What happens to the second request | What it costs | When it wins |
|---|---|---|---|
| Version column on the root (this module) | its UPDATE matches 0 rows; it runs again |
a retry path; under a crowd many requests fail and start again | conflicts are rare; the work spans a user’s think time |
SELECT ... FOR UPDATE on the root’s row |
it waits for the first to commit | writers queue on one row; a slow transaction blocks the rest; rows locked in different orders can deadlock | many writers on one aggregate, in short transactions |
SERIALIZABLE transactions |
PostgreSQL cancels it with SQLSTATE 40001, and it must run again |
every transaction that can conflict must retry; extra tracking work in the database | many rules across many tables, and you do not want to reason about each one |
A constraint (UNIQUE, CHECK, exclusion) |
PostgreSQL refuses the row | the rule lives in the schema, often a second time | the rule is about one row or one key |
Figure 7: four ways to stop the second hold, from the one this module uses to the one that needs no code.
The PostgreSQL 18 docs describe the second and third rows in 13.3, Explicit Locking and 13.2.3, Serializable Isolation Level. Under Repeatable Read, the version UPDATE would not return 0 rows. PostgreSQL raises “could not serialize access due to concurrent update” instead, so a repository written for one isolation level must handle both if the level can change (13.2.2).
The seat rule cannot be a constraint. A CHECK sees one row, and UNIQUE and exclusion constraints compare one row with another. None of them can add up the seats of every order of a show.
At 10:00, the second row of the table may suit TinyTickets better than the first. Every buyer of one show writes to one sale, so the conflicts are not rare. The exercise measures this with the same load test.
Martin Fowler’s catalog of enterprise patterns names the version technique Optimistic Offline Lock: it detects a conflict and rolls the transaction back. Its counterpart, Pessimistic Offline Lock, prevents the conflict instead. The Unit of Work that wraps a transaction is in Design Patterns in Plain Words, Module 7, so this module does not teach it again.
How big an aggregate should be
Vernon’s rule in Part I (p. 4 and 5) is “design small aggregates”: the root, plus only what must stay consistent with it. Large aggregates load many objects to change one, and they fail more often under concurrent use. He reports Niclas Hedhman’s experience that on one project, about 70% of aggregates were a root with value objects. Vernon adds that this is no rule for every model.
The same essays keep bigger aggregates when the rule is real. Vernon (Part I, p. 5) cites Evans’ purchase order, whose lines must not exceed an approved total. In Part III, “Gaining Insight Through Discovery” (p. 13 to 15), his team estimates the size of a backlog item with its tasks and keeps them together.
TinyTickets’ Sale is the large kind. It loads every order of a show, and every hold and payment of that show shares one version. For Leo’s club, with 200 seats, that is a few hundred rows. For a show of 15,000 seats, every command loads thousands of orders, and every buyer of the show conflicts with every other.
The usual way out is a smaller aggregate: one per seat, or per block of seats, each with its own version. The cost moves to the rules that span them, such as “a show cannot sell more than it has”, which then needs a count kept somewhere else. That choice belongs to a later stage of the story, when the shows get that big.
What the authors meant, and where they disagree
Evans (Reference, p. 16) asks you to “use the same aggregate boundaries to govern transactions and distribution”. Inside a boundary, rules apply at once. Across boundaries, updates follow later. If the boundaries make those choices hard, he reads it as a sign that a concept is missing from the model.
Evans lets outside objects hold references to the root only. Vernon goes further: other aggregates by identity only (Part II, p. 8). He also names an exception for query performance (p. 11), and his own team breaks the rule in Part III (p. 15). This is a difference in strength, not a contradiction.
On one aggregate per transaction, Microsoft’s eShop guide disagrees in part. Its page “Domain events: Design and implementation” (updated 2024) accepts several aggregates in one transaction when they are side effects of one command in one relational database. Vernon would make such side effects eventually consistent, unless one of his four reasons applies.
Some practitioners have moved away from fixed boundaries. The Dynamic Consistency Boundary, described at dcb.events, chooses the boundary for each decision by querying the events that decision needs, with an optimistic check on that query. Its example is a course with a capacity and a student who may join at most ten courses, two rules no single aggregate covers. It assumes an event store, which TinyTickets does not have; Module 10 studies event sourcing.
What changed recently
PostgreSQL 18, released on September 25, 2025, lets RETURNING name old and new in INSERT, UPDATE, DELETE and MERGE (release notes). So one version save can return the version it replaced and the one it wrote. One run against the test database (your versions will differ):
docker exec tinytickets-db psql -U postgres -d tinytickets_test -c "UPDATE sales.sales SET version = version + 1 WHERE show_id = 3 AND version = 2 RETURNING old.version, new.version"
version | version
---------+---------
2 | 3
(1 row)
UPDATE 1
The isolation levels and the re-check of WHERE in this module did not change in PostgreSQL 18. The 13.2 text matches what the load test shows on 18.7.
On the DDD side, the definition of an aggregate has not changed in the primary sources since Evans’ Reference (2015) and Vernon’s essays (2011). What is new is the challenge from event-store approaches such as DCB.
When an aggregate is too much
Skip the aggregate when one database constraint says the whole rule. “A ticket is scanned once” is UNIQUE (ticket_code) on door.scans, and Door has no aggregate for it. PostgreSQL refuses the second scan, and the route turns that into a 409.
Skip the version when nothing has an invariant across rows. An organizer’s name and payout account are edited by one person, and any value is allowed, so the last write may win. And if a hot aggregate meets a crowd, as one show does at 10:00, a row lock may cost less than a version, even inside a well-drawn boundary. These limits are our judgment.
Check yourself
- Paying never adds an order. Why does a payment still go through the Sale and save its version?
Answer
A payment can change how long an order takes seats. A payment made before the hold runs out makes the order paid, so it keeps its seats forever. If that transaction commits after a hold loaded the sale and counted those seats as free, both would commit. Saving the payment through the sale’s version makes one of them start again.
- In Step 3, the check and the insert ran in one transaction. Why did more than one buyer still get the last seat?
Answer
PostgreSQL’s default isolation level is Read Committed, where each statement sees only rows committed before it began. Each transaction read the orders before the others had committed their inserts. So each saw a free seat, and nothing in a plain INSERT conflicted with the others.
- What does the losing request’s
UPDATE ... AND version = $2return, and why mustsaveSalethrow?
Answer
It waits for the winner’s row lock, then PostgreSQL checks the WHERE clause against the committed row, whose version moved on. It matches no row, so pg returns rowCount 0 with no error. Without the throw, the command would insert its order and commit.
- Why does the Sale hold
showIdand a number of seats, and not aShowobject?
Answer
The show belongs to the Shows context. Holding only its ID means the Sale cannot change the show by accident, loads less, and copies only what its rule needs, the number of seats. It also keeps each command to one aggregate, the sale.
- When would
SELECT ... FOR UPDATEon the sale’s row be a better choice than the version?
Answer
When many writers change one aggregate at the same time in short transactions, as every buyer of one show does at 10:00. With the version, most of them fail and start again; with the lock, they wait in line. The cost of the lock is that a slow transaction blocks everyone behind it.
Exercise: measure what the version costs at 10:00
Kofi’s show has 100 seats, not one. Copy the load test into a new test, “fifty buyers at once all get a seat when there are enough”, and change three things:
- the show is named
'Big Show'and has100seats - the test counts the 503 answers as
busy, instead of the 409s asrefused - it expects
{ held: 50, busy: 0 }
Run it, and read the numbers.
Then make it pass by changing one line in src/sales/db/sales.ts, and check that the last-seat test still passes. Undo everything at the end.
Solution
The new test, at the end of app.test.ts:
test("fifty buyers at once all get a seat when there are enough", 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, 'Big Show', current_date + 30, '19:00', 'Test Club', 100, 1200)
RETURNING id`,
);
const page = `/shows/${show.rows[0]!.id}`;
await post(`${page}/hold`, { ...buyer, standard: "1" });
const buyers = Array.from({ length: 50 }, () => buyer);
const opened = await Promise.all(buyers.map(() => fetch(`${site}${page}`)));
await Promise.all(opened.map((answer) => answer.text()));
const answers = await Promise.all(buyers.map((one) => post(`${page}/hold`, { ...one, standard: "1" })));
const held = answers.filter((answer) => answer.status === 303).length;
const busy = answers.filter((answer) => answer.status === 503).length;
assert.deepEqual({ held, busy }, { held: 50, busy: 0 });
});
One run printed this (an excerpt; another run gave 19 and 31):
✖ fifty buyers at once all get a seat when there are enough (216.002419ms)
...
actual: { held: 20, busy: 30 },
There are seats for everyone, and 30 buyers were asked to try again. In each round, one save wins and the others conflict. After three attempts, the buyers who lost every round get the 503 page.
The one-line fix locks the sale’s row when it is loaded, in loadSale:
"SELECT version FROM sales.sales WHERE show_id = $1 FOR UPDATE",
Now the second command waits at the SELECT until the first commits, and then reads the new version and the new order. Nobody loads a stale copy, so saveSale never finds 0 rows. Both load tests pass, and so do the other 35 tests.
The cost is that holds for one show now run one at a time, and a slow command holds up every buyer behind it. The version stays as a second guard, and it still matters for any command that loads a sale without the lock. Undo the exercise:
git checkout app.test.ts src/sales/db/sales.ts
Cheat sheet
Cheat sheet
- Aggregate: the entities and values one rule needs at once, loaded, changed and saved as one unit. Not SQL’s
count().- Root: the one entity outside code may call; it checks the invariant on every change and hands out read-only views.
- Consistency boundary: drawn by a real rule, not by tables; a payment is inside because it changes which seats are taken.
- Reference by ID: hold
showId, never aShow; copy in only what the rule needs.- One aggregate per transaction: each command changes one sale; the email and the payout can follow later (Module 9).
- Read Committed: a check and an insert in one transaction still race; each statement sees only committed rows.
- Version column:
UPDATE ... WHERE version = $n; 0 rows is a conflict, so throw, roll back and run the command again.- Costs: every command loads the whole sale; at 10:00 conflicts are common, and a row lock may cost less.
- Skip it: when a
UNIQUEorCHECKsays the whole rule, or no rule spans rows.
Figure 8 is the whole module in one picture.
Load changeSale(showId) BEGIN; Sale.restore(showId, seats, version, orders)
Decide sale.hold / pay / cancel the root checks the seat rule in memory
Save saveSale(sale) UPDATE ... SET version = version + 1
WHERE show_id = $1 AND version = $2
Conflict 0 rows SaleChangedError: ROLLBACK, load again, up to 3 tries
Write insertOrder, saveOrderState then COMMIT
After createPayment, the log line outside the transaction
Figure 8: every hold and payment loads one sale, decides in its root, and saves only if nobody saved it first.
The seat rule now lives in the Sale aggregate, and every hold and payment saves the sale with a version check. The load test gives the last seat once, and a repeated webhook issues its tickets once. All 36 tests pass. Next, Module 8 takes PostgreSQL and Express out of the domain, because Omar’s domain test needs a running database and half the team skips it.
Sources
- Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries, Domain Language, 2015 (CC BY 4.0). Aggregates (p. 16).
- Vaughn Vernon, “Effective Aggregate Design”, 2011: Part I: Modeling a Single Aggregate (p. 2 to 5), Part II: Making Aggregates Work Together (p. 8 to 11), Part III: Gaining Insight Through Discovery (p. 13 to 15).
- Martin Fowler, Optimistic Offline Lock, catalog of Patterns of Enterprise Application Architecture, 2002.
- Microsoft Learn, Domain events: Design and implementation, updated 2024.
- Dynamic Consistency Boundary.
- PostgreSQL 18 documentation: 13.2 Transaction Isolation, 13.3 Explicit Locking, 13.4 Data Consistency Checks at the Application Level, release notes.