Domain-Driven Design in TypeScript / Module 09

Module 9: Domain Events and the Outbox

Record a domain event in the aggregate, save it in an outbox with the sale, relay it into the job queue, and make every handler safe to repeat.

On Friday at 10:03, a buyer at one of Leo’s sales paid for two tickets. A minute later she got the ticket email from TinyTickets, with no ticket codes in it. Soon after 10:12, the worker cancelled her order, because its hold had run out.

“She paid, and she has our email,” Leo wrote. “Did she buy a ticket or not?”

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

Nina traced it that afternoon. The payment’s transaction had failed on a ticket code that an older ticket already had, so PostgreSQL rolled it back, and the order stayed held. But the email job was already in the queue. It had been written on a second connection, and that write committed at once.

This module turns “Tickets issued”, an event from Module 2’s board, into a fact the Sale records. The event is saved in an outbox table in the same transaction as the sale, and the worker turns it into jobs after the commit. Door gets its own list of tickets from the same event, and every job handler becomes safe to run twice.

After this module, you can:

  • turn an event from the board into a TypeScript type that an aggregate records, and test it with no database
  • save domain events in an outbox in the same transaction as the aggregate, and show with a test that a rolled-back payment queues no email
  • relay the outbox into the existing job queue with FOR UPDATE SKIP LOCKED, so Sales publishes an event without knowing who reacts to it
  • make each job handler safe to run twice, and choose “at least once” or “at most once” for an effect outside the database
  • say what eventual consistency between Sales and Door costs, and when an outbox is not worth its table

Where the code stands

Module 8 put PostgreSQL behind ports. markOrderPaid in src/sales/application/sales.ts loads the sale, pays the order, saves it, and calls the port queueConfirmation, which src/sales/wiring.ts fills with enqueue from #platform. Figure 1 is the code figure Module 8 ended with.

{Door} ..........> {Sales} <.......... {Payouts}
   :                  :                    :
   :                  v                    :
   :.............> {Shows} <...............:

