On Tuesday at 10:00, three shows went on sale on TinyTickets, and one of them was Leo’s. Leo kept his dashboard open and reloaded it to watch the tickets go. Each reload took seconds.
“Is my page slowing down the buyers?” Leo asked.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
No buyer had complained about the Hold button that morning. Omar wrote a script that plays a 10:00 sale on his laptop, so that the team could answer Leo with a number.
This module separates the code that answers questions from the code that changes things, which is the idea behind CQRS. Leo’s dashboard stops counting every ticket on each load; each context answers for its own shows, and Sales and Door keep small tables of counts for the page. Then the module studies event sourcing, which goes one step further, and says why TinyTickets does not take it yet.
After this module, you can:
- tell a command from a query in TinyTickets, and say what CQRS separates when there is one database
- replace a query that reads four contexts’ schemas with one question to each context, put together for one page
- keep a table of counts for one page up to date from an outbox event, and keep it right when the job runs twice
- choose between a plain query, a materialized view and a table kept by a projection, and measure the choice under a 10:00 load
- say what event sourcing would change in TinyTickets, what it costs, and which signs would make it worth it
Where the code stands
Module 9 made Sales record TicketsIssued and save it in the outbox with the sale. The worker turns each event into jobs: the ticket email, and Door’s own list of tickets.
Commands go through the Sale aggregate, and one query still reads all four contexts. It is the organizer dashboard in src/platform/db/dashboard.ts, the exception Module 3 left for this module. Figure 1 is the code figure Module 9 ended with.
{Door} {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Sales} --> {Door} the event TicketsIssued, through the outbox
{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; save writes the
sale's events to the outbox
routes/ ..> acl/ ACL ..> [Payment provider]
Inside {Door}: routes/ ..> db/tickets.ts: its own list
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, the
organizer dashboard. Every context ..> platform/.
worker.ts subscribers: TicketsIssued --> send_confirmation,
add_tickets_at_door
Figure 1: the contexts as Module 9 left them; the dashboard in platform/ is the one piece of code that reads every schema.
One query that counts three years of tickets on every load
This is the dashboard’s query (an excerpt of src/platform/db/dashboard.ts):
`SELECT shows.id AS show_id, shows.name, shows.show_date::text AS show_date, shows.seats,
count(tickets.id) FILTER (WHERE orders.status = 'paid') AS tickets_sold,
coalesce(sum(tickets.price_cents) FILTER (WHERE orders.status = 'paid'), 0) AS gross_cents,
coalesce(sum(orders.quantity) FILTER (WHERE orders.status = 'held'), 0) AS seats_held,
count(scans.id) AS scanned,
payouts.amount_cents AS payout_cents,
payouts.paid_at AS paid_out_at
FROM shows.organizers
JOIN shows.shows ON shows.organizer_id = organizers.id
LEFT JOIN sales.orders ON orders.show_id = shows.id
LEFT JOIN sales.tickets ON tickets.order_id = orders.id
LEFT JOIN door.scans ON scans.ticket_code = tickets.code
LEFT JOIN payouts.payouts ON payouts.show_id = shows.id
WHERE organizers.id = $1
GROUP BY shows.id, payouts.amount_cents, payouts.paid_at
ORDER BY shows.show_date`,
Notice three things:
- It joins six tables from four schemas. Every order, ticket and scan of the organizer’s shows is read and counted again on each load, including shows that ended a year ago.
- The “Held” column counts every order whose status is
'held'. A hold that ran out still counts until the jobexpire_holdscancels it, up to a minute later. The rule inOrder.holdsSeatsalso checks the time, so the query is a second, older copy of that rule. count()andsum()returnbigint, whichpghands back as strings. Module 5 parsedgross_centsand left the three counts typed asnumber.
On the laptop, with the test data, none of this shows. Omar’s script fills the test database with a year of sales and then sends many requests at once. Save it as sale-day.ts in the project folder:
// A 10:00 sale on the laptop. It empties the test database, fills it with a
// year of shows, then times buyers' holds and organizers' dashboards that all
// arrive at once. Run it with: node --env-file=.env.test sale-day.ts
import type { AddressInfo } from "node:net";
import { app } from "./app.ts";
import { config, hashPassword, pool } from "#platform";
import { payApp } from "./fakes.ts";
await pool.query(
`TRUNCATE door.scans, door.tickets, payouts.payouts, sales.tickets, sales.orders, sales.sales,
shows.shows, shows.organizers, sessions, users, jobs, outbox RESTART IDENTITY`,
);
// 12 organizers, 20 shows each: shows 1 to 228 are over, and shows 229 to
// 240 go on sale at 10:00. The shows that are over sold 400,000 tickets, two
// to an order; two of every three were scanned, and each show has a payout.
await pool.query(
`INSERT INTO shows.organizers (name, payout_account)
SELECT 'Organizer ' || g, 'acct_' || g FROM generate_series(1, 12) g`,
);
await pool.query(
`INSERT INTO users (email, password_hash, organizer_id)
SELECT 'organizer' || g || '@tinytickets.example', $1, g FROM generate_series(1, 12) g`,
[await hashPassword("sale day")],
);
await pool.query(
`INSERT INTO shows.shows (organizer_id, name, show_date, doors_open, place, seats, price_cents)
SELECT 1 + (g - 1) % 12, 'Show ' || g, current_date - 400 + g, '19:00', 'A club', 3000, 1200
FROM generate_series(1, 228) g`,
);
await pool.query(
`INSERT INTO shows.shows (organizer_id, name, show_date, doors_open, place, seats, price_cents)
SELECT g, 'On sale ' || g, current_date + 30, '19:00', 'A club', 3000, 1200
FROM generate_series(1, 12) g`,
);
await pool.query(
`INSERT INTO sales.orders (token, show_id, buyer_name, buyer_email, quantity, lines, total_cents,
status, hold_expires_at, paid_at, payment_id)
SELECT 'order' || g, 1 + g % 228, 'Buyer', 'buyer@tinytickets.example', 2,
'[{"kind": "standard", "quantity": 2}]', 2550, 'paid', now(), now(), 'pay_' || g
FROM generate_series(1, 200000) g`,
);
await pool.query(
`INSERT INTO sales.tickets (show_id, order_id, buyer_name, code, kind, price_cents)
SELECT show_id, id, 'Buyer', 'T' || id || '-' || n, 'standard', 1200
FROM sales.orders, generate_series(1, 2) n`,
);
await pool.query("INSERT INTO door.tickets (code, show_id, kind) SELECT code, show_id, kind FROM sales.tickets");
await pool.query(
"INSERT INTO door.scans (ticket_code, scanned_by) SELECT code, 1 FROM sales.tickets WHERE id % 3 <> 0",
);
await pool.query(
`INSERT INTO payouts.payouts (organizer_id, show_id, gross_cents, fee_cents, amount_cents, transfer_id)
SELECT organizer_id, id, 0, 0, 0, 'tr_' || id FROM shows.shows WHERE id <= 228`,
);
await pool.query("ANALYZE");
payApp.listen(Number(new URL(config.paymentUrl).port));
const server = app.listen(0);
await new Promise((resolve) => server.once("listening", resolve));
const site = `http://localhost:${(server.address() as AddressInfo).port}`;
function post(path: string, fields: Record<string, string>, cookie = ""): Promise<Response> {
return fetch(`${site}${path}`, {
method: "POST", headers: { cookie }, body: new URLSearchParams(fields), redirect: "manual",
});
}
const cookies: string[] = [];
for (let organizer = 1; organizer <= 12; organizer++) {
const answer = await post("/login", { email: `organizer${organizer}@tinytickets.example`, password: "sale day" });
cookies.push((answer.headers.get("set-cookie") ?? "").split(";")[0]!);
}
// Each request resolves to the milliseconds its answer took.
async function timed(answer: Promise<Response>): Promise<number> {
const start = performance.now();
await (await answer).text();
return performance.now() - start;
}
// Each buyer holds two seats for one of the 12 shows on sale.
let buyers = 0;
const holds = (count: number) => Array.from({ length: count }, () => {
const buyer = ++buyers;
const fields = { name: "Ana", email: `buyer${buyer}@tinytickets.example`, standard: "2" };
return timed(post(`/shows/${229 + (buyer % 12)}/hold`, fields));
});
const dashboard = (cookie: string) => timed(fetch(`${site}/organizer`, { headers: { cookie } }));
// Every organizer has the dashboard open, and reloads it five times.
const dashboards = () => cookies.flatMap((cookie) => [1, 2, 3, 4, 5].map(() => dashboard(cookie)));
function report(label: string, times: number[]): void {
times.sort((a, b) => a - b);
const median = times[Math.floor(times.length / 2)]!;
const ms = (time: number) => `${time.toFixed(0).padStart(4)} ms`;
const count = String(times.length).padStart(3);
console.log(`${label.padEnd(29)} ${count} requests, median ${ms(median)}, slowest ${ms(times.at(-1)!)}`);
}
report("Quiet: one dashboard", [await dashboard(cookies[0]!)]);
report("Quiet: one hold", await Promise.all(holds(1)));
report("10:00, holds alone", await Promise.all(holds(120)));
const [holdTimes, dashboardTimes] = await Promise.all([Promise.all(holds(120)), Promise.all(dashboards())]);
report("10:00, holds with dashboards", holdTimes);
report("10:00, the dashboards", dashboardTimes);
await pool.end();
process.exit(0); // the web app and the fake payment service are still listening
The script writes the rows with SQL, because 400,000 tickets through the web app would take too long. Then it starts the web app and the fake payment service, and logs in as each organizer. It times one request alone, then 120 holds alone, then 120 holds with 60 dashboard loads at the same moment. Like the tests, it empties tinytickets_test before it starts, and the tests empty it again when they run.
Pause and predict: the holds take the same time in both 10:00 rounds, or the dashboards make them slower. Which is it, and by how much?
node --env-file=.env.test sale-day.ts
What you should see (one run on a laptop; your numbers will differ):
Quiet: one dashboard 1 requests, median 192 ms, slowest 192 ms
Quiet: one hold 1 requests, median 39 ms, slowest 39 ms
10:00, holds alone 120 requests, median 759 ms, slowest 811 ms
10:00, holds with dashboards 120 requests, median 1004 ms, slowest 2689 ms
10:00, the dashboards 60 requests, median 1912 ms, slowest 2715 ms
So the answer to Leo is yes. Alone, the slowest hold took 0.8 seconds. With the dashboards open, it took 2.7 seconds, and the dashboards themselves took about two seconds each.
The reason is one shared queue. pg.Pool keeps at most 10 clients, because pg-pool, the package behind it, sets max to 10 when you give none. A request that finds all 10 busy waits in a first-come queue.
One dashboard load took 190 ms alone, and it keeps a client while it counts. So the holds that arrive behind 60 dashboards wait for them (Figure 2).
(12 organizers) --> [Web app] GET /organizer, 60 at once
(120 buyers) --> [Web app] POST /shows/:id/hold, 120 at once
|
v
pg.Pool: 10 clients; everyone else waits in one queue
|
v
one dashboard load reads [[shows.organizers]] [[shows.shows]]
[[sales.orders]] [[sales.tickets]]
[[door.scans]] [[payouts.payouts]]
and counts every order, ticket and scan of the organizer's 20 shows
Figure 2: at 10:00, the buyers and the organizers wait in the same queue, and each dashboard keeps its client while it counts.
The script runs no worker and sends no payments, so the numbers leave out the jobs a real sale adds. A bigger pool would let more dashboards count at the same time, but each of them would still count every ticket. The fix has to make a dashboard load do less work.
Keep the script, because every step that changes the dashboard runs it again. Commit it:
git add -A
git commit -m "Add a script that plays a 10:00 sale"
Reading is a different job
A command changes the sale, a query answers a question
Bertrand Meyer named this split for the methods of a class. His Command-Query Separation principle says a method either does something and returns nothing (a command), or returns an answer and changes nothing (a query). His slides for a 2003 summer school put it in one line:
“Asking a question shouldn’t change the answer” (Meyer, “Principles of Library Design: The Eiffel Experience”, slide 25)
This “command” is the same idea as a CMD note on Module 2’s board, a request to change something. A query is a request for an answer that changes nothing.
Greg Young took the principle from methods up to whole objects. In his CQRS Documents (2010, p. 17), CQRS (Command Query Responsibility Segregation) splits one model into two: one that handles the commands and one that answers the queries. He says it started as Meyer’s principle, applied at a higher level.
TinyTickets already does half of this. Since Module 8, every command goes through an application service that loads a Sale, calls its methods and saves it. The SaleRepository port has saleOf and saleOfOrder and no search methods, because commands need nothing else.
The dashboard never loaded a Sale, and that was right. Young (p. 23) lists the problems of building screens from the domain model, and one of them is Leo’s page:
“Loading of multiple aggregates to build a DTO causes non-optimal querying” (Young, CQRS Documents, p. 23)
saleOf reads every order of a show, so a dashboard built from 20 Sale objects would read even more than the SQL does. Young’s answer (p. 21) is a thin read layer, a set of queries that read the database directly and return plain data, with no domain objects in between.
The dashboard’s query is a thin read layer, and skipping the domain is right for a query. The trouble is that it reads four contexts’ tables, copies a rule, and recomputes three years of sales on every load.
Rule: a command goes through the aggregate, because the aggregate keeps the rules; a query reads the data, because it changes nothing.
The cost is two ways to read the same rows, and a rule can end up in both, as “Held” did. A query that repeats a rule needs a test that pins it to the domain’s answer.
A read model is a table shaped for one page
A read model is data kept in the shape one screen or query needs, with no business rules of its own. Microsoft’s CQRS pattern page (2025) describes the read side the same way, as code that returns plain data and runs no validation. Udi Dahan’s “Clarified CQRS” (2009) puts it more briefly, as “One table for each view”.
You can keep a read model in the same PostgreSQL in three ways, and Figure 3 puts them side by side.
| Read model | How it stays current | What one load reads | How fresh | Reads other contexts’ schemas |
|---|---|---|---|---|
| A plain query (Step 1) | it is the tables | every row it counts | always | no, if each context answers for itself |
| A materialized view | a REFRESH on a schedule |
the stored rows | as of the last refresh | yes, as written below |
| A table kept by a projection (Steps 2 to 4) | a write after each change | one row per show | Door: always; Sales: one worker pass behind | no |
Figure 3: three read models in one database, from the least code to the most.
A materialized view is a query whose result PostgreSQL stores like a table, and recomputes when you run REFRESH MATERIALIZED VIEW. The PostgreSQL docs say its data need not be current, it can have indexes, and you cannot write to it directly. Run sale-day.ts from the problem section first, so the test database holds its 400,000 tickets. Then open psql with docker exec -it tinytickets-db psql -U postgres -d tinytickets_test, type \timing on, and try this:
CREATE MATERIALIZED VIEW organizer_dashboard AS
SELECT shows.organizer_id, shows.id AS show_id,
count(tickets.id) FILTER (WHERE orders.status = 'paid') AS tickets_sold,
coalesce(sum(tickets.price_cents) FILTER (WHERE orders.status = 'paid'), 0) AS gross_cents,
count(scans.id) AS scanned
FROM shows.shows
LEFT JOIN sales.orders ON orders.show_id = shows.id
LEFT JOIN sales.tickets ON tickets.order_id = orders.id
LEFT JOIN door.scans ON scans.ticket_code = tickets.code
GROUP BY shows.id;
SELECT * FROM organizer_dashboard WHERE organizer_id = 1 ORDER BY show_id LIMIT 3;
REFRESH MATERIALIZED VIEW CONCURRENTLY organizer_dashboard;
CREATE UNIQUE INDEX ON organizer_dashboard (show_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY organizer_dashboard;
REFRESH MATERIALIZED VIEW organizer_dashboard;
What you should see (from one run with \timing on, an excerpt):
SELECT 240
Time: 830.247 ms
organizer_id | show_id | tickets_sold | gross_cents | scanned
--------------+---------+--------------+-------------+---------
1 | 1 | 1754 | 2104800 | 877
1 | 13 | 1756 | 2107200 | 878
1 | 25 | 1756 | 2107200 | 878
(3 rows)
Time: 0.667 ms
ERROR: cannot refresh materialized view "public.organizer_dashboard" concurrently
HINT: Create a unique index with no WHERE clause on one or more columns of the materialized view.
CREATE INDEX
REFRESH MATERIALIZED VIEW
Time: 798.631 ms
REFRESH MATERIALIZED VIEW
Time: 773.630 ms
Reading the view took under a millisecond, and building it took 0.8 seconds. Each refresh takes that long again, because core PostgreSQL 18 recomputes the whole query. The first CONCURRENTLY failed, and the hint says why.
The REFRESH docs explain the two kinds. A plain refresh needs no index, and it tends to use fewer resources and finish sooner, as it did here. CONCURRENTLY refreshes “without locking out concurrent selects on the materialized view”, but only with a unique index on plain column names that covers every row.
The lock is the difference you would feel at 10:00. In one psql session, run BEGIN; and REFRESH MATERIALIZED VIEW organizer_dashboard; and leave the transaction open. In a second session, run this:
SET lock_timeout = '1s';
SELECT count(*) FROM organizer_dashboard;
What you should see (an excerpt):
ERROR: canceling statement due to lock timeout
LINE 1: SELECT count(*) FROM organizer_dashboard
^
Time: 1000.813 ms (00:01.001)
The locking docs say a plain refresh takes an ACCESS EXCLUSIVE lock, which conflicts with the lock every SELECT takes. So every dashboard load waits for the whole refresh. With CONCURRENTLY, the same SELECT in the second session returned 240 in about a millisecond, because that refresh takes an EXCLUSIVE lock, which still allows reads. Run ROLLBACK; in the first session and DROP MATERIALIZED VIEW organizer_dashboard; when you are done.
A materialized view is the least code here, one statement and a scheduled job. TinyTickets does not use it, for three reasons:
- It reads four contexts’ schemas, which is the exception this module removes.
- Every refresh recounts 400,000 tickets, even on a day with no sale.
- A “Held” column would be as old as the last refresh.
A projection keeps a read model up to date
A projection is the code that writes a read model from the changes on the write side, either from the tables or from the domain events. This is not the projection of a SQL course, which means the list of columns a SELECT returns.
TinyTickets uses two kinds, one per context, and Figure 4 compares them.
| Door: in the same statement as the scan | Sales: from TicketsIssued, after the commit |
|
|---|---|---|
| When the count changes | with the scan, in the same commit | when the worker next comes round |
| If the projection fails | the scan fails too | the job retries; the payment has committed |
| Who must know about the read model | insertScan |
only the subscriber list in worker.ts |
| Why running it twice is harmless | a code is scanned once (ON CONFLICT) |
it counts the show again from the tables |
Figure 4: two ways to feed a projection; Door chooses consistency, Sales chooses to keep the payment short and unaware of the dashboard.
The same-transaction kind is the simpler one. The count can never disagree with the scans, and no job is needed. Its cost is that every scan now also writes the count, so a bug in the count breaks the door, and all scans of one show wait for one row.
The event kind keeps the payment unaware of the page.
Module 9 built everything it needs. The event commits with the sale, and the worker turns it into one job per subscriber. Its costs come from Module 9 too. The count is behind until the worker comes round, which is eventual consistency, and a job can run twice.
A projection that adds numbers is not safe to repeat. A second run of “add two tickets” adds two more. There are two ways out, and Microsoft’s Event Sourcing pattern page (2026) names the same two for its projections:
- Remember what you counted. Write each event’s key in a table of processed events, in the same transaction as the count, as Richardson’s Idempotent Consumer does (Module 9). The table grows by one row per order, and rows that a migration counts must go in it too.
- Count again. Recompute the show’s numbers from the tables and overwrite the row. A second run writes the same numbers. Each run reads every sold ticket of the show.
TinyTickets counts again, because a show has at most a few thousand tickets and the index from Step 1 finds them. Step 3 breaks the first version so you can see why.
Give the dashboard its own reads, step by step
Each step says why, what to do, the code, and what you should see. Work in the project folder Module 9 left, with sale-day.ts added. The finished code is in the code/module-10/ folder of the course repository. If you kept the exercise from Module 4, your test counts are one higher.
Step 1: Ask each context about its own shows
Why: the dashboard reads four schemas in one query. Each context should answer for its own tables through its public entry, and the dashboard should only put the answers side by side. First, write down the “Held” rule as a test.
What to do: add this test at the end of app.test.ts:
// Leo's word "held" follows Order.holdsSeats: a hold that ran out holds no
// seats, even before the job expire_holds has cancelled it.
test("the dashboard counts a hold that ran out as free", 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, 'Held 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: "2" });
await post(`/shows/${showId}/hold`, { ...buyer, standard: "1" });
await pool.query(
"UPDATE sales.orders SET hold_expires_at = now() - interval '1 minute' WHERE id = (SELECT max(id) FROM sales.orders)",
);
const row = (await loadDashboard(1)).find((one) => one.show_id === showId)!;
assert.deepEqual([row.tickets_sold, row.seats_held], [0, 2]);
});
Run npm test.
What you should see (an excerpt):
✖ the dashboard counts a hold that ran out as free (20.409333ms)
ℹ tests 51
ℹ pass 50
ℹ fail 1
...
[
+ '0',
+ '3'
- 0,
- 2
]
Both problems from the query show up in one line. The numbers are strings, and the hold that ran out still counts, so three seats are held instead of two.
Now give each context its question. Save this migration as migrations/024_index_reads_by_show.sql:
-- Year 3: each context answers the organizer dashboard about its own shows
-- (see "Dashboard" in GLOSSARY.md). These indexes find one show's rows
-- without reading the whole table.
CREATE INDEX ON sales.tickets (show_id);
CREATE INDEX ON sales.orders (show_id) WHERE status = 'held';
CREATE INDEX ON door.tickets (show_id);
The second index holds only the held orders, which are a few at any time. Shows answers with the organizer’s shows. Add this function to src/shows/db/shows.ts, after listUpcomingShows, and add listShowsOf to the list of exports in src/shows/index.ts (an excerpt):
// The shows of one organizer, for the organizer dashboard.
export async function listShowsOf(organizerId: number): Promise<Show[]> {
const result = await pool.query<Show>(
`SELECT ${columns} FROM shows.shows WHERE organizer_id = $1 ORDER BY show_date`,
[organizerId],
);
return result.rows;
}
Sales answers with the tickets sold, the gross and the seats held. Save this as src/sales/db/show-sales.ts, and export it from src/sales/index.ts with export { salesOfShows } from "./db/show-sales.ts";:
import { parseCents } from "#money";
import type { Cents } from "#money";
import { pool } from "#platform";
export type ShowSales = { show_id: number; tickets_sold: number; gross_cents: Cents; seats_held: number };
// What Sales tells the organizer dashboard about each show: the tickets sold,
// what they sold for, and the seats held right now. Held follows the rule in
// Order.holdsSeats: a hold that ran out holds no seats.
export async function salesOfShows(showIds: number[]): Promise<ShowSales[]> {
const result = await pool.query<Omit<ShowSales, "gross_cents"> & { gross_cents: number }>(
`SELECT show_id,
coalesce(sold.tickets_sold, 0) AS tickets_sold,
coalesce(sold.gross_cents, 0) AS gross_cents,
coalesce(held.seats_held, 0) AS seats_held
FROM unnest($1::integer[]) AS show_id
LEFT JOIN (
SELECT tickets.show_id, count(*)::integer AS tickets_sold, sum(tickets.price_cents)::integer AS gross_cents
FROM sales.tickets JOIN sales.orders ON orders.id = tickets.order_id
WHERE tickets.show_id = ANY($1) AND orders.status = 'paid'
GROUP BY tickets.show_id
) AS sold USING (show_id)
LEFT JOIN (
SELECT show_id, sum(quantity)::integer AS seats_held
FROM sales.orders
WHERE show_id = ANY($1) AND status = 'held' AND hold_expires_at > now()
GROUP BY show_id
) AS held USING (show_id)`,
[showIds],
);
return result.rows.map((row) => ({ ...row, gross_cents: parseCents(row.gross_cents) }));
}
Notice three things:
unnest($1::integer[])makes one row per show asked for, so a show with no sales still gets a row with zeros.hold_expires_at > now()is the same test asholdsSeats, so “Held” no longer waits forexpire_holds. The rule is still written twice, in TypeScript and in SQL. The new test is what ties them together.- Every count is cast to
integer, whichpgreturns as a number. The gross still goes throughparseCents, as in Module 5.
Door answers with the scans. In src/door/db/scans.ts, add this function after insertScan, and export it from src/door/index.ts with export { scansOfShows } from "./db/scans.ts"; (an excerpt):
// How many people each show let in, for the organizer dashboard.
export async function scansOfShows(showIds: number[]): Promise<{ show_id: number; scanned: number }[]> {
const result = await pool.query<{ show_id: number; scanned: number }>(
`SELECT tickets.show_id, count(*)::integer AS scanned
FROM door.scans JOIN door.tickets ON tickets.code = scans.ticket_code
WHERE tickets.show_id = ANY($1)
GROUP BY tickets.show_id`,
[showIds],
);
return result.rows;
}
Door counts through its own list, door.tickets, which Module 9 gave it. Payouts answers with the amounts. Add this to src/payouts/db/payouts.ts, with import type { Cents } from "#money"; at the top, and export it from src/payouts/index.ts with export { payoutsOfShows } from "./db/payouts.ts"; (an excerpt):
// What each show paid its organizer, for the organizer dashboard.
export async function payoutsOfShows(showIds: number[]): Promise<{ show_id: number; amount_cents: Cents }[]> {
const result = await pool.query<{ show_id: number; amount_cents: Cents }>(
"SELECT show_id, amount_cents FROM payouts.payouts WHERE show_id = ANY($1)",
[showIds],
);
return result.rows;
}
amount_cents is an integer column with a CHECK, so it is typed Cents without a parse, as Module 5 decided.
Now the page that puts the four answers together. It cannot stay in src/platform/, because every context imports #platform, and a dashboard there would import every context back. It gets its own folder. Save this as src/dashboard/dashboard.ts:
import { scansOfShows } from "#door";
import type { Cents } from "#money";
import { payoutsOfShows } from "#payouts";
import { salesOfShows } from "#sales";
import { listShowsOf } from "#shows";
export type DashboardRow = {
show_id: number; name: string; show_date: string; seats: number;
tickets_sold: number; gross_cents: Cents; seats_held: number; scanned: number;
payout_cents: Cents | null;
};
// Everything Leo asked to see about his shows. Each context answers for its
// own schema, through its public entry, and this function puts the answers
// side by side. It changes nothing.
export async function loadDashboard(organizerId: number): Promise<DashboardRow[]> {
const shows = await listShowsOf(organizerId);
const ids = shows.map((show) => show.id);
const sales = new Map((await salesOfShows(ids)).map((row) => [row.show_id, row]));
const scans = new Map((await scansOfShows(ids)).map((row) => [row.show_id, row.scanned]));
const payouts = new Map((await payoutsOfShows(ids)).map((row) => [row.show_id, row.amount_cents]));
return shows.map((show) => {
const sold = sales.get(show.id)!;
return {
show_id: show.id, name: show.name, show_date: show.show_date, seats: show.seats,
tickets_sold: sold.tickets_sold, gross_cents: sold.gross_cents, seats_held: sold.seats_held,
scanned: scans.get(show.id) ?? 0,
payout_cents: payouts.get(show.id) ?? null,
};
});
}
DashboardRow lost paid_out_at, which the page never printed. Move dashboardPage from src/platform/pages/organizer.ts to a new file, src/dashboard/page.ts, with these imports above it (an excerpt):
import { formatDollars } from "#money";
import { escapeHtml, layout } from "#platform";
import type { DashboardRow } from "./dashboard.ts";
The route moves too. Save this as src/dashboard/routes.ts:
import express from "express";
import { requireLogin } from "#platform";
import type { User } from "#platform";
import { loadDashboard } from "./dashboard.ts";
import { dashboardPage } from "./page.ts";
export const dashboardRoutes = express.Router();
dashboardRoutes.get("/organizer", requireLogin, async (request, response) => {
const user: User = response.locals.user;
response.send(dashboardPage(await loadDashboard(user.organizer_id)));
});
And this as src/dashboard/index.ts:
// The organizer dashboard: a page that reads, and changes nothing. It is not
// a bounded context. Code outside src/dashboard/ imports it as "#dashboard".
export { loadDashboard } from "./dashboard.ts";
export { dashboardRoutes } from "./routes.ts";
Wire it in and clean up src/platform/:
- In
package.json, add"#dashboard": "./src/dashboard/index.ts",to"imports"after#platform. - In
app.ts, addimport { dashboardRoutes } from "#dashboard";, and putdashboardRoutesafterorganizerRoutesinapp.use. - Delete
src/platform/db/dashboard.ts. - Delete the
/organizerroute at the end ofsrc/platform/routes/organizer.ts, with its imports ofloadDashboard,UseranddashboardPage. - In
src/platform/pages/organizer.ts, only the login page is left, so its first line becomesimport { layout, notice } from "./layout.ts";.
Run npm run check.
What you should see:
app.test.ts(11,31): error TS2307: Cannot find module './src/platform/db/dashboard.ts' or its corresponding type declarations.
app.test.ts(371,46): error TS7006: Parameter 'one' implicitly has an 'any' type.
tsc names the one file that still imports the old query; the second error follows from the first. In app.test.ts, the import becomes import { loadDashboard } from "#dashboard";. Run npm run check (no errors) and npm test.
What you should see (an excerpt):
Applied 024_index_reads_by_show.sql
...
✔ the dashboard counts a hold that ran out as free (28.12027ms)
...
ℹ tests 51
ℹ suites 0
ℹ pass 51
ℹ fail 0
The boundary test from Module 3 passes too, because src/dashboard/ imports the contexts only through their # entries. Commit, and then play the sale day again:
git add -A
git commit -m "Ask each context about its own shows for the dashboard"
node --env-file=.env.test sale-day.ts
What you should see (one run; your numbers will differ):
Quiet: one dashboard 1 requests, median 92 ms, slowest 92 ms
Quiet: one hold 1 requests, median 36 ms, slowest 36 ms
10:00, holds alone 120 requests, median 759 ms, slowest 960 ms
10:00, holds with dashboards 120 requests, median 708 ms, slowest 2168 ms
10:00, the dashboards 60 requests, median 2197 ms, slowest 2265 ms
One dashboard alone takes half the time it did. At 10:00, though, the dashboards are no faster, and the slowest hold still waits 2.2 seconds.
In our reading, two things cause it. Each load still counts every ticket and scan of the organizer’s shows. And it now asks the pool for a client four times, going to the back of the queue each time.
Splitting the query fixed the boundaries and the “Held” rule. It did not change how much a load counts.
Step 2: Keep Sales’ counts in a read model
Why: the tickets sold and the gross of a show change only when a payment issues tickets. Counting them on every load repeats work that happens once per payment. Sales already publishes that moment as TicketsIssued.
What to do: save this migration as migrations/025_create_show_sales.sql:
-- Year 3: a read model of Sales for the organizer dashboard: the tickets sold
-- and the gross of each show. Only the job count_sales writes it, after the
-- event TicketsIssued, and no command reads it.
CREATE TABLE sales.show_sales (
show_id integer PRIMARY KEY,
tickets_sold integer NOT NULL CHECK (tickets_sold >= 0),
gross_cents integer NOT NULL CHECK (gross_cents >= 0)
);
-- The tickets sold before this migration, counted once from the tables.
INSERT INTO sales.show_sales (show_id, tickets_sold, gross_cents)
SELECT tickets.show_id, count(*), sum(tickets.price_cents)
FROM sales.tickets JOIN sales.orders ON orders.id = tickets.order_id
WHERE orders.status = 'paid'
GROUP BY tickets.show_id;
The INSERT at the end is the first fill. A read model that starts empty would say a show sold nothing until its next payment. Save the projection as src/sales/jobs/count-sales.ts:
import { pool } from "#platform";
// The projection behind Sales' read model: whenever an order's tickets are
// issued, it adds them to the show's row in sales.show_sales.
export async function countSales(event: { orderToken: string }): Promise<void> {
await pool.query(
`INSERT INTO sales.show_sales (show_id, tickets_sold, gross_cents)
SELECT tickets.show_id, count(*), sum(tickets.price_cents)
FROM sales.orders JOIN sales.tickets ON tickets.order_id = orders.id
WHERE orders.token = $1
GROUP BY tickets.show_id
ON CONFLICT (show_id) DO UPDATE
SET tickets_sold = show_sales.tickets_sold + excluded.tickets_sold,
gross_cents = show_sales.gross_cents + excluded.gross_cents`,
[event.orderToken],
);
}
It reads the order’s tickets from Sales’ own tables, because the event carries no prices. Export it from src/sales/index.ts with export { countSales } from "./jobs/count-sales.ts";. In worker.ts, import it from #sales, subscribe it, and give it a handler (two excerpts):
TicketsIssued: ["send_confirmation", "add_tickets_at_door", "count_sales"],
count_sales: countSales,
The payment command did not change; only the worker’s list gained a subscriber. Now let salesOfShows read the table. In src/sales/db/show-sales.ts, replace the sold subquery with one line, and update the comment (an excerpt):
// What Sales tells the organizer dashboard about each show: the tickets sold
// and what they sold for, from the read model sales.show_sales, and the seats
// held right now. Held follows the rule in Order.holdsSeats: a hold that ran
// out holds no seats.
FROM unnest($1::integer[]) AS show_id
LEFT JOIN sales.show_sales AS sold USING (show_id)
“Held” stays a live query. Holds change by the second at 10:00, and the partial index finds the few held orders at once.
The tests must empty the new table. In app.test.ts, the TRUNCATE becomes this (an excerpt):
`TRUNCATE door.scans, door.tickets, payouts.payouts, sales.tickets, sales.orders, sales.sales,
sales.show_sales, shows.shows, shows.organizers, sessions, users, jobs, outbox RESTART IDENTITY`,
Leo asked the plain question this raises: does a ticket show on his dashboard as soon as it is paid? Write it as a test at the end of app.test.ts:
// Leo's question: does a ticket show on the dashboard as soon as it is paid?
test("the dashboard counts a payment once the worker has run", 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, 'Count 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: "2" });
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_12",
type: "payment.succeeded",
data: { payment_id, amount_cents: 2550, currency: "usd", metadata: { order_ref: token } },
});
const sold = async () => (await loadDashboard(1)).find((row) => row.show_id === showId)!.tickets_sold;
const beforeWorker = await sold();
await runWorker();
assert.deepEqual([beforeWorker, await sold()], [0, 2]);
});
Run npm run check and npm test.
What you should see: no tsc errors, and every test passes (an excerpt):
Applied 025_create_show_sales.sql
...
✔ the dashboard counts a payment once the worker has run (55.467344ms)
...
ℹ tests 52
ℹ suites 0
ℹ pass 52
ℹ fail 0
The answer to Leo is “not at once”. The payment had committed, but “Sold” said 0 until the worker came round. The older dashboard tests still pass, because runWorker runs in the tests before them. Commit:
git add -A
git commit -m "Keep Sales' counts for the dashboard in a read model"
Step 3: Make the projection safe to run twice
Why: Module 9 showed that a job can run twice. The worker can finish a handler and crash before finishJob deletes the row. count_sales adds numbers.
What to do: add this test at the end of app.test.ts. It copies the job before the worker runs it, which is what a crash after the handler leaves behind:
// A job can run twice (Module 9): here, as if the worker had crashed after
// count_sales and before finishJob deleted it.
test("a count job that runs twice counts the payment 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, 'Twice 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: "2" });
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_13",
type: "payment.succeeded",
data: { payment_id, amount_cents: 2550, currency: "usd", metadata: { order_ref: token } },
});
await relayEvents(subscribers);
await pool.query(
`INSERT INTO jobs (kind, payload)
SELECT kind, payload FROM jobs WHERE kind = 'count_sales' AND payload->>'orderToken' = $1`,
[token],
);
await runWorker();
const row = (await loadDashboard(1)).find((one) => one.show_id === showId)!;
assert.deepEqual([row.tickets_sold, row.gross_cents], [2, 2400]);
});
Pause and predict: the buyer paid for two $12 tickets, and the job ran twice. What does the dashboard say?
Run npm test.
What you should see (an excerpt):
✖ a count job that runs twice counts the payment once (47.357483ms)
ℹ tests 53
ℹ suites 0
ℹ pass 52
ℹ fail 1
...
[
+ 4,
+ 4800
- 2,
- 2400
]
The second run added the same two tickets again. Leo would see four tickets sold and $48.00, and Payouts would still pay him for two, because listSoldTicketPrices reads the tickets themselves. Commit the failing test, then make the job count again instead of adding. Replace src/sales/jobs/count-sales.ts with this:
import { pool } from "#platform";
// The projection behind Sales' read model: whenever an order's tickets are
// issued, it counts the show's sold tickets again from Sales' tables and
// writes the result. A second run of the same job writes the same numbers.
export async function countSales(event: { showId: number }): Promise<void> {
await pool.query(
`INSERT INTO sales.show_sales (show_id, tickets_sold, gross_cents)
SELECT $1, count(*), coalesce(sum(tickets.price_cents), 0)
FROM sales.tickets JOIN sales.orders ON orders.id = tickets.order_id
WHERE tickets.show_id = $1 AND orders.status = 'paid'
ON CONFLICT (show_id) DO UPDATE
SET tickets_sold = excluded.tickets_sold, gross_cents = excluded.gross_cents`,
[event.showId],
);
}
The job now reads showId from the event instead of orderToken. It runs the same count as migration 025, for one show, so it is also the way to rebuild that show’s row. Run npm run check and npm test.
What you should see: no tsc errors, and every test passes (an excerpt):
✔ a count job that runs twice counts the payment once (36.081421ms)
ℹ tests 53
ℹ suites 0
ℹ pass 53
ℹ fail 0
There are two costs. Each payment now reads every sold ticket of its show, up to 3,000 for a festival, through the index on sales.tickets (show_id). And with two workers, two jobs for one show could finish in either order, so an older count could overwrite a newer one until the next payment for that show.
TinyTickets runs one worker. If the count ever became too slow, or a second worker started, the other way from the concepts (a table of counted orders) would be the next step. Commit:
git add -A
git commit -m "Count a show's sales again in each count_sales job"
Step 4: Count scans in the same statement as the scan
Why: Door’s answer from Step 1 still joins every scan of the organizer’s shows on each load. A scan is Door’s own command, so Door can keep the count in the same statement, with no event and no job.
What to do: first pin today’s behavior. The test “the door admits a ticket once” scans one ticket of Test Show twice, and the second scan is refused. Add this test at the end of app.test.ts:
// "The door admits a ticket once" scanned one ticket of Test Show twice; the
// second scan was refused.
test("the dashboard counts the scans the door let in", async () => {
const row = (await loadDashboard(1)).find((one) => one.show_id === leoShow)!;
assert.equal(row.scanned, 1);
});
Run npm test: all 54 pass, with the count from Step 1. Commit, so the next change has a test to keep. Then save this migration as migrations/026_create_show_scans.sql:
-- Year 3: a read model of Door for the organizer dashboard: the scans of each
-- show. insertScan adds one in the same statement as the scan.
CREATE TABLE door.show_scans (
show_id integer PRIMARY KEY,
scanned integer NOT NULL CHECK (scanned >= 0)
);
-- The scans before this migration, counted once.
INSERT INTO door.show_scans (show_id, scanned)
SELECT tickets.show_id, count(*)
FROM door.scans JOIN door.tickets ON tickets.code = scans.ticket_code
GROUP BY tickets.show_id;
-- No query reads door.tickets by show any more, and an index costs every insert.
DROP INDEX door.tickets_show_id_idx;
The last line removes the index Step 1 added for Door, because the count no longer needs it. Replace src/door/db/scans.ts with this:
import { pool } from "#platform";
// One row per scan: a ticket's code, admitted once. The same statement adds
// one to the show's count in door.show_scans, so the scan and the count
// commit together. A second scan of the code adds neither.
export async function insertScan(code: string, userId: number): Promise<boolean> {
const result = await pool.query(
`WITH scan AS (
INSERT INTO door.scans (ticket_code, scanned_by) VALUES ($1, $2)
ON CONFLICT (ticket_code) DO NOTHING
RETURNING ticket_code
)
INSERT INTO door.show_scans (show_id, scanned)
SELECT tickets.show_id, 1 FROM scan JOIN door.tickets ON tickets.code = scan.ticket_code
ON CONFLICT (show_id) DO UPDATE SET scanned = show_scans.scanned + 1`,
[code, userId],
);
return result.rowCount === 1;
}
// How many people each show let in, for the organizer dashboard.
export async function scansOfShows(showIds: number[]): Promise<{ show_id: number; scanned: number }[]> {
const result = await pool.query<{ show_id: number; scanned: number }>(
"SELECT show_id, scanned FROM door.show_scans WHERE show_id = ANY($1)",
[showIds],
);
return result.rows;
}
The WITH part inserts the scan and returns its code only if the code was new. The outer INSERT adds one for each code it returns, so a refused scan returns nothing and adds nothing. It is one statement, so the scan and the count commit together. rowCount is now the count’s row, which is 1 exactly when the scan went in, so the route needs no change.
Adding one is safe here, unlike in Step 3, because the scan’s own key decides whether it runs. In app.test.ts, the TRUNCATE gets the new table (an excerpt):
`TRUNCATE door.scans, door.tickets, door.show_scans, payouts.payouts, sales.tickets, sales.orders,
sales.sales, sales.show_sales, shows.shows, shows.organizers, sessions, users, jobs, outbox
RESTART IDENTITY`,
Run npm run check and npm test.
What you should see: no tsc errors, and every test passes (an excerpt):
Applied 026_create_show_scans.sql
...
✔ the door admits a ticket once (58.177079ms)
...
✔ the dashboard counts the scans the door let in (2.288092ms)
ℹ tests 54
ℹ suites 0
ℹ pass 54
ℹ fail 0
The cost is on the door’s side. Every scan of one show now updates the same row, so two scans of one show at the same moment wait for each other for the length of one statement. Commit:
git add -A
git commit -m "Count scans for the dashboard in the same statement as the scan"
Step 5: Play the sale day again
Why: the reason for this module was a measurement, so it ends with one. sale-day.ts writes its rows with SQL, past the projections, so it must fill the two new tables itself.
What to do: in sale-day.ts, add import { countSales } from "#sales"; after the import of #platform, and make the TRUNCATE the same as the one in app.test.ts (two excerpts):
`TRUNCATE door.scans, door.tickets, door.show_scans, payouts.payouts, sales.tickets, sales.orders,
sales.sales, sales.show_sales, shows.shows, shows.organizers, sessions, users, jobs, outbox
RESTART IDENTITY`,
Then build the read models before ANALYZE (an excerpt):
// The read models, built from the rows above: Sales' projection runs once for
// each show, and Door's count is the query of migration 026.
for (let showId = 1; showId <= 240; showId++) {
await countSales({ showId });
}
await pool.query(
`INSERT INTO door.show_scans (show_id, scanned)
SELECT tickets.show_id, count(*)
FROM door.scans JOIN door.tickets ON tickets.code = scans.ticket_code
GROUP BY tickets.show_id`,
);
Calling countSales for every show is how you rebuild Sales’ read model from scratch, for example after a bug in the projection. Run it:
npm run check
node --env-file=.env.test sale-day.ts
What you should see (one run; your numbers will differ):
Quiet: one dashboard 1 requests, median 9 ms, slowest 9 ms
Quiet: one hold 1 requests, median 30 ms, slowest 30 ms
10:00, holds alone 120 requests, median 809 ms, slowest 871 ms
10:00, holds with dashboards 120 requests, median 816 ms, slowest 956 ms
10:00, the dashboards 60 requests, median 932 ms, slowest 940 ms
One dashboard now takes 9 ms. At 10:00, the holds with the dashboards open take about as long as the holds alone, and the slowest one went from 2.7 seconds to under one. So the answer to Leo is now no. His page no longer slows the buyers down.
The dashboards still take about 0.9 seconds at 10:00. They do almost no work, but they wait in the same queue behind 120 holds, and the holds now decide how long it is.
In our reading, the holds are now the write side’s limit. Each show has one version, which Module 7’s exercise measured, and saleOf reads every order of the show on each hold. Commit:
git add -A
git commit -m "Build the read models in sale-day.ts"
Step 6: Update the glossary, the map, the README and the code figure
Why: “Dashboard” is a word Leo uses, and the map still says platform/ holds a query across four schemas.
What to do: in GLOSSARY.md, add this entry at the end:
## Dashboard
The page where an organizer sees each of their shows: the tickets sold,
the sales, the seats held, the scans at the door and the payout. It only
reads. "Sold" and "Sales" change when the worker next comes round after a
payment, not at the moment of the payment.
- Context: none. It asks each context about the organizer's shows.
- Code: `loadDashboard` (`src/dashboard/dashboard.ts`), the route
`GET /organizer`. Sales answers from table `sales.show_sales`, which the
job `count_sales` writes; Door answers from table `door.show_scans`.
In “Scan”, the code line becomes this:
- Code: table `door.scans` (`ticket_code`, `scanned_by`, `scanned_at`),
`insertScan` (`src/door/db/scans.ts`), the route `POST /door/tickets`.
Each scan also adds one to its show's count in `door.show_scans`.
In “Tickets issued”, the worker now makes three jobs (an excerpt):
turns it into the jobs `send_confirmation` (Sales), `add_tickets_at_door`
(Door) and `count_sales` (Sales); see `subscribers` in `worker.ts`.
In CONTEXT-MAP.md, add this section after “Between the contexts”:
## The organizer dashboard
dashboard/ ..> {Shows} src/dashboard/ is not a context: it owns no
dashboard/ ..> {Sales} table and no rule, and only app.ts imports
dashboard/ ..> {Door} it. It asks each context about one
dashboard/ ..> {Payouts} organizer's shows through its entry
(listShowsOf, salesOfShows, scansOfShows,
payoutsOfShows), and each context answers
from its own schema.
The map’s first check command now prints the four new arrows:
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 ..> #shows
1 payouts ..> #sales
2 payouts ..> #shows
5 sales ..> #shows
In README.md, replace the two lines that begin “One query still reads all four schemas” with this paragraph:
The organizer dashboard in `src/dashboard/` belongs to no context either.
It only reads: it asks Shows, Sales, Door and Payouts about the organizer's
shows through their entries, and each one answers from its own schema.
Sales and Door answer from small tables kept for this page, `sales.show_sales`
and `door.show_scans`, so a page load counts no tickets and no scans.
Then make these edits in the same file:
- Add
`#dashboard`to the list of entries, after`#platform`. - In the comment of
npm run worker, write “the dashboard’s counts” after “emails”. - In “Check and test”, add the line
node --env-file=.env.test sale-day.ts # times a 10:00 sale on the laptop, and say under it thatsale-day.tsempties the test database too. - In “Files”, add a line for
src/dashboard/and one forsale-day.ts, remove “the organizer dashboard” from the line forsrc/platform/, and change “001 to 023” to “001 to 026”.
The code/module-10/ folder has the whole file.
Figure 5 is the code figure with this module’s changes marked.
{Door} {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
{Sales} --> {Door} the event TicketsIssued, through the outbox
dashboard/ ..> {Shows}, {Sales}, {Door}, {Payouts} one question to each NEW
{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 NEW
jobs/ count-sales.ts, the projection NEW
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 NEW
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.
The dashboard has moved out NEW. Every context and
dashboard/ ..> platform/.
worker.ts subscribers: TicketsIssued --> send_confirmation,
add_tickets_at_door, count_sales NEW
Legend so far
{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 5: no code in src/ reads another context’s schema any more; the dashboard asks each context through its entry.
Run the checks:
npm run check
npm test
npm run test:fast
What you should see: no tsc errors, 54 tests pass in npm test, and 29 in npm run test:fast. The end of the fast run, from one run:
✔ domain/ and application/ import nothing from the outside world (6.630991ms)
ℹ tests 29
ℹ suites 0
ℹ pass 29
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 291.765744
Commit:
git add -A
git commit -m "Describe the dashboard and its read models in the glossary, the map and the README"
How a payment reaches Leo’s dashboard
Follow Ana’s payment for two tickets, and then Leo’s next reload (Figure 6):
- The payment provider’s webhook reaches
markOrderPaid, as in Module 9. In one transaction, theSalepays the order and recordsTicketsIssued, and the repository writes the event tooutbox. - On its next pass, the worker’s relay turns the event into three jobs:
send_confirmation,add_tickets_at_doorandcount_sales. countSales({ showId })counts the show’s sold tickets again fromsales.ticketsandsales.orders, through the index onshow_id, and overwrites the show’s row insales.show_sales. If the job runs again, it writes the same numbers.- Leo reloads
/organizer.requireLoginfinds his session, anddashboardRoutescallsloadDashboardwith his organizer ID. listShowsOfreads his shows fromshows.shows.salesOfShowsreads one row per show fromsales.show_sales, and the seats held right now from the held orders, through the partial index.scansOfShowsreads one row per show fromdoor.show_scans, which each scan updated in its own statement.payoutsOfShowsreadspayouts.payouts.loadDashboardputs the four answers side by side, anddashboardPageprints them. Nothing in steps 4 to 8 counts a ticket or changes a row.
(Ana) --> [Payment provider] --> [Web app] markOrderPaid
BEGIN ... sale.pay, sale.issueTickets ... [[outbox]] ... COMMIT
[Worker] relayEvents: [[outbox]] --> [[jobs]] x 3
[Worker] count_sales --> [[sales.tickets]], [[sales.orders]] count again
--> [[sales.show_sales]] one row NEW
(Leo) --> [Web app] GET /organizer --> dashboard/ loadDashboard NEW
listShowsOf --> [[shows.shows]]
salesOfShows --> [[sales.show_sales]] NEW, held orders
scansOfShows --> [[door.show_scans]] NEW
payoutsOfShows --> [[payouts.payouts]]
<-- the page
Figure 6: the payment changes the write side once; the worker updates the read model later; Leo’s reload only reads.
Between steps 1 and 3, Leo’s page shows the old count, and Ana’s seats appear neither as held nor as sold. That window is one worker pass, the same as for the door in Module 9.
Going deeper
Three levels of CQRS, and where the authors disagree
The authors do not agree on how far to take the split. It helps to see three levels, and Figure 7 says who describes each one.
| Level | What is separate | TinyTickets | Who describes it |
|---|---|---|---|
| 1. Separate code | commands go through the aggregate; queries read the tables | Module 8, and Step 1 here | Young, 2010, p. 21 (the thin read layer) |
| 2. Separate tables, same database | read models, kept by projections | Steps 2 to 4 | Microsoft’s “single data store” level (2025); Fowler (2011) |
| 3. Separate databases | a read store kept in sync by messages | not in this course | Dahan (2009) expects this in practice; Microsoft’s “more advanced” level |
Figure 7: three levels of CQRS; each one costs more than the one before.
Young (p. 23) says that at level 1 the cost is at worst the same, because a responsibility only moved. He suggests separate data models only after that, synced either at once or later, preferably with events. Microsoft’s CQRS page calls separate models in one data store the foundational level. With separate stores, it recommends the transactional outbox and idempotent consumers of Module 9, and it adds that messaging is not a requirement for CQRS.
Martin Fowler’s “CQRS” (2011) is the most cautious. He writes that “for most systems CQRS adds risky complexity”, and he allows the two models to share a database. He advises using CQRS only in parts of a system, such as one bounded context.
Fowler also notes that a reporting database may be enough when the only problem is demanding queries. TinyTickets’ problem was a demanding query, and its answer, two small tables in the same database, is close to his.
Dahan asks whether the query side must be a separate database, and answers that it need not be, but in practice it usually ends up separate. In a comment under the same post, he suggests plain CRUD for data that one user edits alone.
The disagreement on cost goes away once you separate the levels. Splitting the code is cheap, as Young says. A second store and the syncing between the stores are the expensive parts, which is what Fowler and Microsoft warn about.
Event sourcing: keeping the events instead of the state
TinyTickets stores the current state. An order’s row says “paid”, and the history of how it got there is gone. Event sourcing stores the history instead. Fowler’s “Event Sourcing” (2005) describes it in one line:
“Capture all changes to an application state as a sequence of events.” (Fowler, “Event Sourcing”)
The current state is what you get by replaying the events in order (Figure 8).
State, as TinyTickets stores it Events, as event sourcing stores them
[[sales.orders]] [[events]], stream sale-7
a held 2 seats v1 SeatsHeld order a, 2 seats
b paid 1 seat v2 SeatsHeld order b, 1 seat
[[sales.sales]] show 7, version 3 v3 OrderPaid order b
the state: v1 to v3, replayed in order
Figure 8: the same sale stored as rows that are overwritten, and as events that are only appended.
An event store is the table, or the database, that keeps every stream of events. Young’s design (CQRS Documents, pp. 41 to 43) needs two tables in a relational database: the events with their aggregate and version, and each aggregate’s current version. To save, you compare the version you read with the one stored, and you fail if they differ.
That is Module 7’s version column, on a table you only append to. In the sketch below, a primary key does the same check. You can paste it into psql; it is not part of TinyTickets:
CREATE TABLE try_events (
stream_id text NOT NULL,
version integer NOT NULL,
type text NOT NULL,
data jsonb NOT NULL,
PRIMARY KEY (stream_id, version)
);
INSERT INTO try_events VALUES ('sale-7', 1, 'SeatsHeld', '{"order": "a", "seats": 2}');
INSERT INTO try_events VALUES ('sale-7', 2, 'SeatsHeld', '{"order": "b", "seats": 1}');
-- A second command read the sale at version 1 too, and appends its own version 2.
INSERT INTO try_events VALUES ('sale-7', 2, 'SeatsHeld', '{"order": "c", "seats": 1}');
-- The current state is a fold over the stream.
SELECT sum((data->>'seats')::integer) AS seats_held FROM try_events WHERE stream_id = 'sale-7';
DROP TABLE try_events;
What you should see (an excerpt):
INSERT 0 1
INSERT 0 1
ERROR: duplicate key value violates unique constraint "try_events_pkey"
DETAIL: Key (stream_id, version)=(sale-7, 2) already exists.
seats_held
------------
3
(1 row)
The second command lost the race, as in Module 7, and it would load the stream again and retry. Microsoft’s Event Sourcing page uses the same example, two handlers that each see five seats left, and the store rejects the second write with the same optimistic check.
Loading an aggregate means reading its whole stream, which Microsoft calls rehydration. For long streams, Young (pp. 33 and 44 to 45) adds snapshots. A snapshot is the state saved at one version, so a load reads the snapshot and only the events after it. Young and Microsoft both treat snapshots as an optimization, and the events stay the truth.
What you get in return is in Fowler’s 2005 article. You can throw the state away and rebuild it, ask what the state was at a past date, and correct a wrong past event by reversing it. Young (p. 31) adds that nothing is ever deleted, and a mistake is fixed with a new event that reverses it.
The list of costs is long, and Microsoft’s 2026 page names most of them:
- Changing an event’s shape. Stored events never change, so code must read every old shape forever. Microsoft lists four ways to cope: ignore unknown fields, put a version in each event, upcasting, and rewriting the store, which it calls a last resort. Upcasting is a function that turns an old shape into the current one when it is read, while the stored event stays as it was. A bug that wrote wrong events leaves them in the store, and fixing the code does not fix them.
- No SQL over the current state. The state exists only after a replay, so every list and search needs a projection. Young (p. 50) makes the same point, that event sourcing works because CQRS takes the queries away from the domain.
- Deleting personal data. Events are never deleted, so a buyer’s email in an event stays. Microsoft suggests keeping personal data outside the events, or encrypting it with a key per person and deleting the key.
- Replays reach the outside world. Fowler warns that an outside system cannot tell a replay from the real thing. So calls out, such as emails, must be switched off during a replay.
- Experience. Microsoft lists a team with no event-driven experience as a reason not to use it. Its page opens with a warning that the pattern is complex and costly to adopt or to leave, and adds:
“For most systems and most parts of a system, traditional data management is sufficient.” (Microsoft, “Event Sourcing pattern”, 2026)
Young disagrees. His CQRS Documents (p. 52) conclude that CQRS with event sourcing is less expensive in most cases, because the write side needs no object-relational mapping. In our reading, he compares it with an ORM-heavy design and a team that already thinks in events. TinyTickets has hand-written SQL and no ORM, so his saving is smaller here.
Fowler’s “What do you mean by ‘Event-Driven’?” (2017) separates four patterns that share the word “event”, and says “the core problem is confusing the different patterns”. In his terms, TinyTickets’ outbox is event notification, where events tell other contexts that something happened. The tables are still the truth, and the relay deletes each event once it has become jobs. That is not event sourcing.
When Omar asked whether TinyTickets should keep its events, Maya read these pages that week. She decided “not yet”, and she wrote down the three signs that would change her answer. In our judgment, these are the signs for TinyTickets:
- someone outside the team, an auditor or a court, needs to know who held a ticket and when, which becomes a real question once tickets can move between buyers
- organizers dispute payouts, and the team must show a balance on a past date (Microsoft names a payment ledger as one place for event sourcing)
- a new page needs history that the tables no longer keep, and no projection was writing it down
Until then, a table that a context only appends to, such as a history of changes to a ticket, gives most of the audit value without making events the truth.
What changed recently
Microsoft rewrote both pattern pages: CQRS on 2025-02-20, and Event Sourcing on 2026-03-27. The Event Sourcing page now opens with the warning against using it by default, and it adds upcasting and the key-per-person deletion. It also warns not to confuse an event store with a message broker such as Kafka, which has no stream per aggregate and no optimistic check.
EventStoreDB, a database built for event sourcing, is now called KurrentDB. The company renamed itself Kurrent in November 2024 (Kurrent blog), and the database took the name with version 25.0 in March 2025, its “first release of KurrentDB” (release page). For Node.js and TypeScript, Emmett is an event sourcing library that can store events in PostgreSQL; its README says it has no license yet. We have not used either.
PostgreSQL 18 still recomputes a materialized view in full on every refresh. The pg_ivm extension adds incremental refresh for PostgreSQL 13 to 19. It supports only some aggregates and joins, and no aggregates over outer joins, so it could not keep the view in this module, which uses LEFT JOIN and count().
When a read model is too much
A plain query is enough when it is fast under the load you really have. Most of TinyTickets reads that way and should stay so. The show page, the order page and the ticket email read rows directly, and none of them needs a table of its own. Measure first, as sale-day.ts did, and try an index before a read model.
A read model costs a table, a projection, a first fill in a migration, a way to rebuild it, and a test for a job that runs twice. A read model fed by events is behind by one worker pass, so the page can disagree with itself, as the exercise below shows. Copying a rule into a query, as “Held” does, costs a test that ties the copy to the domain.
CQRS as a whole-system style is too much for most of an app like this one, as Fowler warns. Here it is two tables for one page. These limits are our judgment.
Check yourself
- Why does the dashboard read tables instead of loading
Saleaggregates, and what does CQRS separate in TinyTickets when there is only one database?
Answer
A query changes nothing, so it needs no aggregate to protect a rule, and saleOf would read every order of each show to build one row. CQRS separates the commands, which go through the Sale and its repository, from the queries, which read tables and read models. Both use the same PostgreSQL.
- In Step 1, one dashboard alone got twice as fast, but the 10:00 numbers did not improve. Why not, and what changed that?
Answer
Each load still counted every ticket and scan of the organizer’s shows, and it now asked the pool for a client four times, in a queue shared with 120 holds. Steps 2 and 4 made a load read one row per show from sales.show_sales and door.show_scans. One load then took 9 ms, and the holds were as fast as with no dashboards open.
- Why did the first
countSalescount four tickets instead of two, and why is the second version safe to run twice? What does it cost?
Answer
The job ran twice, and each run added the order’s two tickets to the row. The second version counts the show’s sold tickets again from the tables and overwrites the row, so a second run writes the same numbers. It reads every sold ticket of the show on each payment, and with two workers an older count could overwrite a newer one.
- What did
REFRESH MATERIALIZED VIEW CONCURRENTLYneed before it worked, what does a plainREFRESHdo to a dashboard load, and why did TinyTickets use neither?
Answer
A unique index on plain columns covering every row, here on show_id. A plain refresh takes an ACCESS EXCLUSIVE lock, so a SELECT waits for the whole refresh; the test with lock_timeout = '1s' failed. The view would read four contexts’ schemas, recount 400,000 tickets on every refresh, and show “Held” as of the last refresh.
- What would event sourcing change in how TinyTickets stores a sale, name two of its costs, and name one sign that it would be time for it.
Answer
The sale would be a stream of events that is only appended to, with a version check on each append, and its state would be a replay of the stream. Two costs are reading every old event shape forever (upcasting) and having no SQL over the current state without projections. A sign is an auditor who needs to know who held a ticket and when, or a payout dispute about a past date.
Exercise: a “Left” column that lags
Leo asks for one more column, the seats he can still sell. Add a seats_left field to DashboardRow, computed in loadDashboard from the numbers it already has, and a “Left” column to the page. Then write a test in app.test.ts that reads it three times: while two seats are held, right after the payment, and after the worker’s next pass.
Predict the three numbers first. Undo the change at the end.
Solution
In src/dashboard/dashboard.ts, add seats_left: number; to DashboardRow after seats_held, and this line to the object loadDashboard returns, after the line with seats_held:
seats_left: show.seats - sold.tickets_sold - sold.seats_held,
In src/dashboard/page.ts, add <th>Left</th> after <th>Held</th>, and <td>${row.seats_left}</td> after the cell with row.seats_held. Then add this test at the end of app.test.ts:
test("seats left on the dashboard catch up when the worker has run", 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, 'Left 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: "2" });
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];
const left = async () => (await loadDashboard(1)).find((row) => row.show_id === showId)!.seats_left;
const whileHeld = await left();
await webhook({
id: "evt_14",
type: "payment.succeeded",
data: { payment_id, amount_cents: 2550, currency: "usd", metadata: { order_ref: token } },
});
const beforeWorker = await left();
await runWorker();
console.log("seats left", [whileHeld, beforeWorker, await left()]);
});
One run printed this (an excerpt):
seats left [ 8, 10, 8 ]
✔ seats left on the dashboard catch up when the worker has run (54.259561ms)
Between the payment and the worker’s pass, the page said 10. The order was no longer held, because it was paid, and not yet sold, because count_sales had not run. “Held” is read live and “Sold” is one pass behind, so a sum of the two can be wrong for a moment.
No seat is at risk, because the Hold button asks the Sale, which counts the paid order at once. Only the page is behind. If Leo must never see it, Sales could answer “Left” in the same query from sales.orders, at the cost of reading every order of the show on each load. Undo the exercise:
git checkout app.test.ts src/dashboard/
Cheat sheet
Cheat sheet
- Command and query: a command changes state through the aggregate; a query answers and changes nothing.
- CQRS: separate the two in code first; a separate table comes second; a second database is a later, larger step.
- Read model: a table shaped for one page, with no rules; here
sales.show_salesanddoor.show_scans.- Projection: the code that keeps a read model current, in the same statement (Door) or from an event (Sales).
- Safe to repeat: count again and overwrite, or record what you counted; never only add.
- First fill and rebuild: a migration fills the read model; running the projection for every show rebuilds it.
- Materialized view: one statement, but it recounts everything;
CONCURRENTLYneeds a unique index.- Event sourcing: events are the truth and state is a replay; costs include versions, upcasting and deleting data.
- Measure: run
sale-day.tsbefore and after; try an index before a read model.
Figure 9 is the whole module in one picture.
Command (Ana) --> markOrderPaid --> Sale --> [[sales.*]] + [[outbox]] once
Project [Worker] count_sales --> [[sales.show_sales]] count again
insertScan --> [[door.scans]] + [[door.show_scans]] one statement
Query (Leo) --> loadDashboard --> one question to each context reads only
Studied event sourcing: [[events]] appended, state replayed not yet
Figure 9: commands change the tables once, projections keep the read models, and the page only reads.
The dashboard now asks each context about its own shows, Sales and Door answer from tables kept for that page, and a reload no longer slows the buyers’ holds. Next, Module 11 runs the whole method on one new feature, when Leo asks for ticket transfers between buyers.
Sources
- Bertrand Meyer, “Principles of Library Design: The Eiffel Experience”, lecture 1, ADFOCS summer school, 2003, slides 25 and 26.
- Greg Young, CQRS Documents, 2010: pp. 17, 21, 23, 31, 33, 41 to 45, 50, 52.
- Udi Dahan, “Clarified CQRS”, 2009, with its comments.
- Martin Fowler, “CQRS”, 2011; “Event Sourcing”, 2005; “What do you mean by ‘Event-Driven’?”, 2017.
- Microsoft, Azure Architecture Center: “CQRS pattern”, 2025; “Event Sourcing pattern”, 2026.
- PostgreSQL 18 docs: materialized views,
REFRESH MATERIALIZED VIEW, explicit locking; thepg_ivmextension. - Kurrent: the rebrand, 2024, and KurrentDB 25.0, 2025. Emmett on GitHub.
pg-pool3.14.0, the pool behindpg.Pool: itsindex.jssetsmaxto 10 when you give none.