On Monday, the payment provider announced a new API version, in which amount_cents is called amount. Omar moved TinyTickets’ test account to it, four days before a Friday sale.
His test payment went through on the provider’s page. TinyTickets answered 500, and the test email said “Paid: $NaN”, with no ticket codes.
“Why does a change at the payment company reach the email with my tickets?” Leo asked.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
The live account still used the old version, so no buyer saw the email. But the provider’s field names sit in three Sales files and in the job queue, so one rename outside TinyTickets broke a payment inside it.
This module draws a context map of TinyTickets: which part depends on which, and what kind of link each one is. Then it puts an anticorruption layer between the provider and Sales, so the provider’s next rename changes one file.
After this module, you can:
- draw a context map of an app: every link between its contexts and to outside services, which side must follow the other, and the pattern each link follows
- tell customer/supplier, open host service, published language, conformist, anticorruption layer, shared kernel and separate ways apart, and say which ones matter inside one team and one app
- build an anticorruption layer for a webhook in TypeScript: read the body as
unknown, check it, and translate it into your own type in one file - show what
tscfinds after an outside service renames a field, and what only a check at run time finds - say what an anticorruption layer costs, and when taking the outside model as it is costs less
Where the code stands
Module 3 left four bounded contexts, each with one folder, one # entry and one PostgreSQL schema. The payment provider’s client lives in src/platform/, and so does PaymentEvent, the type that copies the provider’s webhook body. Figure 1 is the code figure from Module 3.
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client and its PaymentEvent type,
the organizer dashboard.
Every context ..> platform/. app.ts and worker.ts ..> each #.
Figure 1: the arrows show which context imports which, and nothing shows how Sales talks to the payment provider.
One renamed field, three files and a stored job
Write Omar’s test payment as a test. Add this at the end of app.test.ts:
test("a webhook in the provider's next API version sends no email", async () => {
await post(`/shows/${leoShow}/hold`, { ...buyer, standard: "1" });
const order = await pool.query("SELECT token, payment_id FROM sales.orders WHERE status = 'pending'");
const { token, payment_id } = order.rows[0];
const sent = emails.length;
// In the provider's next API version, data.amount_cents is called data.amount.
const answer = await webhook({
id: "evt_2",
type: "payment.succeeded",
data: { payment_id, amount: 1350, currency: "usd", metadata: { order_ref: token } },
});
await runOneJob();
assert.deepEqual(emails.slice(sent), []);
assert.equal(answer.status, 400);
});
The test holds one $12 ticket, which costs $13.50 with the booking fee. Then it sends the webhook in the new version’s shape and runs one job, as the worker would. The two checks at the end say what TinyTickets should do: send no email, and answer 400, because it cannot read the body.
Pause and predict: the body has
amountand noamount_cents. Which check fails, and what does the email say, if there is one?
npm test
What you should see (an excerpt; paths are shortened, stack lines are cut, and your timings, dates and IDs will differ):
✔ the worker ends a hold when its time runs out (10.847218ms)
Error: Order b5a44454f46943f678cb9bf026bf1d1a: paid undefined cents, expected 1350.
at markOrderPaid (file:///.../tinytickets/src/sales/services/orders.ts:35:13)
at async file:///.../tinytickets/src/sales/routes/webhooks.ts:15:5
mail: caught an email to ana@tinytickets.example
✖ a webhook in the provider's next API version sends no email (23.156949ms)
...
ℹ tests 16
ℹ pass 15
ℹ fail 1
...
+ actual - expected
+ [
+ {
+ subject: 'Your tickets for Test Show',
+ text: 'Hello Ana,\n' +
...
+ 'Total: $13.50\n' +
+ 'Paid: $NaN (payment pay_5f5fab4a0ab06dc9)\n' +
+ '\n' +
+ 'Your ticket codes:\n' +
+ '\n' +
+ '\n' +
+ 'Show a code at the door.\n' +
+ 'TinyTickets',
+ to: 'ana@tinytickets.example'
+ }
+ ]
- []
The webhook route passed the body’s data to markOrderPaid, which read payment.amount_cents. That field is gone, so the value is undefined, and the check against the order’s total threw. The transaction rolled back, and Express 5 answered 500. The order is still on hold, with no tickets.
But markOrderPaid had already queued the email job, through enqueue, on a different connection, before the check. That job survived the rollback. Module 9 fixes that order of steps. The worker then printed undefined / 100, which is NaN, and listed no codes, because no tickets exist.
tsc saw none of this. In Express’s types, request.body is any, so request.body as PaymentEvent compiles whatever arrives. And Node.js removes the types before it runs the code (Node.js docs, TypeScript), so nothing compares the body with the type at run time.
Keep the test. It fails until Step 4. Now find the provider’s words in Sales:
grep -rnE "PaymentEvent|order_ref|amount_cents" src/sales
What you should see:
src/sales/jobs/send-confirmation.ts:5:import type { PaymentEvent } from "#platform";
src/sales/jobs/send-confirmation.ts:7:export async function sendConfirmation(payload: { payment: PaymentEvent["data"] }): Promise<void> {
src/sales/jobs/send-confirmation.ts:9: const order = await findOrderByToken(payment.metadata.order_ref);
src/sales/jobs/send-confirmation.ts:42:Paid: $${(payment.amount_cents / 100).toFixed(2)} (payment ${payment.payment_id})
src/sales/routes/webhooks.ts:4:import type { PaymentEvent } from "#platform";
src/sales/routes/webhooks.ts:13: const event = request.body as PaymentEvent;
src/sales/services/orders.ts:6:import type { PaymentEvent } from "#platform";
src/sales/services/orders.ts:9:export async function markOrderPaid(payment: PaymentEvent["data"]): Promise<void> {
src/sales/services/orders.ts:13: const order = await findOrderByToken(payment.metadata.order_ref, client);
src/sales/services/orders.ts:34: if (payment.amount_cents !== expectedCents) {
src/sales/services/orders.ts:35: throw new Error(`Order ${order.token}: paid ${payment.amount_cents} cents, expected ${expectedCents}.`);
src/sales/services/orders.ts:46:export async function cancelOrder(payment: PaymentEvent["data"]): Promise<void> {
src/sales/services/orders.ts:49: [payment.metadata.order_ref],
The provider’s body goes from the route to the service, from the service into the jobs table, and from the table to the worker (Figure 2).
[Payment provider] --> {Sales} routes/webhooks.ts request.body as PaymentEvent
{Sales} services/orders.ts payment.metadata.order_ref
payment.amount_cents
[[jobs]] payload {"payment": {"amount_cents": ...}}
[Worker] {Sales} jobs/send-confirmation.ts
payment.amount_cents / 100
Figure 2: the provider’s field names travel through three files and one table, so a rename at the provider reaches all of them.
That is Leo’s question. Module 1 sorted payments as a generic subdomain and Sales as the core. Here the generic part’s words run through the core, and through the data it stores.
A map of how the contexts talk
A context map says who depends on whom
A context map is a description of every bounded context in a system and of every link between them, including links to systems outside it. Evans’ Domain-Driven Design Reference (2015, p. 29) asks you to name each context and to describe each point of contact, with any translation between them. He adds one line on where to start:
“Map the existing terrain. Take up transformations later.” (Evans, Domain-Driven Design Reference, p. 29)
So the first map shows the code as it is, including the links nobody chose. TinyTickets’ link to the payment provider is one of them.
Every link has a direction. The upstream side of a link is the one whose changes affect the other side, and the downstream side is the one that must follow (Reference, p. 28). This is a different “upstream” from a Git branch’s upstream.
In code, the downstream side imports. Door imports #sales, so Sales is upstream of Door. The payment provider is upstream of Sales, and it changes on its own schedule.
It works because the direction tells you who must follow a change, and whom to ask before you make one. The cost is a file that goes stale, like the board from Module 2. So the map in Step 1 ends with the commands that check it against the code.
In TypeScript, the arrows are the imports. This course draws them as A ..> B, as in Figure 1, so A is downstream and B is upstream. For a service outside TinyTickets, ..> means that the code depends on its API.
When the upstream side plans for you
Three of Evans’ patterns describe an upstream side that does work for its downstream side.
A customer/supplier link is one where the upstream side plans for what the downstream side needs, and the downstream side says what that is (Reference, p. 32). Sales answers Door with TicketAtDoor, a shape made for the door, and Payouts with listSoldTicketPrices, which Module 3 moved into Sales for Payouts. Evans names the costs: someone must negotiate and budget the downstream’s needs, and those needs can hold up the upstream’s own work.
An open host service is one protocol that a context offers to all its clients, instead of one translation per client (Reference, p. 35). The #shows entry is one: Sales, Door and Payouts use the same three functions and two types. Here the protocol is a TypeScript entry, not an HTTP API. The cost is that every change to the protocol reaches every client, so the protocol has to change slowly.
A published language is a documented format for the data that two sides exchange, so that neither side’s own model becomes the format (Reference, p. 36). Evans says it often comes with an open host service. The provider’s webhook body is one: it is documented, and it has API versions. TinyTickets has no published language of its own yet.
Inside one team, these links are cheap. Maya, Nina and Omar plan both sides, and tsc reports a broken caller in the same commit as the change.
When the upstream side does not plan for you
The payment provider does not plan for TinyTickets, and it never will. The downstream side then has two choices.
A conformist link is one where the downstream side takes the upstream’s model as it is (Reference, p. 33). Evans writes that this choice makes integration much simpler. It costs the downstream side the freedom to model things its own way. TinyTickets conforms to the email service on purpose: sendEmail takes the service’s own fields, to, subject and text, and those words are fine in Sales.
TinyTickets also conforms to the payment provider’s webhooks, but nobody chose that. PaymentEvent is the provider’s body copied as a type, and Figure 2 shows how far it reached.
An anticorruption layer (ACL) is code in the downstream context that gives it the upstream’s functions in the downstream’s own words, translating in one direction or both (Reference, p. 34). Evans gives the reason: a large upstream interface can, over time, push its model into the downstream’s.
It works because the upstream’s words stop at the layer. A rename at the provider changes the layer, and the rest of Sales keeps its own types. The cost is one more folder, translation code, a test for it, and two sets of names for one idea. A bug in the translation is your bug.
In TypeScript, the layer takes the body as unknown, checks the fields it needs, and returns a type that Sales owns. The provider’s type stays inside the layer’s file, not exported. An ACL is built from the Adapter and Facade patterns, which Design Patterns in Plain Words, Module 3 teaches.
Sharing a model, or no link at all
A shared kernel is a small part of the model, in code or in the database, that two contexts share and change only after they agree (Reference, p. 31). Evans calls it a very close dependency and asks that it stay small. TinyTickets has none. src/platform/ is shared code, but it holds no part of TinyTickets’ model, and Module 3 keeps business rules out of it.
PaymentEvent is the one thing in platform/ that comes from a model. It is a piece of the provider’s model, kept in shared code, and imported by Sales. Step 4 moves it into Sales’ layer.
Separate ways means no link at all, because the benefit is too small for the cost of integration (Reference, p. 37). Door and Payouts import nothing from each other.
The 2015 Reference also adds partnership, which is new since Evans’ book (p. iii). It describes two teams that succeed or fail together, and so plan their interface together (p. 30). TinyTickets has one team, so every internal link is a partnership, and the word tells you nothing new here.
| Pattern | Who adapts | What it costs | In TinyTickets today |
|---|---|---|---|
| customer/supplier | the upstream plans for the downstream | the upstream’s planning time | {Door} ..> {Sales}, {Payouts} ..> {Sales} |
| open host service | every client uses one protocol | the protocol changes slowly | {Sales}, {Door}, {Payouts} ..> {Shows} through #shows |
| published language | both sides use a documented format | a format to document and version | the provider’s webhook body |
| conformist | the downstream takes the upstream’s model | the downstream’s freedom to model | {Sales} ..> [Email service]; the provider’s webhooks |
| anticorruption layer | the downstream translates | a layer, translation code, a test | none yet (Step 4) |
| shared kernel | both sides, together | close coupling, changes agreed by both | none |
| separate ways | nobody | work done twice, if any overlaps | Door and Payouts |
Figure 3: seven patterns, and TinyTickets already uses five of them.
Map the links, then move the provider to the edge
Each step says why, what to do, the code, and what you should see. Work in the project folder Module 3 left, with the new test from the previous section in app.test.ts. The finished code is in the code/module-04/ folder of the course repository.
Step 1: Write the map as the code is today
Why: the map comes first, before any change, so it shows the link to the provider as it is.
What to do: save this as CONTEXT-MAP.md, next to GLOSSARY.md:
# TinyTickets context map
How the four bounded contexts, and the services outside TinyTickets, depend
on each other. In every line the downstream side comes first: it imports,
and it must follow when the upstream side changes. `src/platform/` belongs
to no context, so it is not on the map. The map shows the code on the day
of its last commit, so check the code before you trust a line.
## Notation
{Sales} a bounded context
[Payment provider] a service outside TinyTickets
A ..> B A depends on B: A is downstream, B is upstream
## Between the contexts
{Sales} ..> {Shows} Open host service. Shows offers one entry,
{Door} ..> {Shows} #shows, and all three use its types (Show,
{Payouts} ..> {Shows} EndedShow) as they are.
{Door} ..> {Sales} Customer/supplier. Sales answers
findTicketByCode with TicketAtDoor, a shape
made for Door.
{Payouts} ..> {Sales} Customer/supplier. Sales answers
listSoldTicketPrices, made for Payouts.
{Door} {Payouts} Separate ways. Neither imports the other.
## With services outside TinyTickets
{Sales} ..> [Payment provider] Webhooks: conformist, never chosen.
The provider's PaymentEvent type is
used in three Sales files.
{Sales} ..> [Payment provider] Calls: createPayment and
{Payouts} ..> [Payment provider] sendTransfer in src/platform/ take
our arguments and build the
provider's request.
{Sales} ..> [Email service] Conformist, by choice. sendEmail
takes the service's own fields: to,
subject, text.
## Check it against the code
grep -roE 'from "#(shows|sales|door|payouts)"' src | awk -F'[/"]' '{print $2, "..>", $(NF-1)}' | sort | uniq -c
grep -rnE "PaymentEvent|order_ref|amount_cents" src/sales
The calls to the provider already go through two functions with plain arguments, createPayment(amountCents, orderRef) and sendTransfer(account, amountCents). So the provider’s request fields stay in one file of src/platform/. Only the webhook side has no translation.
Run the first check:
grep -roE 'from "#(shows|sales|door|payouts)"' src | awk -F'[/"]' '{print $2, "..>", $(NF-1)}' | sort | uniq -c
grep -o prints each from "#..." with its file. awk splits the line at / and ", and prints the context folder and the entry it imports. uniq -c counts the import lines.
What you should see:
1 door ..> #sales
1 door ..> #shows
1 payouts ..> #sales
2 payouts ..> #shows
6 sales ..> #shows
Five pairs, and each one is a line of the map. No line says door ..> #payouts or payouts ..> #door, so separate ways holds. Commit the map alone, and leave the new test uncommitted for now:
git add CONTEXT-MAP.md
git commit -m "Map how the contexts and the outside services depend on each other"
Step 2: Rename the provider’s field the conformist way
Why: once the team moves to the new version, someone updates the type. See how far that update reaches while Sales conforms.
What to do: in src/platform/services/payments.ts, change one line of PaymentEvent to the new version’s name (an excerpt):
amount: number;
Run npm run check.
What you should see:
src/sales/jobs/send-confirmation.ts(42,19): error TS2339: Property 'amount_cents' does not exist on type '{ payment_id: string; amount: number; currency: string; metadata: { order_ref: string; }; }'.
src/sales/services/orders.ts(34,17): error TS2339: Property 'amount_cents' does not exist on type '{ payment_id: string; amount: number; currency: string; metadata: { order_ref: string; }; }'.
src/sales/services/orders.ts(35,61): error TS2339: Property 'amount_cents' does not exist on type '{ payment_id: string; amount: number; currency: string; metadata: { order_ref: string; }; }'.
Three errors, in two Sales files, for a type that lives in src/platform/. And tsc found them only because someone edited the type. Omar’s test payment reached that code before anyone had edited it. Undo the change:
git checkout src/platform/services/payments.ts
Rule: a type describes outside data only after someone edits it. Until then, only a check at run time sees the change.
Step 3: Give Sales its own word for a payment
Why: Sales needs a type in its own words, so that the provider’s names can stop at one place. The glossary already has the word, “Payment”.
What to do: in src/sales/services/orders.ts, delete the line import type { PaymentEvent } from "#platform";, and add Sales’ type under the imports:
// A payment in Sales' words (see "Payment" in GLOSSARY.md).
export type Payment = { orderToken: string; paymentId: string; amountCents: number };
orderToken is the glossary’s name, because the order’s column is sales.orders.token. The provider calls the same value metadata.order_ref. Then make the changes in Figure 4.
| File | Old | New |
|---|---|---|
src/sales/services/orders.ts |
payment: PaymentEvent["data"] in markOrderPaid and cancelOrder |
payment: Payment |
src/sales/services/orders.ts |
payment.metadata.order_ref, twice |
payment.orderToken |
src/sales/services/orders.ts |
payment.amount_cents, twice |
payment.amountCents |
src/sales/jobs/send-confirmation.ts |
import type { PaymentEvent } from "#platform"; |
import type { Payment } from "../services/orders.ts"; |
src/sales/jobs/send-confirmation.ts |
payload: { payment: PaymentEvent["data"] } |
payload: { payment: Payment } |
src/sales/jobs/send-confirmation.ts |
payment.metadata.order_ref, payment.amount_cents, payment.payment_id |
payment.orderToken, payment.amountCents, payment.paymentId |
Figure 4: every Sales file except the route now speaks of a Payment, and the job stores one.
markOrderPaid still queues { payment }, so from now on the jobs table stores Sales’ words. Run npm run check.
What you should see:
src/sales/routes/webhooks.ts(15,25): error TS2739: Type '{ payment_id: string; amount_cents: number; currency: string; metadata: { order_ref: string; }; }' is missing the following properties from type 'Payment': orderToken, paymentId, amountCents
src/sales/routes/webhooks.ts(17,23): error TS2739: Type '{ payment_id: string; amount_cents: number; currency: string; metadata: { order_ref: string; }; }' is missing the following properties from type 'Payment': orderToken, paymentId, amountCents
Both errors are in the route, where the provider’s body meets Sales. That is the one place that needs a translation.
Step 4: Translate the webhook in one file
Why: the route needs a Payment, and the body is the provider’s. The layer between them is the only Sales code allowed to know the provider’s names.
What to do: save this as src/sales/acl/payment-provider.ts:
import type { Payment } from "../services/orders.ts";
// Anticorruption layer: the one Sales file that knows the payment provider's
// webhook body (its API version 2025-04). The rest of Sales uses Payment.
type ProviderEvent = {
id: string;
type: string;
data: {
payment_id: string;
amount_cents: number;
currency: string;
metadata: { order_ref: string };
};
};
// What a webhook tells Sales, in Sales' words.
export type PaymentNews = { result: "received" | "failed"; payment: Payment };
// Reads a body that nothing has checked yet. Returns undefined for the event
// types Sales does not use, and throws when a field Sales needs is missing.
export function translatePaymentWebhook(body: unknown): PaymentNews | undefined {
const event = (body ?? {}) as Partial<ProviderEvent>;
const result =
event.type === "payment.succeeded" ? "received" : event.type === "payment.failed" ? "failed" : undefined;
if (result === undefined) {
return undefined;
}
const paymentId = event.data?.payment_id;
const amountCents = event.data?.amount_cents;
const orderToken = event.data?.metadata?.order_ref;
if (
typeof paymentId !== "string" ||
typeof amountCents !== "number" ||
!Number.isInteger(amountCents) ||
typeof orderToken !== "string"
) {
const fields = Object.keys(event.data ?? {}).join(", ");
throw new Error(
`Payment webhook ${event.id} needs payment_id, amount_cents and metadata.order_ref; its data has ${fields}.`,
);
}
return { result, payment: { orderToken, paymentId, amountCents } };
}
The function takes unknown, so no caller can skip the checks. Partial<ProviderEvent> with ?. lets it read fields that may be missing. Each typeof check narrows a value from ... | undefined to its type, so tsc accepts the Payment at the end.
Two translations happen here. “payment.succeeded” becomes “received”, the board’s word from Module 2, and the provider’s three field names become Sales’ three. An event type that Sales does not use returns undefined, as the old route ignored it.
The error names the fields it needs and the fields it got, but not their values. The values include the order’s token, which opens the buyer’s order page, so they stay out of the log.
Now replace src/sales/routes/webhooks.ts with this:
import express from "express";
import { config } from "#platform";
import { translatePaymentWebhook } from "../acl/payment-provider.ts";
import type { PaymentNews } from "../acl/payment-provider.ts";
import { cancelOrder, markOrderPaid } from "../services/orders.ts";
export const webhookRoutes = express.Router();
webhookRoutes.post("/payments/webhook", async (request, response) => {
if (request.headers["x-webhook-secret"] !== config.webhookSecret) {
response.status(401).json({ error: "Wrong secret." });
return;
}
let news: PaymentNews | undefined;
try {
news = translatePaymentWebhook(request.body);
} catch (error) {
console.error(String(error));
response.status(400).json({ error: "This webhook cannot be read." });
return;
}
if (news?.result === "received") {
await markOrderPaid(news.payment);
} else if (news?.result === "failed") {
await cancelOrder(news.payment);
}
response.json({ received: true });
});
A body the layer cannot read gets a 400 before any Sales code runs. So no order changes, and no job is queued. The secret check stays first, as before.
Last, the provider’s type leaves src/platform/. In src/platform/services/payments.ts, delete the comment and the whole PaymentEvent type at the top of the file. In src/platform/index.ts, delete the line export type { PaymentEvent } from "./services/payments.ts";.
Run npm run check, npm test, and the second check from the map.
npm run check
npm test
grep -rnE "PaymentEvent|order_ref|amount_cents" src/sales
What you should see: npm run check prints no errors. The tests print the layer’s message and pass, all 16 (an excerpt, from one run):
✔ the worker ends a hold when its time runs out (10.402296ms)
Error: Payment webhook evt_2 needs payment_id, amount_cents and metadata.order_ref; its data has payment_id, amount, currency, metadata.
✔ a webhook in the provider's next API version sends no email (11.120282ms)
...
ℹ tests 16
ℹ suites 0
ℹ pass 16
ℹ fail 0
And grep finds the provider’s names in one file:
src/sales/acl/payment-provider.ts:10: amount_cents: number;
src/sales/acl/payment-provider.ts:12: metadata: { order_ref: string };
src/sales/acl/payment-provider.ts:29: const amountCents = event.data?.amount_cents;
src/sales/acl/payment-provider.ts:30: const orderToken = event.data?.metadata?.order_ref;
src/sales/acl/payment-provider.ts:39: `Payment webhook ${event.id} needs payment_id, amount_cents and metadata.order_ref; its data has ${fields}.`,
Omar’s message now names the field that changed. The boundary test from Module 3 still passes, because acl/ is a folder inside src/sales/. Commit:
git add -A
git commit -m "Translate the payment provider's webhook in one Sales file"
Step 5: Translate the jobs that wait in the queue
Why: before Step 3, every email job stored the provider’s body in jobs.payload. A job queued by the old code shortly before a deploy still has that shape, and the new worker reads payment.orderToken.
What to do: cause it first. The last npm test left one order on hold in tinytickets_test. In a second terminal, start the pretend services on the test ports:
node --env-file=.env.test fakes.ts
In the first terminal, queue an email job in the old shape for that order, then start the worker, and stop it with Ctrl+C after a few seconds:
docker exec -i tinytickets-db psql -U postgres tinytickets_test <<'SQL'
INSERT INTO jobs (kind, payload)
SELECT 'send_confirmation', jsonb_build_object('payment', jsonb_build_object(
'payment_id', payment_id, 'amount_cents', 1350, 'currency', 'usd',
'metadata', jsonb_build_object('order_ref', token)))
FROM sales.orders WHERE status = 'pending';
SQL
node --env-file=.env.test worker.ts
docker exec tinytickets-db psql -U postgres tinytickets_test -c "SELECT kind, attempts, last_error FROM jobs"
The job has no orderToken. Predict whether the worker fails, retries, or does something else.
What you should see:
INSERT 0 1
Worker started.
kind | attempts | last_error
------+----------+------------
(0 rows)
The job is gone, and the second terminal printed no mail: line. payment.orderToken is undefined, so findOrderByToken finds no order, and sendConfirmation returns as if the email were already sent. The worker deletes a job that returns, so nothing fails and nothing retries. On the server, that’s a buyer with no tickets in their inbox.
Now save this as migrations/016_translate_waiting_payment_jobs.sql:
-- Year 3: the email job carries a payment in Sales' words, not the provider's.
-- Jobs queued by the old code before the deploy keep working.
UPDATE jobs
SET payload = jsonb_build_object('payment', jsonb_build_object(
'orderToken', payload #> '{payment,metadata,order_ref}',
'paymentId', payload #> '{payment,payment_id}',
'amountCents', payload #> '{payment,amount_cents}'))
WHERE kind = 'send_confirmation' AND payload #> '{payment,metadata}' IS NOT NULL;
#> reads the value at a path inside a jsonb document, such as {payment,metadata,order_ref}. The WHERE picks only the old shape, so the migration leaves new jobs alone. Queue the old job again, run the migration, look at the payload, and run the worker again:
docker exec -i tinytickets-db psql -U postgres tinytickets_test <<'SQL'
INSERT INTO jobs (kind, payload)
SELECT 'send_confirmation', jsonb_build_object('payment', jsonb_build_object(
'payment_id', payment_id, 'amount_cents', 1350, 'currency', 'usd',
'metadata', jsonb_build_object('order_ref', token)))
FROM sales.orders WHERE status = 'pending';
SQL
node --env-file=.env.test migrate.ts
docker exec tinytickets-db psql -U postgres tinytickets_test -c "SELECT payload FROM jobs"
node --env-file=.env.test worker.ts
What you should see (your IDs will differ):
INSERT 0 1
Applied 016_translate_waiting_payment_jobs.sql
The database is up to date.
payload
---------------------------------------------------------------------------------------------------------------------------
{"payment": {"paymentId": "pay_d924e4539242b8ce", "orderToken": "2db09cc17b18efc733fcf1585e7caffd", "amountCents": 1350}}
(1 row)
Worker started.
This time the second terminal prints mail: caught an email to ana@tinytickets.example. Stop the worker and the pretend services with Ctrl+C. As in Module 1, the migration, the web app and the worker ship in one deploy. Commit:
git add -A
git commit -m "Translate the email jobs that wait in the queue"
Step 6: Rename the provider’s field again, behind the layer
Why: Step 2 counted what a rename reaches while Sales conforms. Count it again with the layer in place.
What to do: in src/sales/acl/payment-provider.ts, change the same line of ProviderEvent (an excerpt):
amount: number;
Run npm run check.
What you should see:
src/sales/acl/payment-provider.ts(29,35): error TS2339: Property 'amount_cents' does not exist on type '{ payment_id: string; amount: number; currency: string; metadata: { order_ref: string; }; }'.
One error, in the layer. Figure 5 puts the two runs side by side.
| Step 2, conformist | Step 6, with the layer | |
|---|---|---|
| Where the provider’s type lives | src/platform/services/payments.ts, exported |
src/sales/acl/payment-provider.ts, not exported |
tsc errors after the rename |
3, in 2 Sales files | 1, in the layer |
| An unreadable body at run time | 500, an email with Paid: $NaN |
400, one log line, nothing changed |
The jobs table |
the provider’s body | Sales’ Payment |
Figure 5: the same rename reaches two Sales files and a table, or one file.
Undo the change, because the provider’s live account still uses version 2025-04:
git checkout src/sales/acl/payment-provider.ts
Step 7: Update the map, the glossary and the README
Why: the map from Step 1 says Sales conforms to the provider’s webhooks, and that is no longer true.
What to do: in CONTEXT-MAP.md, add one line to the notation:
ACL an anticorruption layer, inside the context it protects
And replace the webhook entry (an excerpt):
{Sales} ..> [Payment provider] Webhooks: ACL. Only
src/sales/acl/payment-provider.ts
knows the provider's field names.
In GLOSSARY.md, replace the two list items of “Payment” with these three:
- Context: Sales. The provider's client is shared code.
- Code: type `Payment` (`orderToken`, `paymentId`, `amountCents`) in
`src/sales/services/orders.ts`, `createPayment`
(`src/platform/services/payments.ts`), `sales.orders.payment_id`.
- The provider's own words (`payment.succeeded`, `payment.failed`,
`amount_cents`, `order_ref`) stay in `src/sales/acl/payment-provider.ts`
for webhooks and in `src/platform/services/payments.ts` for calls.
In README.md, add a paragraph at the end of “Bounded contexts”:
`CONTEXT-MAP.md` says which context depends on which, and on which outside
service, and names the pattern of each link. Webhooks from the payment
provider enter Sales through `src/sales/acl/payment-provider.ts`, the one
Sales file that knows the provider's field names.
In the “Files” block, change 001 to 015 to 001 to 016, and add a line after GLOSSARY.md:
CONTEXT-MAP.md how the contexts and the outside services depend on each other
The code figure gets one new part inside Sales (Figure 6).
{Door} ..........> {Sales} <.......... {Payouts}
: : :
: v :
:.............> {Shows} <...............:
Inside {Sales}: routes/, services/, jobs/ ..> acl/ ACL NEW ..> [Payment provider]
Only acl/ knows the provider's webhook body.
platform/ the pool, the job queue, settings, page layout, login, email,
the payment provider's client, the organizer dashboard.
Every context ..> platform/. app.ts and worker.ts ..> each #.
Legend, added in this module
ACL an anticorruption layer, inside the context it protects
Figure 6: the arrows between contexts did not change; Sales now reaches the provider’s webhook body only through its layer.
What you should see: npm run check prints no errors, and npm test passes all 16 tests. The end of its output (from one run):
✔ four tickets or more pay no booking fee (0.244436ms)
✔ a context imports another context only through its # entry (7.838426ms)
ℹ tests 16
ℹ suites 0
ℹ pass 16
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
Commit:
git add -A
git commit -m "Show the payment layer on the context map"
How a payment webhook works now
Follow Ana’s payment through the new code (Figure 7):
- Ana presses Pay on the provider’s page. The provider sends
POST /payments/webhookwith a JSON body in its API version 2025-04. express.json()inapp.tsparses the body. In Express’s types it isany, and nothing has checked it.src/sales/routes/webhooks.tscompares the secret header. A wrong secret gets 401.translatePaymentWebhooktakes the body asunknown. It turns “payment.succeeded” into “received”, checkspayment_id,amount_centsandmetadata.order_ref, and returns aPaymentNewswith aPaymentin Sales’ words.- If a field is missing, the layer throws, the route logs the message and answers 400, and no other Sales code runs.
markOrderPaidfinds the order bypayment.orderTokenand marks it paid. It queues the email job with{ payment }, sojobs.payloadholds Sales’ words. Then it issues the tickets and comparespayment.amountCentswith the order’s total.- The worker runs
sendConfirmation, which readspayment.orderToken,payment.amountCentsandpayment.paymentId, and sends the email through the email service.
[Payment provider] --> [Web app] app.ts express.json() body: any
{Sales} routes/webhooks.ts secret, else 401
{Sales} acl/payment-provider.ts ACL unknown --> Payment, else 400
{Sales} services/orders.ts markOrderPaid --> [[sales.orders]]
--> [[sales.tickets]]
--> [[jobs]] {payment: Payment}
[Worker] {Sales} jobs/send-confirmation.ts --> [Email service]
Figure 7: the provider’s body stops at the layer, and everything after it, including the stored job, uses Sales’ words.
A payment.failed event takes the same path through steps 1 to 5, and then cancelOrder(news.payment) cancels the order by its token.
Going deeper
Conform or translate, and when the choice flips
Evans presents conformist as a reasonable choice. When the upstream side will not plan for you, taking its model makes integration much simpler (Reference, p. 33). He keeps the anticorruption layer for the case where the upstream’s model would push into yours (p. 34).
Microsoft’s Anti-corruption Layer pattern (2026) agrees on that limit. It says the pattern may not suit two systems whose meanings do not differ much, and it warns against putting business rules or orchestration in the layer.
For TinyTickets, the email service is the first case. It has three fields that mean what Sales means, so a layer would rename nothing. The payment provider is the second case: its words reached the core subdomain and the stored jobs.
The choice flips toward a layer when one of these becomes true:
- The outside service’s names appear in more than one folder. The second
grepinCONTEXT-MAP.mdis a cheap check. - The outside service changes on its own schedule, with versions that you must move to.
- The outside model touches your core subdomain, where your own words matter most.
It flips back when the upstream becomes something you control. If Payments were a context inside TinyTickets with its own open host service, Sales could conform to it, and tsc would show every break in the same commit.
One team, one app
Evans’ patterns describe how teams relate as much as how code relates. The DDD Crew’s context-mapping repository makes the split explicit. It lists three team relationships (mutually dependent, upstream/downstream and free) apart from nine patterns for a link.
Our reading for one team and one deployable app is this. The links between Shows, Sales, Door and Payouts are cheap to change, because the same three developers plan both sides and tsc checks both sides. So the map uses them to record direction, and the layers go where TinyTickets has no say, at the outside services. Evans does not make this claim, and it stops holding if a second team takes over a context.
Vaughn Vernon’s Implementing Domain-Driven Design (2013) gives context maps a chapter of their own (chapter 3), and integrating contexts another (chapter 13), according to the publisher’s table of contents.
Inside the context or as its own service
Evans describes the layer as part of the downstream context. Microsoft’s page allows two forms: a component inside the application, or an independent service. It lists costs for the service form: added latency on every call between the two systems, and one more service to run and scale.
TinyTickets uses the first form, a folder in src/sales/, because the story keeps one deployable app. The latency and the extra service do not apply, but the translation code and its tests do. Splitting into services belongs to System Design.
Types stop at the edge of the process
tsc checks code against types, and the types are gone before the code runs. Node.js strips them, and the body comes from express.json() as any. So a type for outside data is a promise that nothing keeps, until a check at run time keeps it.
That is why the layer takes unknown and checks each field by hand. Module 5 returns to this as “parse, don’t validate”, for the money inside the payment.
What changed recently
- Evans’ 2015 Reference marks Partnership as new since his book (p. iii). It also defines upstream and downstream, mutually dependent and free as team relationships (p. 28).
- Microsoft’s Anti-corruption Layer pattern page, dated May 2026, describes both the in-process form and the service form, with the costs of the service form.
- Node.js 26, an LTS release since October 2026, runs
.tsfiles by stripping their types, with no flag. So the layer’s check at run time is the only check the body gets.
When a layer is too much
Skip the layer when the outside model is small and its words already fit, as with the email service. Three fields with one meaning need no translation, and a layer would add a file and a test that rename nothing.
Skip it too between contexts that one team owns and one tsc run checks. There, conforming to an open host service costs a few edits in the same commit. And skip the map file when an app has two contexts and one outside service, because a paragraph in the README holds that. These limits are our judgment.
Check yourself
- In TinyTickets’ map, which side is upstream in the link between Door and Sales, and what does that tell you before you change
TicketAtDoor?
Answer
Sales is upstream, and Door is downstream, because Door imports #sales. A change to TicketAtDoor reaches Door, and the link is customer/supplier, so Sales plans the change with Door’s needs in mind.
- What is
#showsin the map’s terms, and why issrc/platform/not a shared kernel?
Answer
#shows is an open host service: one entry that Sales, Door and Payouts all use, and all three take its types as they are. src/platform/ is shared code, but a shared kernel is a shared part of the model, and platform/ holds no part of TinyTickets’ model.
- What are the three parts of the webhook layer, and which Sales file may import the provider’s type?
Answer
It takes the body as unknown, checks the fields Sales needs, and translates them into Sales’ own type, Payment, inside a PaymentNews. Only src/sales/acl/payment-provider.ts knows the provider’s type, and it does not export it.
- Why did
tscsay nothing about Omar’s test payment, and what reported the problem after Step 4?
Answer
request.body is any, the cast to PaymentEvent promised a shape nobody checked, and the types are stripped before the code runs. After Step 4, the layer’s check at run time throws, and the route answers 400 with a log line that names the missing field.
- What does the layer cost, and why does Sales conform to the email service instead?
Answer
One more folder, translation code, a test, two sets of names for one idea, and a migration for stored jobs. The email service has three fields that already mean what Sales means, so a layer would rename nothing.
Exercise: refuse a payment in another currency
The provider’s body has a currency field, and the layer ignores it. Payment has no currency, because Sales keeps every amount in US cents. Make the layer refuse a body whose currency is not usd, with a test that sends "eur" and expects 400. Run the test before and after your change.
Solution
Add the test at the end of app.test.ts:
test("a payment in another currency is refused at the edge", async () => {
const answer = await webhook({
id: "evt_3",
type: "payment.succeeded",
data: { payment_id: "pay_3", amount_cents: 1350, currency: "eur", metadata: { order_ref: "no-such-order" } },
});
assert.equal(answer.status, 400);
});
Before the change, it fails with 200 !== 400. The layer translates the body, and markOrderPaid finds no order with that token, so the route answers 200. In src/sales/acl/payment-provider.ts, add these lines before the last return:
// Sales keeps every amount in US cents, so it cannot read another currency.
if (event.data?.currency !== "usd") {
throw new Error(`Payment webhook ${event.id} is in ${event.data?.currency}, and Sales reads only usd.`);
}
Now npm test passes all 17 tests, and the output includes Error: Payment webhook evt_3 is in eur, and Sales reads only usd. The check belongs in the layer because it is translation, not a business rule. Sales has no word for a euro, so the layer cannot turn one into a Payment.
Cheat sheet
Cheat sheet
- Context map: every context and outside service, which side depends on which, and the pattern of each link.
- Upstream, downstream: the downstream side imports, and it must follow when the upstream side changes.
- The upstream plans for you: customer/supplier (a shape per client), open host service (one entry for all), published language (a documented format).
- Conformist: take the upstream’s model as it is; cheap when its words already fit, as with the email service.
- Anticorruption layer:
unknownin, checked, translated into your own type, in one file that keeps the outside type.- Shared kernel, separate ways: share a small model on purpose, or keep no link at all.
- Types at the edge:
tscsees an outside rename only after someone edits the type; a check at run time sees it first.- Stored shapes: data in the job queue keeps the old words, so it needs a migration.
- Cost: a folder, translation code, a test, two names for one idea; skip it for small links whose words fit.
Figure 8 is the whole module in one picture.
Map CONTEXT-MAP.md each link: direction and pattern
Inside #shows, #sales open host service, customer/supplier
Outside [Email service] conformist, by choice
Outside [Payment provider] ACL in src/sales/acl/payment-provider.ts
Edge body: unknown checked and translated to Payment, or 400
Stored jobs.payload migration 016 translates waiting jobs
Rename amount_cents one tsc error, in the layer
Figure 8: map the links as they are, then put a layer where an outside model reaches your core.
The code now has a context map, and the provider’s webhook body stops at one file in Sales, and all 16 tests pass. Next, Module 5 looks at the money itself. amountCents is still a plain number, and nothing stops a dollar amount from going where cents belong.
Sources
- Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries, Domain Language, 2015 (CC BY 4.0). New patterns (p. iii), Definitions of team relationships (p. 28), Context Map (p. 29), Partnership (p. 30), Shared Kernel (p. 31), Customer/Supplier Development (p. 32), Conformist (p. 33), Anticorruption Layer (p. 34), Open-host Service (p. 35), Published Language (p. 36), Separate Ways (p. 37).
- DDD Crew, Context Mapping.
- Microsoft Learn, Anti-corruption Layer pattern, Azure Architecture Center, 2026.
- Vaughn Vernon, Implementing Domain-Driven Design, Addison-Wesley, 2013: table of contents.
- Node.js documentation: TypeScript.