{Shows}, {Sales}, {Payouts} ..> money/   the shared kernel (#money)

Inside {Sales}:  routes/ ..> wiring.ts ..> application/ ..> domain/
                 db/, jobs/, acl/ ..> application/; db/, jobs/ ..> domain/
                 domain/       Sale, Order, pricing (a domain service), and
                               the port SaleRepository; imports only
                               domain/ and #money
                 application/  salesService: one function per command, the
                               transaction and the retry; ports
                               WithTransaction, startPayment
                 db/           the PostgreSQL adapters; ..> {Shows}
                               findShow on the transaction's client
                 wiring.ts     the composition root
                 routes/ ..> acl/ ACL ..> [Payment provider]
                 A test fails when domain/ or application/ imports
                 anything else.

platform/   the pool, the job queue, settings, page layout, login, email,
            the payment provider's client, the organizer dashboard.
            Every context ..> platform/. platform/ ..> money/.
            app.ts and worker.ts ..> each #.

Figure 1: the contexts as Module 8 left them; Door asks Sales about each ticket it scans.

This module leans on the job queue, so here are the three facts it needs. A job is a row in the table jobs, with a kind, a JSON payload and a time to run. The worker (worker.ts) claims one due row at a time, runs the handler for its kind, and deletes the row when the handler succeeds. The course Background Jobs covers the queue in depth, including what happens when a handler fails.

A payment that rolled back, and an email that went out anyway

The payment command is markOrderPaid. This is the work it does inside the transaction (an excerpt of src/sales/application/sales.ts, lines 84 to 95):

        const outcome = sale.pay(token, deps.now());
        await sales.save(sale);
        if (outcome !== "paid") {
          return outcome;
        }
        await deps.queueConfirmation(payment);
        await issueTickets(token, sale.tickets(token, newTicketCode));
        const totalCents = sale.order(token).details.totalCents;
        if (payment.amountCents !== totalCents) {
          throw new Error(`Order ${token}: paid ${payment.amountCents} cents, expected ${totalCents}.`);
        }
        return outcome;

And this is enqueue, which fills queueConfirmation (an excerpt of src/platform/db/jobs.ts):

export async function enqueue(kind: string, payload: object): Promise<void> {
  await pool.query("INSERT INTO jobs (kind, payload) VALUES ($1, $2)", [kind, payload]);
}

withTransaction runs BEGIN on one client from the pool, and the repository uses that client. enqueue calls pool.query, which takes any free client and runs one statement outside the transaction, so PostgreSQL commits that statement on its own. Figure 2 shows the two connections on Friday.

[Web app] markOrderPaid
  client 1: the transaction            client 2: pool.query
  BEGIN
  sale.pay, sales.save   order: paid
                                       INSERT INTO jobs   committed at once
  issueTickets           X a code that already exists
  ROLLBACK               order: held
[Worker]  send_confirmation --> [Email service]   "Your tickets", no codes

Figure 2: the job’s insert ran on another connection, so the rollback could not take it back.

Pause and predict: the job’s INSERT runs before the error, on the second connection. After the transaction rolls back, is the job still in the table, and what does the worker send?

A duplicate ticket code is hard to cause on purpose. The amount check also comes after the job, so Nina’s test pays the wrong amount instead. Add it to app.test.ts, before the load test:

// Nina's test. The order's total is 2150 cents, so a payment of 2000 fails
// the amount check, and the transaction rolls back.
test("a payment whose transaction rolls back sends no email", async () => {
  const bea = { name: "Bea", email: "bea@tinytickets.example" };
  const show = await pool.query("SELECT id FROM shows.shows WHERE name = 'Other Show'");
  await post(`/shows/${show.rows[0].id}/hold`, { ...bea, standard: "1" });
  const order = await pool.query("SELECT token, payment_id FROM sales.orders WHERE buyer_email = $1", [bea.email]);
  const { token, payment_id } = order.rows[0];
  const answer = await webhook({
    id: "evt_9",
    type: "payment.succeeded",
    data: { payment_id, amount_cents: 2000, currency: "usd", metadata: { order_ref: token } },
  });
  assert.equal(answer.status, 500);
  assert.deepEqual(await stateOf(token), [{ status: "held", paid: false, cancelled: false }]);
  while (await runOneJob()) {}
  assert.deepEqual(emails.filter((email) => email.to === bea.email).map((email) => email.subject), []);
});

The buyer has her own email address, so the last line counts only her emails. while (await runOneJob()) {} runs every job that is due, as the worker would. Run the tests:

npm test

What you should see (an excerpt from one run):

✖ a payment whose transaction rolls back sends no email (34.766862ms)
ℹ tests 45
ℹ suites 0
ℹ pass 44
ℹ fail 1
...
  + [
  +   'Your tickets for Other Show'
  + ]
  - []

The webhook answered 500 and the order is still held, so those two checks pass. The job stayed in the table, though, and the worker sent the email. With console.log(emails.at(-1)?.text) added before the last line, the same run printed this (your dates and payment ID will differ):

Hello Bea,

Your tickets for Other Show on 2026-12-19, doors open at 20:00, Other Club.

1 x standard ticket, $20.00 each
Booking fee, $1.50
Total: $21.50
Paid: $20.00 (payment pay_fcee545e672a7d5e)

Your ticket codes:


Show a code at the door.
TinyTickets

The email has no codes, because the tickets rolled back with the payment. Remove the console.log line if you added it, and keep the test, which fails until Step 2. Commit it:

git add -A
git commit -m "Test that a rolled-back payment sends no email"

Three quick fixes come to mind. Each one fails in its own way:

  • Queue the job last. queueConfirmation still runs on the second connection, so a failed COMMIT leaves the same job behind. The worker can also run the job before the COMMIT finishes, while the tickets are not yet visible to it.
  • Check the order’s status in the job. That moves the race to the other side. If the worker runs the job before the payment commits, it reads a held order and skips it, and no email ever goes out.
  • Queue the job after the COMMIT. Then a crash between the COMMIT and the queue loses the email for a paid order.

The job, or a record that the payment happened, has to commit in the same transaction as the payment. The next section builds that.

Events that commit with the sale

A domain event in code is a fact the aggregate records

Module 2 wrote domain events on the board in the past tense, in Leo’s words. Two policies and one event in BOARD.md describe this part of the sale:

POL  Whenever a payment is received, issue the tickets
EVT  Tickets issued
POL  Whenever tickets are issued, email them to the buyer

In code, a domain event is an immutable value that records one such fact, so other code can react to it later. Evans’ Reference (2015, p. 13) says an event usually carries the time it happened and the identities of the entities involved. Vernon’s example event in “Effective Aggregate Design”, Part III (2011, p. 14), carries IDs, not object references. So TicketsIssued carries the show’s ID, the order’s token, the ticket codes and the time.

This is a different “event” from an EventEmitter event in Node.js. Design Patterns in Plain Words Module 5 uses an emitter, which calls every listener at once, in the same process. A domain event is data. It is stored, and a handler may run much later, in another process.

In Jimmy Bogard’s “A better domain events pattern” (2014), the entity adds each event to a list instead of sending it at once, and the save step sends the list. That fits Module 8’s Sale. It already lists the orders it added and changed in changes(), so it can list its events there too, and a domain test can check them with no database.

Not every event on the board becomes a type. “Seats held” stays a line on the board, because no code reacts to it yet. The cost of a recorded event is that someone must save it. A repository or a fake that forgets to save it loses the event, and nothing fails.

Before the commit, after it, or with it

The event must reach its handlers at some point. Figure 3 compares the three points you can pick.

When the handler runs Who describes it What goes wrong for the ticket email
In the same process, before COMMIT, inside the transaction Dahan (2009), Bogard (2014) the email goes out for a payment that later rolls back (Bea’s email)
In the same process, after COMMIT Microsoft’s guide (2018, updated 2024) a crash between COMMIT and the handler loses the email
Later, from a row written in the same transaction Richardson, “Transactional outbox” the email arrives later, and may arrive twice

Figure 3: three points to run an event’s handlers; only the last one commits the event with the payment.

Udi Dahan’s “Domain Events – Salvation” (2009) runs the handlers at once, in the same transaction as the domain work. He also warns against slow work in a handler, such as calling an email server, and suggests sending a one-way message instead. Bogard (2014) collects the events and sends them at save: “Just before we commit our transaction, we dispatch our events”. Microsoft’s guide to domain events offers both moments, right before or right after the commit, and says the choice decides between one transaction and eventual consistency.

Running a handler before the commit suits a rule inside Sales that must hold when the transaction ends. For an effect outside the database, such as an email, it sends too early.

The transactional outbox writes the event in the same transaction

A transactional outbox is a table where code writes the messages it wants to send, in the same transaction as its own changes. The messages commit or roll back with the changes, and a separate process sends them afterward. Chris Richardson’s pattern page, “Transactional outbox”, states what it buys:

“Messages are guaranteed to be sent if and only if the database transaction commits” (Richardson, “Pattern: Transactional outbox”)

His page also lists the costs. A developer might forget to write the outbox row, and the sender might send a message more than once. TinyTickets adds a third cost, one more table and one more loop in the worker.

In TinyTickets, the repository writes the outbox row in save, on the transaction’s client. A command cannot forget it, because the Sale records the event and the repository saves whatever the sale lists. The outbox lives in the public schema next to jobs, because every context may write to it, and src/platform/ owns it as it owns the queue.

Design Patterns in Plain Words Module 7 solved a smaller version. It wrote the email job in the checkout’s own transaction. That is equally atomic, and it is the right choice when the email is the only thing that reacts.

But Sales would then write one job for every reaction, in every context. Door is about to need one too. With the outbox, Sales writes one fact in its own words, and the worker decides who reacts to it.

A relay moves the outbox into the job queue

A relay is the code that reads the outbox after the commit and passes each event on. Richardson names two kinds: a polling publisher, which queries the table, and transaction log tailing, which reads the database’s transaction log. TinyTickets uses a polling relay inside the existing worker, and it passes events into the jobs table, because the queue stays a table in this stage.

The relay works in one transaction. It deletes up to 100 outbox rows, inserts one job for each subscriber of each event, and commits. The deletes and the inserts commit together, so an event turns into its jobs once.

Two relays at the same time must not take the same rows. FOR UPDATE locks the rows a SELECT returns, and SKIP LOCKED tells PostgreSQL to skip rows that another transaction has locked instead of waiting for them. The PostgreSQL docs on SELECT say this gives an inconsistent view of the data, which suits several consumers of a queue-like table. claimJob in src/platform/db/jobs.ts already claims jobs this way.

Ids are another trap. A sequence hands out an id when a row is inserted, not when its transaction commits. The sequence docs also say a value “is not reclaimed for re-use if the calling transaction later aborts”, so a rolled-back event leaves a gap. Step 2 shows a gap, and Step 3 shows why a relay that remembers the last id it saw loses events.

At least once, so every handler must be safe to repeat

The job queue delivers at least once, which means a job can run more than once. The worker can run a handler and crash before finishJob deletes the row. claimJob locks a job for five minutes, so after that, another pass claims it again.

A handler is idempotent when running it twice has the same result as running it once. Richardson’s page and Gunnar Morling’s “Reliable Microservices Data Exchange With the Outbox Pattern” (2019) both conclude that every consumer of an outbox must be idempotent.

Richardson’s “Idempotent Consumer” shows the general tool. A table of processed message IDs is written in the handler’s own transaction, so a second delivery fails on the key and changes nothing. Evans (p. 13) gives the domain side of it. An event’s identity lets a receiver recognize the same event twice.

TinyTickets’ handlers have natural keys, so they need no such table. Figure 4 lists each one.

Handler Its effect Safe to repeat because What a crash can still do
the relay jobs the deletes and the inserts commit together nothing
add_tickets_at_door rows in door.tickets ON CONFLICT (code) DO NOTHING nothing
send_confirmation an email it checks confirmation_sent_at first a crash after the send and before the mark sends a second email
pay_organizers a transfer the payout’s row is written first (Step 6) a crash after the row and before the transfer leaves a row for a person to check

Figure 4: each handler and the key that makes a second run harmless.

An email and a transfer leave the database, so no transaction covers them, and you have to choose. A second email is a nuisance, so the email is sent at least once. A second transfer is lost money, so the payout is sent at most once, and a person finishes the rare case by hand.

Some outside services accept a key that makes a repeated request harmless. With such a service, pass a key that names the request, such as the order’s token or the show’s ID. The pretend services in fakes.ts accept no such key.

Eventual consistency between Sales and Door

Today the door asks Sales about every scan. findTicketByCode joins two Sales tables, and the door route then checks the order’s status itself, so Sales’ rule “a ticket counts only on a paid order” lives in Door too. With TicketsIssued, Door can keep its own list. Sales issues tickets only for paid orders, so the list holds Sales’ answer, and Door reads no Sales table.

The cost is eventual consistency. Under eventual consistency, two contexts agree after a delay, not at the moment of the commit.

Evans (p. 16) asks for this split. Rules inside an aggregate apply at once, and rules across aggregates apply asynchronously. Vernon (Part II, 2011, p. 9) says to ask the domain experts how much delay they accept.

Leo asked the plain question this raises: can a buyer who paid a moment ago get in at once? The door knows the ticket only after the worker comes round, relays the event, and runs Door’s job. An idle worker looks for work once a second, and a long queue makes the wait longer. Step 4 writes a test for it. Vernon (Part III, p. 14) names the options for a screen that may be stale: poll, push, or tell the user that it may lag.

Door and Sales now share a contract, the event’s fields as JSON. Module 4 called such a shared format a published language. Door writes down the two fields it reads, and no type connects them to Sales’ type. If Sales renames tickets, tsc stays quiet, and the test “the door admits a ticket once” in app.test.ts fails instead.

When one transaction cannot cover the work: sagas

The payment already spans two systems. The provider charges the buyer outside the database, and ROLLBACK cannot undo a charge, as Design Patterns Module 7 says. When a payment comes after the hold ran out, Module 6’s rule cancels the order, and someone refunds the buyer by hand.

A saga is a long piece of work written as a sequence of shorter transactions, where either all of them complete or compensating transactions undo the part that ran. Hector Garcia-Molina and Kenneth Salem introduced the idea in “Sagas” (1987). Their motive was that long-lived transactions hold resources and delay short ones. The refund is TinyTickets’ one compensating step (Figure 5).

Hold seats      -->  Pay at the provider   -->  Mark paid, issue tickets
Sales, one          outside TinyTickets,       Sales, one transaction
transaction         no ROLLBACK                   |
                                                  | too late?
                                                  v
                                             Refund by hand: the
                                             compensating step

Figure 5: the sale as three steps; only the last one can find out that the first one expired.

Richardson’s “Saga” page names two ways to run the steps. In choreography, each step publishes an event, and the next step reacts to it, which is what TicketsIssued does for the email and the door. In orchestration, one object tells each step what to do and keeps the state of the whole flow.

Gregor Hohpe and Bobby Woolf’s “Process Manager” is that object: “a central processing unit, a Process Manager, to maintain the state”. Richardson also warns that a saga has no automatic rollback, and that sagas running at once see each other’s partial work.

TinyTickets does not need an orchestrator yet. Its flow has three steps, and a person does its one compensating step, the refund. It becomes worth one when refunds must happen without a person, or when a flow has several steps that can each fail.

Publish the sale’s events through an outbox, step by step

Each step says why, what to do, the code, and what you should see. Work in the project folder Module 8 left, with Nina’s test added. The finished code is in the code/module-09/ folder of the course repository. If you kept the exercise from Module 4, your test counts are one higher.

Step 1: Let the sale record TicketsIssued

Why: the event belongs to the aggregate that makes the tickets. Module 8’s Sale.tickets(token, newCode) already makes them, so it records the event, and its name becomes the verb Leo uses.

What to do: save this as src/sales/domain/events.ts:

import type { TicketKind } from "./pricing.ts";

// A domain event of Sales: "Tickets issued" on the board (BOARD.md). A fact
// in Leo's words, in the past tense, that never changes once it is recorded.
// It names the show and the order by their IDs.
export type TicketsIssued = {
  readonly type: "TicketsIssued";
  readonly showId: number;
  readonly orderToken: string;
  readonly tickets: readonly { readonly code: string; readonly kind: TicketKind }[];
  readonly occurredAt: Date;
};

The type field names the event, so code that reads it back from JSON knows what it holds. Every field is readonly, down to the list of tickets.

In src/sales/domain/sale.ts, import the type, and give the sale a list of events after #changed (two excerpts):

import type { TicketsIssued } from "./events.ts";
  // The events this copy of the sale recorded, for the repository to save.
  readonly #events: TicketsIssued[] = [];

Then replace tickets and changes with these two methods (an excerpt):

  // Issues the tickets of a paid order: one per seat, at the price of its
  // kind. Records TicketsIssued with their codes.
  issueTickets(token: string, newCode: () => string, now: Date): NewTicket[] {
    const order = this.#find(token);
    if (order.state.status !== "paid") {
      throw new Error(`Order ${token} is ${order.state.status}, not paid; it gets no tickets.`);
    }
    const tickets = order.details.lines.flatMap((line) =>
      Array.from({ length: line.quantity }, () => ({
        kind: line.kind, code: newCode(), priceCents: ticketPriceCents(this.priceCents, line.kind),
      })),
    );
    this.#events.push({
      type: "TicketsIssued",
      showId: this.showId,
      orderToken: token,
      tickets: tickets.map(({ code, kind }) => ({ code, kind })),
      occurredAt: now,
    });
    return tickets;
  }

  // What a repository must write when it saves this sale.
  changes(): { added: OrderView[]; changed: OrderView[]; events: TicketsIssued[] } {
    return { added: [...this.#added], changed: [...this.#changed], events: [...this.#events] };
  }

Notice three things:

  • The method now refuses an order that is not paid. Before, nothing stopped a caller from issuing tickets for a held order. Now no event can say that a held order got tickets.
  • The event keeps the code and the kind of each ticket, not the price. Door needs the codes, and the price stays in Sales.
  • now comes in as an argument, like the clock in every other method of the sale.

In src/sales/domain/sale.test.ts, the test “a paid order gets one ticket per seat” calls the new name (an excerpt):

  const tickets = sale.issueTickets("a", () => "CODE", minutesLater(1));

Add a test at the end of the same file:

test("issuing the tickets of a paid order records TicketsIssued", () => {
  const sale = Sale.restore(1, 3, twelveDollars, 0, []);
  sale.hold("a", ana, standard(2), tenOClock);
  assert.throws(() => sale.issueTickets("a", () => "CODE", tenOClock), /not paid/);
  sale.pay("a", minutesLater(1));
  let next = 0;
  sale.issueTickets("a", () => `CODE${++next}`, minutesLater(1));
  assert.deepEqual(sale.changes().events, [{
    type: "TicketsIssued", showId: 1, orderToken: "a",
    tickets: [{ code: "CODE1", kind: "standard" }, { code: "CODE2", kind: "standard" }],
    occurredAt: minutesLater(1),
  }]);
});

Run the domain tests, then the type check:

node --test src/sales/domain/
npm run check

What you should see (two excerpts):

✔ issuing the tickets of a paid order records TicketsIssued (0.72457ms)
ℹ tests 16
ℹ suites 0
ℹ pass 16
ℹ fail 0
src/sales/application/sales.ts(90,40): error TS2339: Property 'tickets' does not exist on type 'Sale'.

The 16 domain tests pass with no database. tsc names the one caller of the old method. Before you fix it, rename the port that saves tickets, because issueTickets would otherwise mean two things in one function. In src/sales/application/sales.ts, the field of SalesTransaction becomes saveTickets, and the work inside markOrderPaid changes (two excerpts):

  saveTickets(orderToken: string, tickets: NewTicket[]): Promise<void>;
      const outcome = await inTransaction(async ({ sales, saveTickets }) => {
        const sale = await sales.saleOfOrder(token);
        if (sale === undefined) {
          return "no such order";
        }
        const now = deps.now();
        const outcome = sale.pay(token, now);
        // Issuing the tickets records TicketsIssued, so it comes before save.
        const tickets = outcome === "paid" ? sale.issueTickets(token, newTicketCode, now) : [];
        await sales.save(sale);
        if (outcome !== "paid") {
          return outcome;
        }
        await deps.queueConfirmation(payment);
        await saveTickets(token, tickets);
        const totalCents = sale.order(token).details.totalCents;
        if (payment.amountCents !== totalCents) {
          throw new Error(`Order ${token}: paid ${payment.amountCents} cents, expected ${totalCents}.`);
        }
        return outcome;
      });

save writes what the sale lists, so the event must be recorded before save. queueConfirmation and the amount check stay where they were for now. In src/sales/db/tickets.ts, rename the function issueTickets to insertTickets, the name of the SQL it runs. The two adapters follow (an excerpt of src/sales/db/transaction.ts, then one of src/sales/application/in-memory.ts):

import { insertTickets } from "./tickets.ts";
      saveTickets: (orderToken, tickets) => insertTickets(client, orderToken, tickets),
      saveTickets: async (orderToken, newTickets) => {

Run npm run check (no errors) and npm test. Of 46 tests, 45 pass, and Nina’s still fails, because the event is recorded but nothing saves it yet.

To see what readonly buys, add this test at the end of src/sales/domain/sale.test.ts, and run npm run check:

test("an event cannot be changed", () => {
  const sale = Sale.restore(1, 3, twelveDollars, 0, []);
  sale.hold("a", ana, standard(1), tenOClock);
  sale.pay("a", tenOClock);
  const [event] = sale.changes().events;
  event!.orderToken = "b";
  event!.tickets.push({ code: "FREE", kind: "vip" });
});

What you should see:

src/sales/domain/sale.test.ts(86,10): error TS2540: Cannot assign to 'orderToken' because it is a read-only property.
src/sales/domain/sale.test.ts(87,18): error TS2339: Property 'push' does not exist on type 'readonly { readonly code: string; readonly kind: TicketKind; }[]'.

A handler that receives the event cannot change it in place, not even its list of tickets. readonly is checked only by tsc, so this holds for TypeScript code, not for the JSON the event becomes later. Delete the test, and commit:

git add -A
git commit -m "Let the sale record TicketsIssued"

Step 2: Write the events to an outbox in the same transaction

Why: the event exists only in memory. It must reach the database on the transaction’s client, so that it commits with the sale or not at all.

What to do: save this migration as migrations/020_create_outbox.sql:

-- Year 3: the transactional outbox. A context writes its domain events here,
-- in the same transaction as its own changes, and the worker moves them into
-- jobs. Like jobs, it belongs to no context and stays in public.
CREATE TABLE outbox (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  type text NOT NULL,
  payload jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

Save this as src/platform/db/outbox.ts, and export it from src/platform/index.ts with export { writeToOutbox } from "./db/outbox.ts";:

import type pg from "pg";

// Writes a domain event to the outbox on the caller's client, so the event
// commits or rolls back with the caller's transaction.
export async function writeToOutbox(client: pg.PoolClient, type: string, payload: object): Promise<void> {
  await client.query("INSERT INTO outbox (type, payload) VALUES ($1, $2)", [type, payload]);
}

The function asks for the caller’s client instead of using the pool, which is the whole difference from enqueue. In src/sales/db/sale-repository.ts, add import { writeToOutbox } from "#platform";, and let save write the events after the orders (an excerpt):

      const { added, changed, events } = sale.changes();
      for (const order of added) {
        await insertOrder(order, sale.showId, client);
      }
      for (const order of changed) {
        await saveOrderState(order, client);
      }
      // On the same client, so an event commits only with the sale.
      for (const event of events) {
        await writeToOutbox(client, event.type, event);
      }

Now remove the old path. In src/sales/application/sales.ts, delete the line queueConfirmation(payment: Payment): Promise<void>; from SalesDeps, and the line await deps.queueConfirmation(payment); from markOrderPaid. In src/sales/application/sales.test.ts, delete queueConfirmation: async () => {},. src/sales/wiring.ts loses the port and its import of enqueue:

import { createPayment } from "#platform";
import { salesService } from "./application/sales.ts";
import { savePayment } from "./db/orders.ts";
import { withTransaction } from "./db/transaction.ts";

// The composition root of Sales: the one file that picks an adapter for each
// port of the application services.
export const sales = salesService({
  withTransaction,
  async startPayment(orderToken, amountCents) {
    const payment = await createPayment(amountCents, orderToken);
    await savePayment(orderToken, payment.id, payment.payUrl);
    return payment.payUrl;
  },
  now: () => new Date(),
});

The in-memory adapter must save the events too, or the application tests would never see one. In src/sales/application/in-memory.ts, import the type, keep a list, fill it in save, and return it (four excerpts):

import type { TicketsIssued } from "../domain/events.ts";
  const events: TicketsIssued[] = [];
          const { added, changed, events: recorded } = sale.changes();
          for (const order of added) {
            orders.push({ showId: sale.showId, token: order.token, details: order.details, state: order.state });
          }
          for (const order of changed) {
            orders.find((one) => one.token === order.token)!.state = order.state;
          }
          events.push(...recorded);
  return { withTransaction, orders, tickets, events };

Add a test to src/sales/application/sales.test.ts, before “a failed payment gives the seats to the next buyer”:

test("a payment saves TicketsIssued with the sale", async () => {
  const { store, service } = salesOnShowOne();
  await service.holdSeats(1, ana, [{ kind: "standard", quantity: 2 }]);
  const token = store.orders[0]!.token;
  await service.markOrderPaid({ orderToken: token, paymentId: "pay_1", amountCents: parseCents(2550) });
  assert.deepEqual(store.events.map((event) => [event.type, event.orderToken, event.tickets.length]), [["TicketsIssued", token, 2]]);
});

Last, app.test.ts empties every table before it runs, and the outbox joins them. In the TRUNCATE at the top of the file, change jobs RESTART IDENTITY to jobs, outbox RESTART IDENTITY.

Pause and predict: nothing queues the email job now. Which tests fail, and does Nina’s pass?

Run npm run check and npm test.

What you should see: no tsc errors, and two failures (an excerpt):

Applied 020_create_outbox.sql
...
✖ a paid webhook issues the tickets, and the worker emails them (21.309461ms)
✖ the email for four tickets lists no booking fee (26.056865ms)
ℹ tests 47
ℹ pass 45
ℹ fail 2
...
  false !== true
...
  TypeError [Error]: Cannot read properties of undefined (reading 'text')

Nina’s test passes, because no job reaches the queue for a payment that rolls back. But none reaches it for a payment that commits either. The first failure is runOneJob() finding no job, and the second is emails.at(-1) finding no email. The events are waiting in the outbox. Look at them in the test database:

docker exec tinytickets-db psql -U postgres -d tinytickets_test -c "SELECT id, type, payload->>'orderToken' AS order_token FROM outbox ORDER BY id"

What you should see (from one run; your tokens will differ):

 id |     type      |           order_token            
----+---------------+----------------------------------
  1 | TicketsIssued | c07aa2c77f4712ee6e7ee50dd92558dd
  2 | TicketsIssued | a1b8baa1979ac21f0b5efa7d31e3ac4e
  3 | TicketsIssued | 18c114d99df3f3a0cd0356cc69f09045
  5 | TicketsIssued | 2fd7c7fc048dd2f15f59321af8dcd479
(4 rows)

Four payments committed, and there is no id 4. That id went to Bea’s payment. Her transaction wrote the event, failed the amount check after it, and rolled back. Her event went with it, and the sequence did not give the id back. Commit:

git add -A
git commit -m "Write the sale's events to an outbox in the same transaction"

Step 3: Relay the outbox into the job queue

Why: the events must become jobs. The obvious relay remembers the last id it read and asks for higher ones next time, and it loses events. Save this as try-cursor.ts in the project folder to see how:

import pg from "pg";

// Two transactions, A and B, each write one event. A writes first and
// commits last. A relay remembers the last id it has seen.
const a = new pg.Client();
const b = new pg.Client();
const relay = new pg.Client();
await Promise.all([a.connect(), b.connect(), relay.connect()]);

const write = "INSERT INTO outbox (type, payload) VALUES ('Try', '{}') RETURNING id";
const readAfter = async (lastSeen: number) => {
  const result = await relay.query("SELECT id FROM outbox WHERE type = 'Try' AND id > $1 ORDER BY id", [lastSeen]);
  return result.rows.map((row) => Number(row.id));
};

await a.query("BEGIN");
const idA = (await a.query(write)).rows[0].id;
await b.query("BEGIN");
const idB = (await b.query(write)).rows[0].id;
console.log(`A wrote id ${idA}, B wrote id ${idB}.`);

await b.query("COMMIT");
const first = await readAfter(0);
const lastSeen = Math.max(...first);
console.log(`B committed. The relay reads after 0: [${first}]. It remembers ${lastSeen}.`);

await a.query("COMMIT");
console.log(`A committed. The relay reads after ${lastSeen}: [${await readAfter(lastSeen)}].`);

await relay.query("DELETE FROM outbox WHERE type = 'Try'");
await Promise.all([a.end(), b.end(), relay.end()]);

Pause and predict: A’s event has the lower id. Which read returns it?

node --env-file=.env.test try-cursor.ts

What you should see (one run; your ids depend on what the tests left):

A wrote id 7, B wrote id 8.
B committed. The relay reads after 0: [8]. It remembers 8.
A committed. The relay reads after 8: [].

Neither read returns id 7. When the relay first looked, A had not committed, so its row was invisible. When A committed, the relay was already past it.

The id order is the order of the inserts, and the commit order can differ. So the relay below takes every row that is still in the table and deletes what it takes. Delete the file:

rm try-cursor.ts

What to do: add the relay to src/platform/db/outbox.ts, with import { pool } from "./pool.ts"; under the first import, and export it from src/platform/index.ts as export { relayEvents, writeToOutbox } from "./db/outbox.ts"; (an excerpt):

// Moves up to 100 events from the outbox into the job queue, one job for each
// subscriber of the event's type, in one transaction. Rows that another relay
// has locked are skipped. Returns the number of events moved.
export async function relayEvents(subscribers: Record<string, string[]>): Promise<number> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const events = await client.query<{ type: string; payload: object }>(
      `DELETE FROM outbox WHERE id IN (
         SELECT id FROM outbox ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED)
       RETURNING type, payload`,
    );
    for (const event of events.rows) {
      for (const kind of subscribers[event.type] ?? []) {
        await client.query("INSERT INTO jobs (kind, payload) VALUES ($1, $2)", [kind, event.payload]);
      }
    }
    await client.query("COMMIT");
    return events.rows.length;
  } catch (error) {
    await client.query("ROLLBACK");
    throw error;
  } finally {
    client.release();
  }
}

One statement claims the rows and deletes them. If anything after it fails, the ROLLBACK puts the rows back, and the next pass tries again. The relay takes the subscribers as an argument, so src/platform/ does not know who listens either. An event whose type has no subscriber is deleted with no job, a cost listed under “When an outbox is too much”.

The worker owns the list of subscribers. In worker.ts, import relayEvents from #platform, add the list above handlers, and relay on every pass of the loop (two excerpts):

// The jobs each domain event starts, one for each subscriber. Sales records
// TicketsIssued and does not know who listens.
export const subscribers: Record<string, string[]> = {
  TicketsIssued: ["send_confirmation"],
};
  while (!stopping) {
    const relayed = await relayEvents(subscribers);
    if (!(await runOneJob()) && relayed === 0) {
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }

The email job now gets the event, not the payment. In src/sales/jobs/send-confirmation.ts, delete the import of Payment, and change the start of the function (an excerpt):

// Emails the tickets of a paid order. The job comes from the event
// TicketsIssued, so it exists only for a payment whose transaction committed.
// It returns early when the email was already sent, or for an order that is
// not paid (a job queued by the old code).
export async function sendConfirmation(event: { orderToken: string }): Promise<void> {
  const order = await findOrderByToken(event.orderToken);
  if (order === undefined || order.status !== "paid" || order.confirmation_sent_at !== null) {
    return;
  }

The status check is not the fix, as the problem section showed. It is there for the jobs the old code queued before the deploy, some of which may belong to a payment that rolled back. The email’s “Paid” line now reads the order’s row, so it becomes this (an excerpt), and OrderRow in src/sales/db/orders.ts gains the line payment_id: string | null; after confirmation_sent_at:

Paid: ${formatDollars(order.total_cents)} (payment ${order.payment_id})

The amount check makes the total and the amount paid equal for every committed payment. Jobs queued before the deploy still carry a payment, so a migration translates them, as Module 4 did for its jobs. Save this as migrations/021_send_confirmation_by_order.sql:

-- Year 3: the email job now gets the event TicketsIssued and reads the order
-- by its token. Jobs queued by the old code before the deploy keep working.
UPDATE jobs
SET payload = jsonb_build_object('orderToken', payload #> '{payment,orderToken}')
WHERE kind = 'send_confirmation' AND payload ? 'payment';

The tests must now do what the worker does. In app.test.ts, import relayEvents from #platform and subscribers from ./worker.ts, and add this helper after buyer:

// What the worker does when it comes round: it moves the events into jobs,
// then runs every job that is due.
async function runWorker(): Promise<void> {
  await relayEvents(subscribers);
  while (await runOneJob()) {}
}

Replace assert.equal(await runOneJob(), true); in “a paid webhook issues the tickets, and the worker emails them” with await runWorker();. Do the same with the two lines await runOneJob(); and with Nina’s while (await runOneJob()) {}. Then run npm run check and npm test.

What you should see: no tsc errors, and every test passes (an excerpt):

Applied 021_send_confirmation_by_order.sql
...
✔ a paid webhook issues the tickets, and the worker emails them (38.768509ms)
...
✔ a payment whose transaction rolls back sends no email (40.630685ms)
...
ℹ tests 47
ℹ suites 0
ℹ pass 47
ℹ fail 0

The paid payment’s email goes out, and Bea’s does not. In the outbox, each row now looks like this before the relay takes it (one payload from one run):

{"type": "TicketsIssued", "showId": 5, "tickets": [{"code": "2FE808EB", "kind": "standard"}, {"code": "ED409B29", "kind": "standard"}], "occurredAt": "2026-11-19T19:49:01.955Z", "orderToken": "1b42966598ed67452ecd22856632f387"}

occurredAt is a string now. JSON has no date type, so whoever reads the payload gets text, whatever the TypeScript type said. Commit:

git add -A
git commit -m "Relay the outbox into the job queue"

Step 4: Give Door its own list of tickets

Why: Door reads Sales’ tables on every scan and repeats Sales’ rule about paid orders. TicketsIssued already carries what Door needs.

What to do: save this as migrations/022_keep_tickets_at_door.sql:

-- Year 3: Door keeps its own list of the tickets it lets in (see "Ticket" in
-- GLOSSARY.md), filled from Sales' event TicketsIssued. A scan no longer reads
-- Sales' tables.
CREATE TABLE door.tickets (
  code text PRIMARY KEY,
  show_id integer NOT NULL,
  kind text NOT NULL
);
-- The tickets sold before this migration, copied once from Sales.
INSERT INTO door.tickets (code, show_id, kind)
SELECT tickets.code, tickets.show_id, tickets.kind
FROM sales.tickets JOIN sales.orders ON orders.id = tickets.order_id
WHERE orders.status = 'paid' AND tickets.code IS NOT NULL;

The copy at the end reads Sales’ schema once, at deploy time, so that tickets sold before the deploy still get people in. Tickets from before migration 010 have no code, so they are left out. Save this as src/door/db/tickets.ts:

import { pool } from "#platform";

// A ticket at the Door: a code that lets one person in to one show.
export type DoorTicket = { code: string; show_id: number; kind: string };

export async function findTicket(code: string): Promise<DoorTicket | undefined> {
  const result = await pool.query<DoorTicket>("SELECT code, show_id, kind FROM door.tickets WHERE code = $1", [code]);
  return result.rows[0];
}

// Adds the tickets of one order. A code that is already there is skipped, so
// adding the same tickets twice changes nothing.
export async function addTickets(showId: number, tickets: { code: string; kind: string }[]): Promise<void> {
  for (const ticket of tickets) {
    await pool.query(
      "INSERT INTO door.tickets (code, show_id, kind) VALUES ($1, $2, $3) ON CONFLICT (code) DO NOTHING",
      [ticket.code, showId, ticket.kind],
    );
  }
}

In src/door/routes/door.ts, replace the import of findTicketByCode from #sales with import { findTicket } from "../db/tickets.ts";. Then call findTicket(code) instead, and delete the check that the order is paid (an excerpt of the route after the change):

  const ticket = await findTicket(code);
  const show = ticket === undefined ? undefined : await findShow(ticket.show_id);
  if (ticket === undefined || show === undefined || show.organizer_id !== user.organizer_id) {
    response.status(404).send(doorPage(`No ticket ${code} for your shows.`));
    return;
  }
  if (!(await insertScan(code, user.id))) {

Sales no longer needs to answer the door. Delete TicketAtDoor, findTicketByCode and the import of OrderStatus from src/sales/db/tickets.ts, and change the first export of src/sales/index.ts to export { listSoldTicketPrices } from "./db/tickets.ts";. In app.test.ts, add door.tickets after door.scans in the TRUNCATE.

Pause and predict: the door now reads door.tickets, and nothing fills it yet. Which test fails, and with what status?

Run npm run check and npm test.

What you should see: no tsc errors, and one failure (an excerpt):

✖ the door admits a ticket once (54.283722ms)
ℹ tests 47
ℹ pass 46
ℹ fail 1
...
  404 !== 200

The migration copied the old tickets, but the test empties the table first, and nobody tells Door about new tickets. Save Door’s handler as src/door/jobs/add-tickets.ts:

import { addTickets } from "../db/tickets.ts";

// The fields Door reads from Sales' event TicketsIssued. Door writes them
// down itself and imports nothing from Sales.
type TicketsIssued = { showId: number; tickets: { code: string; kind: string }[] };

// Whenever Sales issues tickets, Door adds them to the tickets it lets in.
export async function addTicketsAtDoor(event: TicketsIssued): Promise<void> {
  await addTickets(event.showId, event.tickets);
}

Door’s type has the same name as Sales’ type and a smaller shape. It is Door’s reading of the published language, so it imports nothing, and the boundary test from Module 3 stays green. Export it from src/door/index.ts with export { addTicketsAtDoor } from "./jobs/add-tickets.ts";. In worker.ts, import it from #door, subscribe it, and give its job kind a handler (two excerpts):

  TicketsIssued: ["send_confirmation", "add_tickets_at_door"],
  add_tickets_at_door: addTicketsAtDoor,

Run npm test again: all 47 tests pass. Sales did not change in this half of the step. A second context now reacts to its event, and the only new line outside Door is in the worker’s list.

Now write Leo’s question as a test. Add it at the end of app.test.ts:

// Leo's question: can a buyer who just paid get in at once?
test("the door lets a new ticket in once the worker has run", async () => {
  const cookie = await logIn();
  const show = await pool.query<{ id: number }>(
    `INSERT INTO shows.shows (organizer_id, name, show_date, doors_open, place, seats, price_cents)
     VALUES (1, 'Door Show', current_date + 30, '19:00', 'Test Club', 10, 1200)
     RETURNING id`,
  );
  await post(`/shows/${show.rows[0]!.id}/hold`, { ...buyer, standard: "1" });
  const order = await pool.query("SELECT token, payment_id FROM sales.orders ORDER BY id DESC LIMIT 1");
  const { token, payment_id } = order.rows[0];
  await webhook({
    id: "evt_10",
    type: "payment.succeeded",
    data: { payment_id, amount_cents: 1350, currency: "usd", metadata: { order_ref: token } },
  });
  const ticket = await pool.query("SELECT code FROM sales.tickets ORDER BY id DESC LIMIT 1");
  const code = ticket.rows[0].code;
  const beforeWorker = await post("/door/tickets", { code }, cookie);
  await runWorker();
  const afterWorker = await post("/door/tickets", { code }, cookie);
  assert.deepEqual([beforeWorker.status, afterWorker.status], [404, 200]);
});

What you should see (an excerpt):

✔ the door lets a new ticket in once the worker has run (79.305663ms)
ℹ tests 48
ℹ suites 0
ℹ pass 48
ℹ fail 0

The payment had committed, and the code was in sales.tickets, but the door answered 404 until the worker ran. That is the eventual consistency from the concepts, written down as a test. Commit:

git add -A
git commit -m "Give Door its own list of tickets"

Step 5: Move the amount check into the sale

Why: Module 8 left one comparison in the application service, after the tickets. Whether a payment matches the order is Leo’s rule, and the sale can refuse a wrong amount before it changes anything.

What to do: in src/sales/domain/sale.ts, give pay the amount (an excerpt):

  // Paying keeps an order's seats after its hold would have run out, so a
  // payment changes the sale, and goes through it. A payment of another
  // amount than the order's total is refused before anything changes.
  pay(token: string, amountCents: Cents, now: Date): PaymentOutcome {
    const order = this.#find(token);
    if (amountCents !== order.details.totalCents) {
      throw new Error(`Order ${token}: paid ${amountCents} cents, expected ${order.details.totalCents}.`);
    }
    this.#changed.add(order);
    return order.pay(now);
  }

Run npm run check.

What you should see:

src/sales/application/sales.ts(84,30): error TS2554: Expected 3 arguments, but got 2.
src/sales/domain/sale.test.ts(32,21): error TS2554: Expected 3 arguments, but got 2.
src/sales/domain/sale.test.ts(52,8): error TS2554: Expected 3 arguments, but got 2.
src/sales/domain/sale.test.ts(71,8): error TS2554: Expected 3 arguments, but got 2.

tsc lists every caller. In markOrderPaid, the work inside the transaction becomes this (an excerpt):

        const now = deps.now();
        const outcome = sale.pay(token, payment.amountCents, now);
        // Issuing the tickets records TicketsIssued, so it comes before save.
        const tickets = outcome === "paid" ? sale.issueTickets(token, newTicketCode, now) : [];
        await sales.save(sale);
        await saveTickets(token, tickets);
        return outcome;

The command is back to Module 8’s shape: load, call the sale, save. In src/sales/domain/sale.test.ts, pass each order’s total. On line 32, sale.pay("a", minutesLater(5)) becomes sale.pay("a", parseCents(2550), minutesLater(5)). Line 52 passes parseCents(4250) for two standard tickets and one VIP, and line 71 passes parseCents(2550). Then add a test at the end:

test("a payment of another amount than the total is refused, and changes nothing", () => {
  const sale = Sale.restore(1, 2, twelveDollars, 0, []);
  sale.hold("a", ana, standard(2), tenOClock);
  assert.throws(() => sale.pay("a", parseCents(2000), minutesLater(1)), /paid 2000 cents, expected 2550/);
  assert.deepEqual(sale.changes().changed, []);
});

Run the domain tests, then all of them:

node --test src/sales/domain/
npm test

What you should see: 17 domain tests pass, and then all 49 (an excerpt of the second run):

✔ a payment whose transaction rolls back sends no email (25.14394ms)
...
ℹ tests 49
ℹ suites 0
ℹ pass 49
ℹ fail 0

Nina’s test still passes, and for a stronger reason now. Bea’s payment fails before anything is written, and the outbox would have rolled back its event anyway. Commit:

git add -A
git commit -m "Move the amount check into the sale"

Step 6: Write each payout before its transfer

Why: pay_organizers is a job, so it can run twice too. In src/payouts/jobs/pay-organizers.ts, it sends the transfer first and writes the payout’s row after. A crash between the two leaves no row, and the next run pays the organizer again.

What to do: a crash is hard to cause in a test, but two runs at the same time open the same gap. Add this test at the end of app.test.ts, and import payOrganizers from #payouts and transfers from ./fakes.ts:

// A crash between the transfer and the payout's row is hard to cause in a
// test. Two runs at once open the same gap. Holds do not check the show's
// date yet, so the test can sell two tickets for a show that ended.
test("two payout runs at once pay the organizer once", async () => {
  const show = await pool.query<{ id: number }>(
    `INSERT INTO shows.shows (organizer_id, name, show_date, doors_open, place, seats, price_cents)
     VALUES (1, 'Ended Show', current_date - 6, '19:00', 'Test Club', 10, 1200)
     RETURNING id`,
  );
  await post(`/shows/${show.rows[0]!.id}/hold`, { ...buyer, standard: "2" });
  const order = await pool.query("SELECT token, payment_id FROM sales.orders ORDER BY id DESC LIMIT 1");
  const { token, payment_id } = order.rows[0];
  await webhook({
    id: "evt_11",
    type: "payment.succeeded",
    data: { payment_id, amount_cents: 2550, currency: "usd", metadata: { order_ref: token } },
  });
  const sent = transfers.length;
  await Promise.allSettled([payOrganizers(), payOrganizers()]);
  assert.deepEqual(transfers.slice(sent).map((transfer) => transfer.amount_cents), [2280]);
});

Two $12 tickets make 2400 cents, and the site keeps 5% of each, so Leo’s payout is 2280 cents. Run npm test.

What you should see (an excerpt):

pay: transfer 2280 cents to acct_leo
pay: transfer 2280 cents to acct_leo
Paid 2280 cents for show 5.
✖ two payout runs at once pay the organizer once (21.094587ms)
...
    [
      2280,
  +   2280
    ]

Both runs listed the show as unpaid, and both sent the money. Only one row went in, because show_id is unique. The other run failed on that key after its transfer had left. Now fix it. Save this as migrations/023_write_payout_before_transfer.sql:

-- Year 3: a payout's row is written before its transfer is sent, so a second
-- run of the payout job finds it and sends nothing. transfer_id stays empty
-- until the payment provider answers.
ALTER TABLE payouts.payouts ALTER COLUMN transfer_id DROP NOT NULL;

In src/payouts/db/payouts.ts, replace insertPayout with these two functions (an excerpt):

// Writes the payout of one show before its transfer is sent. Returns false
// when the show already has a payout, so the caller sends nothing.
export async function insertPayout(p: {
  organizerId: number; showId: number; grossCents: number; feeCents: number; amountCents: number;
}): Promise<boolean> {
  const result = await pool.query(
    `INSERT INTO payouts.payouts (organizer_id, show_id, gross_cents, fee_cents, amount_cents)
     VALUES ($1, $2, $3, $4, $5)
     ON CONFLICT (show_id) DO NOTHING`,
    [p.organizerId, p.showId, p.grossCents, p.feeCents, p.amountCents],
  );
  return result.rowCount === 1;
}

export async function saveTransferId(showId: number, transferId: string): Promise<void> {
  await pool.query("UPDATE payouts.payouts SET transfer_id = $2 WHERE show_id = $1", [showId, transferId]);
}

Then src/payouts/jobs/pay-organizers.ts writes the row first:

import { insertPayout, listShowsToPay, saveTransferId } from "../db/payouts.ts";
import { sendTransfer } from "#platform";
import { listSoldTicketPrices } from "#sales";
import { payoutFor } from "../services/payouts.ts";

export async function payOrganizers(): Promise<void> {
  for (const show of await listShowsToPay()) {
    const prices = await listSoldTicketPrices(show.show_id);
    const payout = payoutFor(prices);
    // The row first: a second run, at the same time or after a crash, finds
    // it and sends nothing. If the transfer fails, the row stays without a
    // transfer_id, and a person checks it.
    if (!(await insertPayout({ organizerId: show.organizer_id, showId: show.show_id, ...payout }))) {
      continue;
    }
    const transferId = await sendTransfer(show.payout_account, payout.amountCents);
    await saveTransferId(show.show_id, transferId);
    console.log(`Paid ${payout.amountCents} cents for show ${show.show_id}.`);
  }
}

Run npm run check and npm test.

What you should see: no tsc errors, one transfer, and all 50 tests pass (an excerpt):

Applied 023_write_payout_before_transfer.sql
...
pay: transfer 2280 cents to acct_leo
Paid 2280 cents for show 5.
...
ℹ tests 50
ℹ suites 0
ℹ pass 50
ℹ fail 0

The unique key on show_id decides which run pays, before any money moves. The cost is the other side of the trade. When the provider fails, or the worker crashes before saveTransferId, the row stays without a transfer_id. No later run retries it, so Leo is paid late until a person checks the row, but never twice. Commit:

git add -A
git commit -m "Write each payout before its transfer"

Step 7: Update the glossary, the map, the README and the code figure

Why: the glossary still says Door asks Sales for tickets, and nothing names the new event.

What to do: in GLOSSARY.md, add this entry before “Ticket”:

## Tickets issued

The event that happens when a paid order gets its tickets: one per seat,
each with a code. The buyer's email and the door's list follow from it.

- Context: Sales records it; Sales and Door react to it.
- Code: type `TicketsIssued` (`src/sales/domain/events.ts`), recorded by
  `Sale.issueTickets` and saved with the sale in table `outbox`. The worker
  turns it into the jobs `send_confirmation` (Sales) and
  `add_tickets_at_door` (Door); see `subscribers` in `worker.ts`.

In “Ticket”, replace the line for the Door with this:

- At the Door: a code that lets one person in, once. Door keeps its own
  list in table `door.tickets` (`src/door/db/tickets.ts`), filled from the
  event "Tickets issued" when the worker next comes round, not at the
  moment of the payment.

Two more entries change by a few words. In “Sale”, the method tickets is now issueTickets. In “Payout”, the code line becomes this:

- Code: table `payouts.payouts`, `src/payouts/jobs/pay-organizers.ts`. The
  row is written before the transfer is sent, so a show is never paid
  twice; a row with no `transfer_id` is a transfer a person must check.

In CONTEXT-MAP.md, add a line to the notation, and replace the entry for Door and Sales (two excerpts):

    A --> B               A's domain event reaches B through the outbox
                          and a job; B is downstream
    {Sales}   --> {Door}      Published language: the event
                              TicketsIssued, as JSON. The worker turns it
                              into the job add_tickets_at_door. Door writes
                              down the fields it reads (showId, tickets)
                              and imports nothing from Sales; Sales keeps
                              those fields.

The map’s first check command now prints no import from Door to Sales:

grep -roE 'from "#(shows|sales|door|payouts)"' src | awk -F'[/"]' '{print $2, "..>", $(NF-1)}' | sort | uniq -c
   1 door ..> #shows
   1 payouts ..> #sales
   2 payouts ..> #shows
   5 sales ..> #shows

In README.md, make three small edits. Write “events” before “emails” in the comment of npm run worker, add “the outbox” before “the job queue” in the line for src/platform/, and change “001 to 019” to “001 to 023”. Then add this paragraph after the one about in-memory.ts:

When the sale issues tickets, it records the event `TicketsIssued`, and the
repository writes it to the table `outbox` in the same transaction as the
sale. The worker moves each event into one job per subscriber
(`subscribers` in `worker.ts`): Sales emails the buyer, and Door adds the
codes to its own list, `door.tickets`. So a new ticket reaches the door when
the worker next comes round, not at the moment of the payment. A job can run
twice, and every handler gives the same result when it does.

Figure 6 is the code figure with this module’s changes marked.

{Door}             {Sales} <.......... {Payouts}
   :                  :                    :
   :                  v                    :
   :.............> {Shows} <...............:

{Sales} --> {Door}   the event TicketsIssued, through the outbox NEW

{Shows}, {Sales}, {Payouts} ..> money/   the shared kernel (#money)

Inside {Sales}:  routes/ ..> wiring.ts ..> application/ ..> domain/
                 db/, jobs/, acl/ ..> application/; db/, jobs/ ..> domain/
                 domain/       Sale, Order, pricing, the port SaleRepository,
                               and the event TicketsIssued NEW
                 application/  salesService; ports WithTransaction,
                               startPayment (queueConfirmation is gone NEW)
                 db/           the PostgreSQL adapters; save writes the
                               sale's events to the outbox NEW
                 routes/ ..> acl/ ACL ..> [Payment provider]
Inside {Door}:   routes/ ..> db/tickets.ts: its own list NEW
                 jobs/add-tickets.ts: TicketsIssued as Door reads it NEW

platform/   the pool, the outbox and its relay NEW, the job queue, settings,
            page layout, login, email, the payment provider's client, the
            organizer dashboard. Every context ..> platform/.
worker.ts   subscribers: TicketsIssued --> send_confirmation,
            add_tickets_at_door NEW

Legend so far
{Name}      a bounded context (Module 3)
A ..> B     A depends on B in code (an import); for an outside service, on
            its API (Module 3, Module 4)
A --> B     A's domain event reaches B through the outbox and a job; no
            import (Module 9)
ACL         an anticorruption layer, inside the context it protects (Module 4)
money/      a shared kernel: one folder of the model that several contexts
            import, changed only when they all agree (Module 5)

Figure 6: Door no longer imports Sales; it hears from Sales through an event.

Run the checks:

npm run check
npm test
npm run test:fast

What you should see: no tsc errors, 50 tests pass in npm test, and 29 in npm run test:fast. The end of the fast run, from one run:

✔ domain/ and application/ import nothing from the outside world (3.254161ms)
ℹ tests 29
ℹ suites 0
ℹ pass 29
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 272.931904

Commit:

git add -A
git commit -m "Describe the events and the outbox in the glossary, the map and the README"

How a payment works now

Follow Ana’s payment for one standard ticket, from the webhook to the door (Figure 7):

  1. The provider’s webhook reaches webhookRoutes, the anticorruption layer translates it, and the route calls sales.markOrderPaid(payment).
  2. inTransaction calls withTransaction, which takes one client and runs BEGIN. saleOfOrder loads the sale of Ana’s show on that client.
  3. sale.pay(token, amountCents, now) checks the amount against the order’s total, then pays the order. A wrong amount throws here, before anything changes.
  4. sale.issueTickets(token, newTicketCode, now) makes one ticket per seat and records TicketsIssued with the codes. No input or output happens in steps 3 and 4.
  5. sales.save(sale) moves the version, writes the order’s new state, and writes the event to outbox, all on the same client. saveTickets inserts the tickets. Then COMMIT makes the order, the tickets and the event visible together, or none of them.
  6. On its next pass, the worker’s relay deletes the outbox row with FOR UPDATE SKIP LOCKED and inserts two jobs, send_confirmation and add_tickets_at_door, in one transaction.
  7. The worker runs each job. sendConfirmation reads the paid order and its tickets and emails them, unless confirmation_sent_at says it already did. addTicketsAtDoor adds the codes to door.tickets, skipping any it already has.
  8. Ana scans her code at the door. Door finds it in its own list and lets her in.
(Ana) --> [Payment provider] --> [Web app] routes/webhooks.ts
            --> sales.markOrderPaid                    application/sales.ts
                  BEGIN                                db/transaction.ts
                  sale.pay, sale.issueTickets          domain/: no I/O
                  sales.save --> [[sales.sales]] version
                             --> [[sales.orders]] paid
                             --> [[outbox]] TicketsIssued   NEW
                  saveTickets --> [[sales.tickets]]
                  COMMIT
[Worker] relayEvents: [[outbox]] --> [[jobs]] x 2      one transaction NEW
[Worker] send_confirmation   --> [Email service]
[Worker] add_tickets_at_door --> [[door.tickets]]      NEW
(Ana) --> [Web app] /door/tickets --> [[door.tickets]], [[door.scans]]

Figure 7: everything up to COMMIT happens in one transaction; everything after it happens later and can happen twice.

If anything before the COMMIT fails, as Bea’s payment does in step 3, nothing after it happens. There is no event, so no jobs and no email. If the worker crashes in step 7, the job runs again, and the handlers give the same result.

Going deeper

Five ways to get an event out, and when each wins

Figure 8 puts this module’s choice next to the others.

Option How the event leaves When it wins Source
Handler before COMMIT in the same process and transaction a rule inside one context and one database that must hold at commit Dahan, 2009; Bogard, 2014
Handler after COMMIT in the same process, after the transaction an effect you can afford to lose in a crash Microsoft’s guide
Job row in the same transaction straight into jobs one reaction, in the same context Design Patterns Module 7
Outbox and a polling relay (this module) outbox, then jobs several contexts react, and the queue is in the same database Richardson
Outbox and log tailing PostgreSQL’s write-ahead log, read by a tool such as Debezium a message broker with many consumers Morling, 2019; Debezium docs

Figure 8: five ways to publish an event; only the first can send for a transaction that rolls back, and the second can lose an event in a crash.

Morling’s post describes the last option. A connector reads each outbox insert from the write-ahead log, PostgreSQL’s record of every change, and sends it to Kafka, a message broker. So the code may insert the row and delete it in the same transaction, and the table stays empty.

The Debezium Outbox Event Router expects a table with an aggregateid, which becomes the message key, so events of one aggregate stay in order. That option needs a broker, and System Design Module 6 is where TinyTickets gets one.

PostgreSQL’s LISTEN and NOTIFY could wake the relay instead of the one-second pause. The NOTIFY docs say a notification from a transaction is delivered only if it commits, and only to sessions that are listening at that moment, per the LISTEN docs. A relay that is restarting misses it. So NOTIFY can shorten the wait, and the outbox table stays the record of what is left to send.

The relay keeps no order. It takes the rows in id order, but ids follow the inserts, not the commits. The SELECT docs also warn that ORDER BY with a locking clause can return rows out of order under Read Committed.

Each order has one TicketsIssued, so TinyTickets needs no order today. Events that must be handled in order for one aggregate would need a version in the payload, which is the reason Debezium keys messages by aggregate.

What the authors meant, and where they disagree

On when to dispatch, Evans (Reference, p. 16) applies rules inside an aggregate at once and across aggregates asynchronously. Vernon (Part II, p. 9) has each subscriber run in its own transaction and change one aggregate, with redelivery and retries when it fails. Bogard (2014) accepts side effects of one command in one logical transaction across aggregates. Microsoft’s guide states the disagreement and says both can be right, depending on the business, the scale, and how much compensation code you are willing to write.

Microsoft’s guide also separates domain events, handled inside one context, from integration events, which cross contexts and are published only after the change is saved. In those words, TicketsIssued is both. Sales’ own email reacts to it, and Door reacts across a boundary. The outbox gives both the “only after it is saved” rule.

The guide also suggests storing events in extra tables in the original transaction, which is an outbox under another name.

On long flows, Vernon (Part II, p. 9) describes chains of domain events with retries, and compensation or a report when retries run out. In later comments under his 2009 post, Dahan says he now prefers modeling such flows as sagas. A 2017 comment under the same post points out that a static class like his DomainEvents is a problem with async and await. TinyTickets passes events through changes(), so there is no static class.

What changed recently

PostgreSQL 18, released on 2025-09-25, added a built-in uuidv7() function, which makes UUIDs that sort by time (see the release notes). It is a candidate for an event ID that must be unique across contexts and databases. In our reading, time-ordered is still not commit-ordered, so the trap in Step 3 applies to it too.

SKIP LOCKED is not new. It came with PostgreSQL 9.5, released in January 2016 (see the 9.5 release notes). Debezium’s current documentation is for its 3.x line, version 3.7 in November 2026.

When an outbox is too much

Skip the outbox when one reaction lives in the same context and the same database. Write the job row in the command’s own transaction, as Design Patterns Module 7 did. It is equally atomic, and it needs no relay. Skip the event too when the reaction is a rule that must hold at commit inside one aggregate; then it belongs in the aggregate’s method.

The outbox earns its cost only when Sales should not know who reacts. That cost is one more table and a relay in the worker. Every handler must be idempotent, and the reaction arrives later, which Leo and the buyers can see at the door.

A failure now spans two processes, the web app and the worker, so it takes longer to debug. An event type that nobody subscribes to disappears in the relay without a job. These limits are our judgment.

Check yourself

  1. Why did Bea’s email go out although her payment rolled back, and why would moving queueConfirmation to the last line of the transaction not be enough?
Answer

enqueue ran on pool.query, a second connection outside the transaction, so its insert committed at once and the rollback could not take it back. Queued last, it would still run on that connection: a failed COMMIT would leave the same job, and the worker could run it before the commit finished.

  1. What does Sale.issueTickets record, and why does markOrderPaid call it before sales.save?
Answer

It records TicketsIssued: the show’s ID, the order’s token, each ticket’s code and kind, and the time. The repository’s save writes what the sale lists in changes(), the events included, so an event recorded after save would never reach the outbox.

  1. Why does the relay delete the rows it moves, instead of remembering the last id it read?
Answer

Ids are handed out at insert, not at commit. In Step 3, A wrote id 7 and committed after B’s id 8, so a relay that had remembered 8 never read 7. Taking every row still in the table, with FOR UPDATE SKIP LOCKED, and deleting it in the same transaction as the new jobs, misses nothing and moves each event once.

  1. The job queue can run a job twice. What makes add_tickets_at_door and pay_organizers safe, and what does the payout’s choice cost?
Answer

add_tickets_at_door inserts with ON CONFLICT (code) DO NOTHING, so a second run adds nothing. pay_organizers writes the payout’s row before the transfer, and the unique show_id lets only one run send money. The cost is “at most once”. If the transfer fails or the worker crashes after the row, the row has no transfer_id, and a person must finish the payout.

  1. Leo asks whether a buyer who paid a moment ago can get in at once. What is the answer, and when would you write the job directly instead of using an outbox?
Answer

Not in the same moment. Door knows the ticket after the worker has relayed the event and run add_tickets_at_door, as the test in Step 4 shows with a 404 and then a 200. Write the job directly in the command’s transaction when only one thing reacts and it lives in the same context.

Exercise: run two relays at once

TinyTickets runs one worker, but nothing stops you from starting a second one. Write a test in app.test.ts that puts 150 events in the outbox, runs two relays at the same time, and checks that each event became its jobs exactly once. Undo it at the end.

Solution

TicketsIssued has two subscribers, so 150 events must make 300 jobs. Add the test at the end of app.test.ts:

test("two relays at once turn each event into its jobs once", async () => {
  await pool.query("TRUNCATE outbox, jobs");
  await pool.query("INSERT INTO outbox (type, payload) SELECT 'TicketsIssued', '{}' FROM generate_series(1, 150)");
  const moved = await Promise.all([relayEvents(subscribers), relayEvents(subscribers)]);
  const jobs = await pool.query("SELECT count(*)::int AS count FROM jobs");
  console.log("moved", moved, "jobs", jobs.rows[0].count);
  assert.equal(moved[0]! + moved[1]!, 150);
  assert.equal(jobs.rows[0].count, 300);
});

One run printed this (an excerpt; which relay takes 100 can change from run to run):

moved [ 100, 50 ] jobs 300
✔ two relays at once turn each event into its jobs once (194.743143ms)

Each relay locked at most 100 rows. The second one skipped the rows the first had locked and took the 50 after them, so no event was moved twice.

The test also passes with plain FOR UPDATE. Then the second relay waits for the first one’s locks, and the locking docs say a waiting SELECT FOR UPDATE gets no row when the row it waited for was deleted. So here SKIP LOCKED lets two relays work at the same time; it is not what keeps them correct. Undo the exercise:

git checkout app.test.ts

Cheat sheet

Cheat sheet

  • Domain event: an immutable fact in the past tense, with IDs and a time; the aggregate records it (Sale.issueTickets).
  • Not an emitter event: it is stored and handled later, maybe in another process.
  • Outbox: write the event on the transaction’s client (writeToOutbox), so it commits only with the change.
  • Relay: in one transaction, take rows with FOR UPDATE SKIP LOCKED, insert one job per subscriber, delete the rows.
  • Ids: never relay from the last id seen; ids follow inserts, not commits, and rollbacks leave gaps.
  • At least once: every handler must be idempotent; use a natural key or a table of processed IDs.
  • Outside effects: choose at least once (email) or at most once (money: write the row first).
  • Eventual consistency: another context sees the event when the worker comes round; ask how long the business accepts.
  • Skip it: one reaction in the same context; write the job in the same transaction.

Figure 9 is the whole module in one picture.

Record    sale.issueTickets       --> TicketsIssued in changes()
Save      sales.save              --> [[outbox]] on the transaction's client
Commit    COMMIT                  the order, the tickets, the event, or none
Relay     relayEvents (worker)    [[outbox]] --> [[jobs]], one per subscriber
Handle    send_confirmation       email; at least once
          add_tickets_at_door     ON CONFLICT DO NOTHING
          pay_organizers          row first; at most once

Figure 9: a fact is recorded in the domain, committed with the change, and handled later, once or more.

Sales now records what happened and does not know who reacts. The email and the door’s list both follow from TicketsIssued through the outbox and the job queue, and a rolled-back payment sends nothing. Next, Module 10 looks at Leo’s organizer dashboard, which joins across four aggregates and takes seconds to load on a sale day.

Sources