Door staff at Leo’s club asked that a ticket work only on the day of its show. On Tuesday, Nina added a valid_on date to the tickets table and pushed the change.
On Wednesday, Omar ran the tests before Friday’s sale. The test that pays for an order and emails the tickets failed.
“I only changed the door,” Nina said.
“Is a ticket at the door the same thing as a ticket I sell?” Leo asked.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
It is not the same thing. In Sales, a ticket is a seat sold with a price. At the door, it is a code that lets one person in. In Payouts, it is a price that counts toward the organizer’s money.
All three meanings share one table and one file, so a change for one breaks the others. This module gives each meaning a bounded context of its own: one folder and one PostgreSQL schema each, still inside one app, with a test that keeps the folders apart.
After this module, you can:
- find a word that means different things in different parts of the code, and name the bounded context each meaning belongs to
- move code into one folder per context, and give each folder one public entry with
package.json"imports" - make the tests fail when one context reaches into another’s files, and say what Node.js and
tscrefuse on their own - move each context’s tables into its own PostgreSQL schema with a migration, and find the queries that still cross
- say what a modular monolith costs, and when one folder per context is too much
Where the code stands
Module 2 left a board with four candidate boundaries: Shows, Sales, Door and Payouts. The code is still sorted by technical layer, and every table is in PostgreSQL’s default schema, public. Figure 1 is the same picture as in Module 2.
(Buyers) --+
(Organizers) --+--> [Web app] routes/ --> services/ --> db/ --> [[PostgreSQL]]
(Door staff) --+ pages/
[Worker] jobs/ --> services/, db/ -------^
Figure 1: the code is sorted by layer, so nothing in it says where Sales ends and the Door begins.
One table, three meanings of “ticket”
Start from the code Module 2 left, and add Nina’s change. Save this as migrations/014_add_valid_on_to_tickets.sql:
-- Year 3: at the door, a ticket works only on the day of its show.
ALTER TABLE tickets ADD COLUMN valid_on date;
UPDATE tickets SET valid_on = shows.show_date FROM shows WHERE shows.id = tickets.show_id;
ALTER TABLE tickets ALTER COLUMN valid_on SET NOT NULL;
It follows the same pattern as migration 008: add the column, fill it for the rows that exist, then require it. Nina also changed the door’s query to read the new column, but the failure needs only the migration.
Pause and predict:
npm testmigrates the test database and runs the 14 tests. Which tests fail, and why would a column for the door break any of them?
npm test
What you should see (an excerpt; paths are shortened and some stack lines are cut, and your timings will differ):
Applied 014_add_valid_on_to_tickets.sql
The database is up to date.
✔ the show page has a form to hold seats (146.227385ms)
✔ a hold leads to the payment page (24.931496ms)
✔ a hold for more seats than are left is refused (4.861406ms)
✔ a webhook without the secret is refused (3.811905ms)
✖ a paid webhook issues the tickets, and the worker emails them (23.688022ms)
error: null value in column "valid_on" of relation "tickets" violates not-null constraint
at async insertTicket (file:///.../tinytickets/db/tickets.ts:9:3)
at async markOrderPaid (file:///.../tinytickets/services/orders.ts:27:9)
at async file:///.../tinytickets/routes/webhooks.ts:15:5 {
✖ the door admits a ticket once (49.24453ms)
✖ the dashboard shows the organizer's own shows only (44.565464ms)
✔ the dashboard needs a login (2.385544ms)
...
ℹ tests 14
ℹ pass 11
ℹ fail 3
Under “failing tests”, the three reasons are 500 !== 200 for the webhook, Cannot read properties of undefined (reading 'code') for the door, and a dashboard that says 0 of 5 where the test expects 3 of 5.
Nina’s migration filled valid_on for the tickets that existed. But the next ticket comes from insertTicket, which markOrderPaid calls when a payment arrives, and that INSERT names no valid_on. PostgreSQL refuses the row, the transaction rolls back, and the webhook answers 500.
So no tickets exist, and the door test and the dashboard test fail after it. Nina never opened services/orders.ts, because it has nothing to do with the door.
Figure 2 lists everything that uses the tickets table, and what “ticket” means in each place.
| File | Uses the table to | Columns | “Ticket” means |
|---|---|---|---|
services/orders.ts, through insertTicket |
write one row per seat sold | show_id, order_id, buyer_name, code, kind, price_cents |
a seat sold, with a price |
jobs/send-confirmation.ts |
list the codes in the email | code, kind |
a seat sold, with a price |
routes/door.ts |
find a code, then record a scan in door_tickets |
code, kind |
a code that lets one person in |
db/payouts.ts |
add up what the organizer earned | price_cents |
a price that counts toward a payout |
db/dashboard.ts |
show Leo his numbers | most of them | all of the above |
Figure 2: one table serves three meanings, so a column for one of them is a column all of them must write.
And “ticket” means more than these. In services/pricing.ts, the type Ticket is one line of an order ({ kind, quantity }), stored in the column orders.tickets. At the door, a scan is stored in a table named door_tickets. Module 1 left this as the glossary’s first open question.
Before you go on, undo Nina’s change. Delete the migration and give the tests a fresh database, because the column is already in it:
rm migrations/014_add_valid_on_to_tickets.sql
docker exec tinytickets-db dropdb -U postgres tinytickets_test
docker exec tinytickets-db createdb -U postgres tinytickets_test
A boundary for each meaning
A bounded context is where one meaning holds
A bounded context is a part of a system inside which one model, and the words of its language, have exactly one meaning. Outside it, the same word may mean something else. Evans’ Domain-Driven Design Reference (2015, p. 2) puts the reason in one line:
“Model expressions, like any other phrase, only have meaning in context.” (Evans, Domain-Driven Design Reference, p. 2)
The same page says why one model for everything fails. On a large project, different groups of users and different teams build different models. When code from different models is mixed, the software gets buggy and hard to understand. TinyTickets has three developers, not several teams, but the board in Module 2 found the same split in its users: buyers, door staff and organizers.
It works because each context can change its model without asking the others. Sales can add a column to its tickets, and Door never sees it.
The cost is translation. When Door needs a ticket, it asks Sales and gets an answer in a shape both agree on, and that shape is code someone writes and keeps. You get more folders, some data in two places, and a rule that wears away unless something checks it.
A bounded context is not a React context and not a microservice. In this course, each context is a folder of TypeScript and a schema in the one PostgreSQL database, inside one deployable app. In TypeScript, the boundary is the one file that other folders may import.
Four contexts from the board
The four candidates from Module 2 become four contexts, with the same names as the four subdomains from Module 1:
- Shows keeps shows and organizers. It has no tickets at all.
- Sales keeps holds, orders, payments, tickets and the ticket email. Here a ticket is a seat sold with a code, a kind and a price, which is Leo’s meaning. One line of an order becomes an order line.
- Door keeps scans. A ticket is a code to admit once, and Door asks Sales for it.
- Payouts keeps payouts and the fee. A ticket is a price, and Payouts asks Sales for the prices.
Some code belongs to no context: the database pool, the job queue, settings, page layout, login, email and the payment provider’s client. It goes into a fifth folder, src/platform/. Most of it is the generic subdomains from Module 1 (payments, email, login).
The organizer dashboard goes into src/platform/ too, because its one query reads all four contexts. It stays the one exception until Module 10.
Evans’ Reference (p. 38) has a name for code like the starter project: a big ball of mud, a part of a system with no real boundaries, where models mix. His advice is to draw a boundary around the whole mess and not try careful modeling inside it. This module is the first cut through that ball. The cost is that platform/ can turn into a second ball, so it must never hold a business rule.
A modular monolith keeps one deploy
A modular monolith is one deployable app whose code is split into modules with boundaries that something enforces. Shopify described its move to one in 2019 (Westeinde, “Deconstructing the Monolith”). It reorganized a large Rails app by business concept instead of technical layer, with strict boundaries and no new deployment units.
TinyTickets keeps one web app, one worker and one database on one server, as the story requires. Splitting the contexts into services would add network calls between them and more parts to deploy. System Design Module 5 covers when that is worth it. Shopify also reported the costs of the move: one big reorganization touched almost every file, Git history got harder to follow on GitHub, and keeping the parts isolated never finished.
Conway’s law is the observation that an organization designs systems whose structure copies the way its people communicate (Conway, 1968). With three developers in one team, the team does not decide these boundaries, so the language does.
One public entry per context
Node.js runs TinyTickets with type stripping, and the Node.js docs on TypeScript say that Node ignores tsconfig.json. So tsconfig paths cannot give a folder a short name. The same page names the closest feature, subpath imports.
A subpath import is an entry in the "imports" field of package.json whose name starts with # and maps to a file (Node.js docs, Modules: Packages). It applies only to code inside the package. TinyTickets gets one entry per context, and that file is the context’s public entry, the one file other folders may import from it.
"imports": {
"#sales": "./src/sales/index.ts"
}
It works because only the names in the list resolve. #sales maps to src/sales/index.ts, and #sales/db/tickets.ts is in no list, so Node refuses it. tsc refuses it too, because TypeScript with module: nodenext reads "imports" the same way Node does (TypeScript handbook, Modules reference). The project already has allowImportingTsExtensions, so the entry can point at a .ts file.
The cost is one index.ts per context that someone must keep, and every new export in it is a decision about what other contexts may use. And it has a hole that Step 4 shows.
One schema per context
In PostgreSQL, a schema is a namespace inside one database that holds tables, written before the table name: sales.tickets (PostgreSQL 18, Schemas). A table name without a schema is looked up through the search_path setting, which by default finds public. Evans’ Reference (p. 2) lists database schemas, beside code bases, among the physical signs of a context’s boundary.
ALTER TABLE ... SET SCHEMA moves a table with its indexes, constraints and owned sequences, and copies no rows (PostgreSQL 18, ALTER TABLE). Every query then names the schema, so grep can tell which context a query reads.
The cost is that a schema, by itself, stops nothing. TinyTickets connects with one database role that owns every schema, so Door’s SQL can still read Sales’ tables. Step 7 finds those queries with grep.
Draw the boundaries, step by step
Each step says why, what to do, the code, and what you should see. Work in the project folder Module 2 left, with PG... settings that point at your PostgreSQL. The finished code is in the code/module-03/ folder of the course repository.
Step 1: Split the files that serve two contexts
Why: every file will move into exactly one context’s folder, so a file that serves two contexts must split first. Two files do: db/tickets.ts (Sales’ queries and the door’s scan) and pages/organizer.ts (login, the dashboard and the door page).
What to do: move insertDoorTicket out of db/tickets.ts into a new file, db/scans.ts, unchanged:
import { pool } from "./pool.ts";
// A door ticket is the stub the door staff tear off: one row per scan.
export async function insertDoorTicket(code: string, userId: number): Promise<boolean> {
const result = await pool.query(
`INSERT INTO door_tickets (ticket_code, scanned_by) VALUES ($1, $2)
ON CONFLICT (ticket_code) DO NOTHING`,
[code, userId],
);
return result.rowCount === 1;
}
Move doorPage out of pages/organizer.ts into a new file, pages/door.ts:
import { layout, notice } from "./layout.ts";
export function doorPage(message: string): string {
return layout(
"Door",
`<h1>Door</h1>
${notice(message)}
<form method="post" action="/door/tickets">
<label>Ticket code <input name="code" autofocus required></label>
<button>Scan</button>
</form>`,
);
}
In routes/door.ts, the first imports become:
import express from "express";
import { insertDoorTicket } from "../db/scans.ts";
import { findTicketByCode } from "../db/tickets.ts";
import type { User } from "../db/users.ts";
import { doorPage } from "../pages/door.ts";
findTicketByCode stays in db/tickets.ts. It reads the tickets table, so it moves with Sales, and Door will ask Sales for it.
What you should see: npm run check prints no errors, and npm test passes all 14 tests. Commit:
git add -A
git commit -m "Split the door code out of the shared files"
Step 2: Move every file into one folder per context
Why: a folder per context makes the boundary visible in every path. Moving files in a commit with no other edits keeps Git’s rename detection working, as in Module 1.
What to do: Figure 3 maps every file to its context. The files keep their layer folders inside the context, so an import between two files of the same context still works after the move.
| Context | Files |
|---|---|
src/shows/ |
db/shows.ts |
src/sales/ |
routes/holds.ts, routes/shows.ts, routes/webhooks.ts, services/holds.ts, services/orders.ts, services/pricing.ts, services/pricing.test.ts, db/orders.ts, db/tickets.ts, jobs/expire-holds.ts, jobs/send-confirmation.ts, pages/shows.ts |
src/door/ |
routes/door.ts, db/scans.ts, pages/door.ts |
src/payouts/ |
services/payouts.ts, services/payouts.test.ts, db/payouts.ts, jobs/pay-organizers.ts |
src/platform/ |
config.ts, passwords.ts, db/pool.ts, db/jobs.ts, db/users.ts, db/dashboard.ts, routes/requests.ts, routes/organizer.ts, pages/layout.ts, pages/organizer.ts, services/email.ts, services/payments.ts |
| the project folder | app.ts, server.ts, worker.ts, migrate.ts, seed.ts, fakes.ts, app.test.ts |
Figure 3: every file has one home, and the files that start the app stay outside src/.
The buyer’s pages (routes/shows.ts and pages/shows.ts) go to Sales, not Shows, because they sell seats. On the board, buyers act only in the Sales stretch. Run these moves in Bash:
move() { mkdir -p "src/$1/$(dirname "$2")" && git mv "$2" "src/$1/$2"; }
move shows db/shows.ts
move sales routes/holds.ts
move sales routes/shows.ts
move sales routes/webhooks.ts
move sales services/holds.ts
move sales services/orders.ts
move sales services/pricing.ts
move sales services/pricing.test.ts
move sales db/orders.ts
move sales db/tickets.ts
move sales jobs/expire-holds.ts
move sales jobs/send-confirmation.ts
move sales pages/shows.ts
move door routes/door.ts
move door db/scans.ts
move door pages/door.ts
move payouts services/payouts.ts
move payouts services/payouts.test.ts
move payouts db/payouts.ts
move payouts jobs/pay-organizers.ts
move platform config.ts
move platform passwords.ts
move platform db/pool.ts
move platform db/jobs.ts
move platform db/users.ts
move platform db/dashboard.ts
move platform routes/requests.ts
move platform routes/organizer.ts
move platform pages/layout.ts
move platform pages/organizer.ts
move platform services/email.ts
move platform services/payments.ts
rmdir db jobs pages routes services
npm run check
What you should see: tsc lists every import that now crosses from one folder to another. This is the start of its output; the whole list has 47 TS2307 errors and two TS7006 errors that follow from them:
app.test.ts(6,24): error TS2307: Cannot find module './config.ts' or its corresponding type declarations.
app.test.ts(7,22): error TS2307: Cannot find module './db/pool.ts' or its corresponding type declarations.
app.test.ts(9,29): error TS2307: Cannot find module './jobs/expire-holds.ts' or its corresponding type declarations.
app.test.ts(10,30): error TS2307: Cannot find module './passwords.ts' or its corresponding type declarations.
app.test.ts(108,38): error TS7006: Parameter 'row' implicitly has an 'any' type.
...
src/door/routes/door.ts(3,34): error TS2307: Cannot find module '../db/tickets.ts' or its corresponding type declarations.
...
src/sales/services/orders.ts(5,26): error TS2307: Cannot find module '../db/shows.ts' or its corresponding type declarations.
...
src/shows/db/shows.ts(1,22): error TS2307: Cannot find module './pool.ts' or its corresponding type declarations.
Read the list as a map of dependencies. Every line is one place where a file needs code from another context or from platform/. No import inside a context broke, because the layer folders moved with the files.
Step 3: Give each context one public entry
Why: every import that tsc listed must now go through a context’s public entry, so each context decides what others may use.
What to do: add an "imports" field to package.json, after "type":
"imports": {
"#shows": "./src/shows/index.ts",
"#sales": "./src/sales/index.ts",
"#door": "./src/door/index.ts",
"#payouts": "./src/payouts/index.ts",
"#platform": "./src/platform/index.ts"
},
Create the five entries. src/shows/index.ts:
// The public entry of Shows. Code outside src/shows/ imports it as "#shows".
export { findShow, listUpcomingShows } from "./db/shows.ts";
export type { Show } from "./db/shows.ts";
src/sales/index.ts:
// The public entry of Sales. Code outside src/sales/ imports it as "#sales".
export { findTicketByCode } from "./db/tickets.ts";
export { expireHolds } from "./jobs/expire-holds.ts";
export { sendConfirmation } from "./jobs/send-confirmation.ts";
export { holdRoutes } from "./routes/holds.ts";
export { showRoutes } from "./routes/shows.ts";
export { webhookRoutes } from "./routes/webhooks.ts";
src/door/index.ts:
// The public entry of Door. Code outside src/door/ imports it as "#door".
export { doorRoutes } from "./routes/door.ts";
src/payouts/index.ts:
// The public entry of Payouts. Code outside src/payouts/ imports it as "#payouts".
export { payOrganizers } from "./jobs/pay-organizers.ts";
src/platform/index.ts:
// Code that belongs to no context. Code outside src/platform/ imports it as "#platform".
export { config } from "./config.ts";
export { claimJob, enqueue, failJob, finishJob } from "./db/jobs.ts";
export { pool } from "./db/pool.ts";
export type { User } from "./db/users.ts";
export { escapeHtml, layout, messagePage, notice } from "./pages/layout.ts";
export { hashPassword } from "./passwords.ts";
export { organizerRoutes, requireLogin } from "./routes/organizer.ts";
export { formText } from "./routes/requests.ts";
export { sendEmail } from "./services/email.ts";
export { createPayment, sendTransfer } from "./services/payments.ts";
export type { PaymentEvent } from "./services/payments.ts";
The export type lines are needed because verbatimModuleSyntax is on. Without type, tsc reports TS1205 for each re-exported type.
Now fix each line that tsc listed. Change only the path in quotes, following Figure 4. Where a file then has two imports from the same entry, merge them into one line.
The path tsc cannot find |
New path |
|---|---|
./pool.ts, ./db/pool.ts, ../db/pool.ts, ./db/jobs.ts, ../db/jobs.ts, ../db/users.ts, ./config.ts, ../config.ts, ./passwords.ts, ./organizer.ts, ./routes/organizer.ts, ./requests.ts, ./layout.ts, ./pages/layout.ts, ../pages/layout.ts, ./payments.ts, ../services/payments.ts, ../services/email.ts |
#platform |
../db/shows.ts |
#shows |
../db/tickets.ts, ./routes/holds.ts, ./routes/shows.ts, ./routes/webhooks.ts, ./jobs/expire-holds.ts, ./jobs/send-confirmation.ts |
#sales |
./routes/door.ts |
#door |
./jobs/pay-organizers.ts |
#payouts |
Figure 4: each broken path points at a file that now lives in one context, so it becomes that context’s entry.
For example, the imports of app.ts become:
import express from "express";
import { messagePage, organizerRoutes } from "#platform";
import { doorRoutes } from "#door";
import { holdRoutes, showRoutes, webhookRoutes } from "#sales";
And the imports of worker.ts:
import { claimJob, enqueue, failJob, finishJob, pool } from "#platform";
import { expireHolds, sendConfirmation } from "#sales";
import { payOrganizers } from "#payouts";
What you should see: npm run check prints no errors, and npm test passes all 14 tests. Figure 5 is the first picture of the code inside the web app, drawn from the # imports. A ..> B means that code in A imports code from B.
{Door} NEW ..........> {Sales} NEW <.......... {Payouts} NEW
: : :
: v :
:.................> {Shows} NEW <...............:
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client, the organizer dashboard.
Every context ..> platform/. app.ts and worker.ts ..> each #.
Legend, added in this module
{Name} a bounded context
A ..> B A depends on B in code (an import)
Figure 5: after Step 7, Door and Payouts depend on Sales and Shows, Sales depends on Shows, and Shows depends on no context.
The figure already shows the arrows from Step 7. After Step 3, two are missing: Door does not import Shows yet, and Payouts imports no context, because their queries still read the other contexts’ tables directly. Commit the move:
git add -A
git commit -m "Move the code into one folder per context"
Git records each file as a rename. The 16 files whose only change was the move are 100% similar.
Step 4: Reach into Sales, two ways
Why: the entries only help if reaching past them fails. Try it before you trust it.
What to do: in src/door/routes/door.ts, change the import of findTicketByCode to point inside Sales:
import { findTicketByCode } from "#sales/db/tickets.ts";
Run npm run check and npm test.
What you should see: tsc refuses it:
src/door/routes/door.ts(3,34): error TS2307: Cannot find module '#sales/db/tickets.ts' or its corresponding type declarations.
And Node refuses to load the app, so the whole test file fails (an excerpt; paths are shortened and stack lines are cut):
TypeError [ERR_PACKAGE_IMPORT_NOT_DEFINED]: Package import specifier "#sales/db/tickets.ts" is not defined in package .../tinytickets/package.json imported from .../tinytickets/src/door/routes/door.ts
...
✖ app.test.ts (184.962157ms)
...
ℹ tests 6
ℹ pass 5
ℹ fail 1
The five tests in the other files ran and passed, and the test file itself counts as the one failure. Now change the same line to a relative path into Sales:
import { findTicketByCode } from "../../sales/db/tickets.ts";
Predict what npm run check and npm test say this time.
What you should see: npm run check prints no errors, and npm test passes all 14 tests. A relative path never looks at "imports", so Node and tsc both accept it. Nothing stops Door from reading Sales’ internals this way, and nothing will, until a test checks it.
Rule:
"imports"closes the#door into a context. A relative path walks around it.
Step 5: Add a test that fails on a relative crossing
Why: the hole from Step 4 needs a check that fails the build. Run in the existing test command, it costs nothing to keep.
What to do: keep the relative import from Step 4 for now. Save this as test/boundaries.test.ts:
import assert from "node:assert/strict";
import { test } from "node:test";
import { readdirSync, readFileSync } from "node:fs";
import { dirname, join, relative, resolve, sep } from "node:path";
const src = resolve(import.meta.dirname, "../src");
// shortcut: a regex, not a parser; it misses specifiers built at run time.
const specifier = /\b(?:from|import)\s*\(?\s*['"]([^'"]+)['"]/g;
test("a context imports another context only through its # entry", () => {
const crossings: string[] = [];
for (const file of readdirSync(src, { recursive: true, encoding: "utf8" })) {
if (!file.endsWith(".ts")) continue;
const context = file.split(sep)[0];
for (const [, spec] of readFileSync(join(src, file), "utf8").matchAll(specifier)) {
if (!spec.startsWith(".")) continue;
const target = relative(src, resolve(src, dirname(file), spec));
if (target.split(sep)[0] !== context) crossings.push(`${file} -> ${spec}`);
}
}
assert.deepEqual(crossings, []);
});
The test reads every .ts file under src/, and the first folder of its path is its context. For each relative import, it works out the target’s path from src/, and it records the import if the target’s first folder differs.
It skips # and package imports, because Node and tsc already refuse a # import that is not listed. The Node.js test runner finds the file by its .test.ts name, so npm test needs no change.
What you should see: npm test runs 15 tests and fails one (an excerpt):
✖ failing tests:
test at test/boundaries.test.ts:10:1
✖ a context imports another context only through its # entry (11.837522ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'door/routes/door.ts -> ../../sales/db/tickets.ts'
+ ]
- []
The failure names the file and the import. Change the line back to import { findTicketByCode } from "#sales";, run npm test again (15 pass), and commit:
git add -A
git commit -m "Fail the tests when a context reaches into another"
The test has limits. It uses a regular expression, not a parser, so it also matches an import written inside a comment or a string, and it misses import(someVariable). It checks folders, not what an entry exports. And it treats platform/ like a context, so a context must use #platform too.
Step 6: Move each context’s tables into its own schema
Why: the tables still sit together in public, so nothing in a query says which context it reads. A schema per context puts the owner’s name in front of every table.
What to do: save this as migrations/014_create_context_schemas.sql:
-- Year 3: one schema per bounded context (see README.md).
-- SET SCHEMA moves each table with its rows, indexes, keys and sequence.
-- users, sessions and jobs belong to no context and stay in public.
CREATE SCHEMA shows;
CREATE SCHEMA sales;
CREATE SCHEMA door;
CREATE SCHEMA payouts;
ALTER TABLE shows SET SCHEMA shows;
ALTER TABLE organizers SET SCHEMA shows;
ALTER TABLE orders SET SCHEMA sales;
ALTER TABLE tickets SET SCHEMA sales;
ALTER TABLE door_tickets SET SCHEMA door;
ALTER TABLE payouts SET SCHEMA payouts;
The job queue stays a table in public, as the story requires. Run npm test before you change any SQL.
What you should see: every test that uses the database fails, because the test setup empties door_tickets and no table has that name in public any more (an excerpt):
Applied 014_create_context_schemas.sql
The database is up to date.
✖ the show page has a form to hold seats (29.459422ms)
✖ a hold leads to the payment page (0.905803ms)
...
✔ a context imports another context only through its # entry (8.69749ms)
ℹ tests 15
ℹ pass 6
ℹ fail 9
...
error: relation "door_tickets" does not exist
Now write the schema before every table name in the SQL of src/, app.test.ts and seed.ts. This command lists the lines to change:
grep -rnE "(FROM|JOIN|INTO|UPDATE|TRUNCATE) [a-z_]+" src *.ts
| Table | Write it as |
|---|---|
shows |
shows.shows |
organizers |
shows.organizers |
orders |
sales.orders |
tickets |
sales.tickets |
door_tickets |
door.door_tickets (renamed in Step 8) |
payouts |
payouts.payouts |
users, sessions, jobs, migrations |
unchanged, in public |
Change only the table name after FROM, JOIN, INTO, UPDATE and TRUNCATE. A column written as orders.status stays as it is, because PostgreSQL names the table orders inside the query even when its schema is written in the FROM. For example, in src/sales/db/orders.ts:
const result = await pool.query<Order>("SELECT * FROM sales.orders WHERE show_id = $1", [showId]);
In app.test.ts, the TRUNCATE lists every table:
`TRUNCATE door.door_tickets, payouts.payouts, sales.tickets, sales.orders,
shows.shows, shows.organizers, sessions, users, jobs RESTART IDENTITY`,
What you should see: npm test passes all 15 tests, with Door’s and Payouts’ queries still reading Sales’ tables. They pass because the app’s one database role owns every schema. A schema gives each table an owner’s name, and it stops no other context from reading it. Commit:
git add -A
git commit -m "Move the tables into one schema per context"
Step 7: Find the queries that cross, and ask the owner instead
Why: now that every table carries its context’s name, a query in one folder that names another context’s schema is easy to find.
What to do: list every table a query names whose schema differs from the folder it is in:
grep -rnoE "(FROM|JOIN|INTO|UPDATE) [a-z]+\.[a-z_]+" src | awk -F'[/ .]' '$2 != $(NF-1)'
grep -o prints each FROM sales.orders on its own line, after its file and line number. awk splits the line at /, spaces and dots, and prints it when the folder after src/ differs from the schema.
What you should see:
src/sales/db/tickets.ts:31:JOIN shows.shows
src/platform/db/dashboard.ts:19:FROM shows.organizers
src/platform/db/dashboard.ts:20:JOIN shows.shows
src/platform/db/dashboard.ts:21:JOIN sales.orders
src/platform/db/dashboard.ts:22:JOIN sales.tickets
src/platform/db/dashboard.ts:23:JOIN door.door_tickets
src/platform/db/dashboard.ts:24:JOIN payouts.payouts
src/payouts/db/payouts.ts:9:FROM shows.shows
src/payouts/db/payouts.ts:10:JOIN shows.organizers
src/payouts/db/payouts.ts:20:FROM sales.tickets
src/payouts/db/payouts.ts:20:JOIN sales.orders
The dashboard is the exception from earlier, and it stays. The other three crossings move to the context that owns the table.
First, findTicketByCode in src/sales/db/tickets.ts joins shows.shows only to get the organizer. Return the show’s ID instead, and leave the organizer to Shows:
export type TicketAtDoor = { code: string; kind: string; show_id: number; order_status: string };
export async function findTicketByCode(code: string): Promise<TicketAtDoor | undefined> {
const result = await pool.query<TicketAtDoor>(
`SELECT tickets.code, tickets.kind, tickets.show_id, orders.status AS order_status
FROM sales.tickets
JOIN sales.orders ON orders.id = tickets.order_id
WHERE tickets.code = $1`,
[code],
);
return result.rows[0];
}
In src/door/routes/door.ts, add import { findShow } from "#shows"; under the #sales import, and ask Shows for the organizer (an excerpt):
const ticket = await findTicketByCode(code);
const show = ticket === undefined ? undefined : await findShow(ticket.show_id);
if (ticket === undefined || show === undefined || show.organizer_id !== user.organizer_id) {
Second, listSoldTicketPrices reads only Sales’ tables. Move the whole function, unchanged, from src/payouts/db/payouts.ts to the end of src/sales/db/tickets.ts, and export it from src/sales/index.ts:
export { findTicketByCode, listSoldTicketPrices } from "./db/tickets.ts";
Third, listShowsToPay joins Shows’ tables to find the shows that ended five days ago. Shows can answer the date part. Add this to the end of src/shows/db/shows.ts:
export type EndedShow = { show_id: number; organizer_id: number; payout_account: string };
// Shows whose date is the given number of days ago or earlier.
export async function listShowsEndedDaysAgo(days: number): Promise<EndedShow[]> {
const result = await pool.query<EndedShow>(
`SELECT shows.id AS show_id, shows.organizer_id, organizers.payout_account
FROM shows.shows
JOIN shows.organizers ON organizers.id = shows.organizer_id
WHERE shows.show_date <= current_date - $1::integer`,
[days],
);
return result.rows;
}
And export it from src/shows/index.ts:
export { findShow, listShowsEndedDaysAgo, listUpcomingShows } from "./db/shows.ts";
export type { EndedShow, Show } from "./db/shows.ts";
Payouts keeps the rule “no payout yet”, because the payouts are its own data. Replace the start of src/payouts/db/payouts.ts, up to insertPayout, with this:
import { pool } from "#platform";
import { listShowsEndedDaysAgo } from "#shows";
import type { EndedShow } from "#shows";
// Shows that ended five days ago or earlier and have no payout yet.
export async function listShowsToPay(): Promise<EndedShow[]> {
const ended = await listShowsEndedDaysAgo(5);
const paid = await pool.query<{ show_id: number }>(
"SELECT show_id FROM payouts.payouts WHERE show_id = ANY($1)",
[ended.map((show) => show.show_id)],
);
const paidIds = paid.rows.map((row) => row.show_id);
return ended.filter((show) => !paidIds.includes(show.show_id));
}
The five days stay in Payouts, which passes them to Shows. In src/payouts/jobs/pay-organizers.ts, the imports become:
import { insertPayout, listShowsToPay } from "../db/payouts.ts";
import { sendTransfer } from "#platform";
import { listSoldTicketPrices } from "#sales";
import { payoutFor } from "../services/payouts.ts";
What you should see: npm run check prints no errors, and npm test passes all 15 tests. Run the grep again, and only the six dashboard lines are left.
One query became two. listShowsToPay asks Shows for every ended show, then removes the ones Payouts already paid. That’s more code, and it reads more rows than the join did.
No test covers the payout job, so run it against your own data before you deploy. Commit:
git add -A
git commit -m "Ask the context that owns a table instead of reading it"
Step 8: Give “ticket” one meaning in each context
Why: the folders and schemas are in place, but inside Sales “ticket” still means two things, and Door still stores scans in a table named for tickets.
What to do: in src/sales/services/pricing.ts, rename only the type declaration:
export type OrderLine = { kind: TicketKind; quantity: number };
Run npm run check.
What you should see:
src/sales/db/orders.ts(2,15): error TS2305: Module '"../services/pricing.ts"' has no exported member 'Ticket'.
src/sales/routes/holds.ts(7,15): error TS2305: Module '"../services/pricing.ts"' has no exported member 'Ticket'.
src/sales/services/holds.ts(6,15): error TS2305: Module '"./pricing.ts"' has no exported member 'Ticket'.
src/sales/services/pricing.ts(20,66): error TS2304: Cannot find name 'Ticket'.
All four are in src/sales/. The order-line meaning never left Sales, so the rename changes nothing outside it. Now save the database half as migrations/015_split_ticket.sql:
-- Year 3: "ticket" has one meaning in each context (see GLOSSARY.md).
-- In Sales, the lines of an order are not tickets. At the Door, a scan is not a ticket.
ALTER TABLE sales.orders RENAME COLUMN tickets TO lines;
ALTER TABLE door.door_tickets RENAME TO scans;
Then make the renames in Figure 6, by hand or with your editor.
| File | Old name | New name |
|---|---|---|
src/sales/services/pricing.ts |
parameter tickets: Ticket[], loop variable ticket in orderTotalCents |
lines: OrderLine[], line |
src/sales/db/orders.ts |
Ticket, the field tickets in Order and in insertOrder‘s parameter, r.tickets |
OrderLine, lines, r.lines |
src/sales/routes/holds.ts |
Ticket, the array tickets, ticket in the reduce |
OrderLine, lines, line |
src/sales/services/holds.ts |
Ticket, the parameter tickets, ticket in the reduce |
OrderLine, lines, line |
src/sales/services/orders.ts |
order.tickets |
order.lines |
src/sales/jobs/send-confirmation.ts |
for (const ticket of order.tickets) and ticket. inside that loop |
for (const line of order.lines), line. |
src/sales/db/tickets.ts |
IssuedTicket |
Ticket |
src/door/db/scans.ts |
insertDoorTicket, door.door_tickets |
insertScan, door.scans |
src/door/routes/door.ts |
insertDoorTicket |
insertScan |
src/platform/db/dashboard.ts |
door.door_tickets, door_tickets. |
door.scans, scans. |
app.test.ts |
door.door_tickets in the TRUNCATE |
door.scans |
Figure 6: in Sales, “ticket” now means a seat sold; an order has lines; Door keeps scans.
In src/sales/jobs/send-confirmation.ts, the variable tickets two lines above the loop holds Ticket rows, so it keeps its name. src/door/db/scans.ts now reads:
import { pool } from "#platform";
// One row per scan: a ticket's code, admitted once.
export async function insertScan(code: string, userId: number): Promise<boolean> {
const result = await pool.query(
`INSERT INTO door.scans (ticket_code, scanned_by) VALUES ($1, $2)
ON CONFLICT (ticket_code) DO NOTHING`,
[code, userId],
);
return result.rowCount === 1;
}
Run npm run check, then npm test.
What you should see: npm run check prints no errors, but five tests fail (an excerpt):
✖ a hold leads to the payment page (26.885746ms)
error: column "tickets" of relation "orders" does not exist
at async insertOrder (file:///.../tinytickets/src/sales/db/orders.ts:16:18)
at async createHold (file:///.../tinytickets/src/sales/services/holds.ts:17:17)
...
ℹ pass 10
ℹ fail 5
tsc checked every TypeScript name and none of the SQL. The INSERT in insertOrder still names the column tickets. In src/sales/db/orders.ts, change its second line:
`INSERT INTO sales.orders (token, show_id, buyer_name, buyer_email, quantity,
lines, amount_in_dollars, hold_expires_at)
Now run npm test again. The end of its output (from one run):
✔ four tickets or more pay no booking fee (0.180332ms)
✔ a context imports another context only through its # entry (9.298898ms)
ℹ tests 15
ℹ suites 0
ℹ pass 15
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
Then migrate the laptop’s own database, and list its tables by schema:
npm run migrate
docker exec tinytickets-db psql -U postgres tinytickets -c "SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema <> 'information_schema' AND table_schema <> 'pg_catalog' ORDER BY 1, 2"
What you should see: both migrations apply to the data seed.ts added in Module 1, and the tables are now in five schemas (Figure 7):
Applied 014_create_context_schemas.sql
Applied 015_split_ticket.sql
The database is up to date.
table_schema | table_name
--------------+------------
door | scans
payouts | payouts
public | jobs
public | migrations
public | sessions
public | users
sales | orders
sales | tickets
shows | organizers
shows | shows
(10 rows)
Figure 7: each context’s tables carry its name, and only the tables no context owns stay in public.
Last, the glossary. Remove “Ticket” from “Open questions”, and add this entry after “Payout”:
## Ticket
One word with a different meaning in each context. Leo's meaning is the
Sales one.
- In Sales: one seat sold on a paid order, with a code, a kind and a price.
Code: table `sales.tickets`, type `Ticket` (`src/sales/db/tickets.ts`).
- At the Door: a code that lets one person in, once. Door asks Sales for it
through `#sales` (`findTicketByCode`) and keeps only its scans.
- In Payouts: the price of a ticket sold, which counts toward the payout.
Payouts asks Sales for the prices through `#sales`
(`listSoldTicketPrices`).
- Do not say: ticket, for a line of an order or for a scan.
Give every other entry a - Context: line: Shows for Show and Organizer, Door for Scan, Payouts for Fee and Payout, and Sales for the rest. Then update the paths and table names in each “Code” line. In the “Order” entry, add the lines (sales.orders.lines, type OrderLine) and “Do not say: tickets, for the lines of an order”.
The code/module-03/ folder has the whole file. In README.md, add a short “Bounded contexts” section that lists the five entries and the dashboard exception, and update the “Files” block. Commit:
git add -A
git commit -m "Give ticket one meaning in each context"
How a door scan works now
Follow one scan at Leo’s club through the new code (Figure 8):
- Door staff type a code on
/doorand press “Scan”.app.tsmounteddoorRoutesfrom#door, soPOST /door/ticketsreachessrc/door/routes/door.ts. requireLoginfrom#platformchecks the session and puts the user onresponse.locals.- Door asks Sales with
findTicketByCodefrom#sales. Its SQL readssales.ticketsandsales.ordersand nothing else, and it answers with the code, the kind, the show’s ID and the order’s status. - Door asks Shows with
findShowfrom#shows, and compares the show’sorganizer_idwith the user’s. A code for another organizer’s show gets a 404. - If the order is not paid, the door answers 409.
insertScan, in Door’s own folder, writes a row todoor.scans. TheON CONFLICTmakes a second scan of the same code insert nothing, and the door answers 409 “already scanned”.- Otherwise the page says “Welcome!” with the ticket’s kind and code.
(Door staff) --> [Web app] app.ts --> {Door} POST /door/tickets
{Door} ..> platform/ requireLogin
{Door} ..> {Sales} findTicketByCode --> [[sales.tickets]]
[[sales.orders]]
{Door} ..> {Shows} findShow --> [[shows.shows]]
{Door} insertScan --> [[door.scans]]
Figure 8: Door writes only its own schema, and it reads the other two through their entries.
If Leo’s day-of-show rule came back now, it would be a change inside src/door/, because Door already has the show and its date. The exercise below makes it.
Going deeper
Five ways to enforce the boundary
This module uses "imports" plus a 22-line test because it adds no dependency and runs in the existing npm test. It also works with TypeScript 7.0 today, and it names the file that broke the rule. Figure 9 compares it with four other options on the same stack, Node.js 26.13.1 and TypeScript 7.0.2.
| Option | What it enforces | What it costs here |
|---|---|---|
"imports" and the boundary test |
# names only; no relative path into another folder |
a regular expression, not a parser |
npm workspaces, one package per context with "exports" |
only the files "exports" lists, imported by package name |
a package.json per context; relative paths still cross; type stripping refuses files under node_modules, so it works only while the symlinks resolve outside it |
| TypeScript project references | which context may depend on which | one tsconfig.json per context, declaration output, tsc -b; a deep relative import passed once the reference existed |
| dependency-cruiser | any rule about paths, plus graphs | with TypeScript 7.0 it printed “no dependency violations found (0 modules, 0 dependencies cruised)” and exited 0; it needed swc to check anything |
ESLint no-restricted-imports or eslint-plugin-boundaries |
rules per folder, shown in the editor | typescript-eslint required a TypeScript older than 6.1, so it ran only beside a second compiler (@typescript/typescript6): 95 packages, 220 MB |
Figure 9: the smallest tool that works is the one already installed, and two of the larger ones break on TypeScript 7.0.
"exports" is the field a package uses to list the files that other packages may import. Once it is present, every other path in the package is closed. The Node.js docs say this is not strong encapsulation, because an absolute path to a file still loads it.
The dependency-cruiser result is a warning about every check. It passed while it checked nothing. That’s why Step 5 broke the rule on purpose before trusting the test.
The choice flips when you need more than one rule. Module 8 adds layers inside each context, and Module 4 decides which directions between contexts are allowed. When the rules grow, or the team wants errors in the editor, a lint tool is worth its packages.
Those tools wait on TypeScript. The TypeScript 7.0 announcement says 7.0 ships without a programmatic API, and that a new one is planned for 7.1.
Schema, role or database per context
A schema per context names the owner and keeps every join possible, which is why the dashboard still works. Each context could also connect with its own database role, with USAGE on its own schema only. Then PostgreSQL refuses a crossing query with ERROR: permission denied for schema sales.
The cost of a role per context is one pool, or one connection setting, per context. A separate database per context goes beyond this course, which keeps one database for System Design to start from.
The foreign keys moved with the tables. Most keys across schemas point the same way as an import arrow: sales.orders and payouts.payouts refer to shows.shows. One does not, because users.organizer_id, in public, refers to shows.organizers.
A key also couples data, because PostgreSQL refuses to delete a row that a key still points at. So Shows cannot delete a show that has orders. Door’s scans has no key to sales.tickets, as before.
What the authors meant, and where practice went
Evans lists several things that can set a context’s boundary: team organization, use in parts of the application, and code bases and database schemas (Reference, p. 2). His Continuous Integration pattern (p. 5) adds a warning. If you keep cutting a system into smaller contexts, you lose integration and coherence between its parts.
Martin Fowler’s “BoundedContext” (2014) stresses the language, and says you need a different model when the language changes. Microsoft’s “Use domain analysis to model microservices” (2026) gives one drone a different model in each context, with only what that context needs. For TinyTickets, the language test is the one that found the boundary, because one word broke a test.
The DDD Crew’s Bounded Context Canvas lists what to write down about each context. Its fields include the purpose, the strategic classification, the messages the context receives and sends, its language and its open questions. The canvas says no message bus is required, so it fits contexts inside one app. The README’s short section is a start on it.
Shopify built a static boundary checker, Packwerk, for its modular monolith. Its 2024 retrospective reports that the team removed the checks for private code in version 3.0, because they had turned the tool into an API design tool. Static analysis also missed code loaded at run time, and lists of known violations grew faster than teams fixed them.
The boundary test in this module is exactly such a check for private files. So keep the entries small, and keep running the app and its tests too.
Fowler’s “MonolithFirst” (2015) argues that boundaries are hard to get right at the start, so a modular monolith comes first. Stefan Tilkov’s “Don’t start with a monolith” (2015) answers that a monolith’s parts couple tightly, because moving code between them is so easy. Both cases favor boundaries that something enforces.
What changed recently
- Node.js accepts subpath imports that start with
#/since v25.4.0 and v24.14.0, and TypeScript 6.0 (March 2026) supports them undernodenextandbundler(TypeScript 6.0 announcement). Node.js 22.17 rejects them. A catch-all such as"#/*": "./src/*"would open every file again, so this module names one entry per context. - TypeScript 7.0 (July 2026) has no programmatic API, so lint tools that read TypeScript lag behind it, as Figure 9 shows.
- Shopify’s Packwerk retrospective (January 2024) moved the advice from “check everything statically” toward small checks plus running the code.
- Since PostgreSQL 15, a new database no longer lets every user create tables in
public, so a role per context cannot leave stray tables there by default.
When one folder per context is too much
Skip it when a word has one meaning everywhere in the app. A small app with one team and one model gains folders and entries, and no test it did not have. Skip it too when the contexts would be so small that every change crosses three folders, which is Evans’ warning about losing integration.
And skip the boundary test if nobody will keep it in the suite. A skipped check is worse than none, because it suggests a boundary that nobody enforces. These limits are our judgment.
Check yourself
- What does “ticket” mean in Sales, at the Door and in Payouts, and which context owns the table?
Answer
In Sales, a seat sold on a paid order, with a code, a kind and a price. At the Door, a code that lets one person in once. In Payouts, a price that counts toward the payout. Sales owns sales.tickets, and Door and Payouts ask Sales through #sales.
- After Step 3, why does
#sales/db/tickets.tsfail, and why does../../sales/db/tickets.tswork?
Answer
"imports" lists only #sales, so Node.js throws ERR_PACKAGE_IMPORT_NOT_DEFINED and tsc reports TS2307 for any other #sales/... name. A relative path never looks at "imports", so both accept it.
- What does the boundary test check, and what can it miss?
Answer
It fails when a relative import in one folder of src/ points into another folder. It uses a regular expression, so it matches imports inside comments and strings, misses import(someVariable), and does not check what an entry exports.
- After migration 014, why did the tests still pass while Payouts read Sales’ tables, and how did you find those queries?
Answer
The app’s one database role owns every schema, so a schema names the owner but stops no query. The grep and awk command in Step 7 listed each table whose schema differs from the folder of the query.
- What does a modular monolith cost, and when would you not split the code into contexts?
Answer
More folders and entries, translation between contexts (two queries where one join did), and a check that must stay in the suite. Skip it when each word has one meaning in the whole app, or when the contexts would be so small that every change crosses several of them.
Exercise: Leo’s rule, inside the Door
Door staff still want a ticket to work only on the day of its show. Add the rule to TinyTickets without touching src/sales/, src/shows/ or any migration. The door should answer 409 when the show’s date is not today. Run the tests, and fix what fails.
Solution
Door already has the show from #shows, with its date. In src/door/routes/door.ts, after the check that the order is paid, add:
// shortcut: today's date in UTC; a venue in another time zone needs its own date.
if (show.show_date !== new Date().toISOString().slice(0, 10)) {
response.status(409).send(doorPage(`Ticket ${code} is for ${show.show_date}, not today.`));
return;
}
npm test then fails one test, “the door admits a ticket once”, with 409 !== 200. The test show is 30 days away, so the new rule refuses its ticket. In app.test.ts, give the test show today’s date:
VALUES (1, 'Test Show', current_date, '19:00', 'Test Club', 5, 12),
Now all 15 tests pass, and git diff --stat lists only src/door/routes/door.ts and app.test.ts. The postgres:18 container’s time zone is UTC, so current_date and toISOString() agree there. With a local PostgreSQL in another time zone, they may not agree late in the day.
Cheat sheet
Cheat sheet
- Bounded context: the part of the system where one word has one meaning; “ticket” differs in Sales, Door and Payouts.
- Modular monolith: one deployable app, split into contexts with boundaries a check enforces.
- Folder:
src/<context>/, with the layer folders inside;src/platform/holds no business rule.- Entry:
"imports"inpackage.jsonmaps#salestosrc/sales/index.ts; Node.js andtscrefuse other#names.- Test:
test/boundaries.test.tsfails on a relative import into another folder.- Schema: one per context, moved with
ALTER TABLE ... SET SCHEMA; writesales.ticketsin every query.- Crossings:
grepfor a schema that differs from the folder, then ask the owner through its entry.- Cost: more files, two queries where one join did, and a check that must stay in the suite.
Figure 10 is the whole module in one picture.
One meaning src/sales/ Sales keeps tickets, orders, order lines
One entry #sales package.json "imports" -> index.ts
Refused #sales/db/... Node.js and tsc: not defined
Caught ../../sales/... test/boundaries.test.ts
One schema sales.tickets migration 014, qualified names in SQL
Asked findTicketByCode Door reads Sales through #sales
Asked listShowsEndedDaysAgo Payouts reads Shows through #shows
Exception dashboard reads all four schemas until Module 10
Figure 10: each meaning of a word gets a folder, an entry and a schema, and a test keeps the folders apart.
The code now has four contexts in src/, each with one # entry and one schema, plus src/platform/ and a boundary test, and all 15 tests pass. Next, Module 4 looks at how the contexts talk. Door asks Sales for a ticket in a shape made for the Door, and the payment provider’s field names still reach deep into Sales.
Sources
- Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries, Domain Language, 2015 (CC BY 4.0). Definitions (p. vi), Bounded Context (p. 2), Continuous Integration (p. 5), Big Ball of Mud (p. 38).
- Martin Fowler, “BoundedContext”, January 15, 2014, and “MonolithFirst”, June 3, 2015.
- Stefan Tilkov, “Don’t start with a monolith”, June 9, 2015.
- Kirsten Westeinde, “Deconstructing the Monolith”, Shopify Engineering, February 21, 2019.
- Gannon McGibbon and Chris Salzberg, “A Packwerk Retrospective”, Rails at Scale, January 26, 2024.
- Melvin E. Conway, “How Do Committees Invent?”, Datamation, April 1968.
- Microsoft Learn, Use domain analysis to model microservices, 2026.
- DDD Crew, Bounded Context Canvas.
- Node.js documentation: Modules: Packages (subpath imports,
"exports"), TypeScript and the test runner. - TypeScript: Modules reference, Announcing TypeScript 6.0 (March 23, 2026) and Announcing TypeScript 7.0 (July 8, 2026).
- PostgreSQL 18 documentation: Schemas and ALTER TABLE.