Skip to content

15 min read

Event-driven architecture: the outbox pattern

In one sentence: In an event-driven architecture, each part announces what has happened and the others react without anyone calling them. The danger is losing notices between two writes, one in the database and one in the queue, and the outbox pattern avoids it: the notice is saved in the same transaction as the change, and another process carries it to the queue afterwards.

What you will learn

  • Tell a command from an event, and explain what changes when parts react to events instead of being called.
  • Explain the dual write problem and cause it in the shop.
  • Read the shop’s outbox and its relayer, with FOR UPDATE SKIP LOCKED, and see that the email is no longer lost.
  • Decide when events help and when they only hide what is going on.

Before you start, read: 01-queues.md phase-5/08-transactions.md

Carmen pays order 21. The payment gateway notifies the shop, and the shop does two things: it turns the order into paid in PostgreSQL and it leaves the confirmation email in the Redis queue, as in lesson 1.

We told you back then: those are two writes in two places. If the API goes down between one and the other, or Redis fails, the order is paid and the email exists nowhere. Nobody misses it, because nobody knows it should exist.

And the gateway can’t fix it by retrying: the shop has already written down its event, and answers “repeated.” The email is lost for good. This lesson fixes it, and shows you what lies behind the fix: events.

The analogy

Think of an office’s outbox tray. When you sign a contract, you don’t run to the post office in the middle of the meeting: you file the contract and, in the same motion, put the customer’s letter in the tray.

Every few minutes the messenger comes by, picks up the letters, takes them to the post office and ticks each one off a list. If one day the messenger doesn’t show up, the letters wait. None gets lost, because the letter and the contract were saved together, on the same desk.

Where the analogy breaks down

  • The tray works because it sits on the same desk as the filing cabinet. In the shop, the outgoing table is in the same database as the order: if it were in Redis, the problem would come back.
  • If the messenger delivers the letters and falls ill before ticking them off, tomorrow’s messenger delivers them again. A repeated letter is noticeable; a repeated job is not, unless it carries a number that identifies it.
  • The email goes out a little after the payment, never at the same moment.

One command says what to do; an event says what happened

Section titled “One command says what to do; an event says what happened”

Compare these two messages:

  • “Send the confirmation email for order 21.”
  • “Order 21 is paid.”

The first is a command: it goes to someone in particular, who has to do it. The second is an event: it tells something that has already happened, and doesn’t say who cares about it or what to do with it.

Command Event
How it’s written In the imperative: “send,” “charge” In the past: “paid,” “created”
Who it goes to One party, who knows how to do it Whoever wants it: zero, one or many
Who decides what happens The sender Each party that receives it

The shop already uses both. The queue’s jobs are commands: “send this email.” The order changes from lesson 3 are events: the API publishes “order 21 has changed” in Redis and doesn’t know who follows it, nobody or ten browsers.

Publish and subscribe: whoever announces doesn’t know who listens

Section titled “Publish and subscribe: whoever announces doesn’t know who listens”

In an Event-driven architectureA way of organising a system in which each part announces what has happened (“order created”) and other parts react on their own. Whoever announces does not know who is listening, so reactions can be added without touching it.Go to definition, the parts of a system talk to each other mostly with events. Payments publishes “order paid,” and every part that has subscribed reacts on its own. It is lesson 3’s Pub/sub (publish and subscribe)Publish and subscribe: a system in which some programs publish messages on a channel and every program subscribed at that moment receives them instantly, not just one as in a queue. If nobody is listening, the message is lost. Whoever publishes does not know who is listening.Go to definition, used as a way of organizing the whole system.

  1. Payments → Message brokerevent: order 21 is paid
  2. Message broker → Emailorder 21 is paid
  3. Message broker → Deliveryorder 21 is paid
  4. Emailsends the confirmation
  5. Deliveryprepares the shipment
  • Adding a reaction doesn’t touch whoever announces. If billing subscribes tomorrow, the payments code doesn’t change.
  • A part that is down doesn’t stop the others. With email stopped, the payment is saved anyway, and the notice waits.

The broker is a program that receives messages and hands them out. The best known are Kafka, which keeps events for days and lets you read them again; RabbitMQ, which routes each message to queues by rules; and NATS, light and very fast. What the shop needs, with Redis, is not to lose messages along the way.

Two writes, two places: the gap from lesson 1

Section titled “Two writes, two places: the gap from lesson 1”

This is how the shop took payments up to step 40-zero-downtime:

  1. Payment gateway → APIPOST /v2/webhooks/payments (event evt_…)
  2. API → PostgreSQLwrite down the gateway's event
  3. API → PostgreSQLorder 21, paid (COMMIT)
  4. API → Redis (the queue)the email job
  5. APIthe API goes down here
  6. Redis (the queue)the job never arrives

This is the dual write problem: two systems that don’t share a TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition, so there is no way to save in both at once. Between one write and the other there is a gap, and sooner or later something falls into it: a deployment, an out-of-memory crash, a slow Redis.

Swapping the order doesn’t fix it. If you enqueue first and save the payment afterwards, a crash in between sends the email for an unpaid order. There are protocols for two systems to commit together (two-phase commit), but Redis doesn’t have them.

And there was another gap, inside PostgreSQL: the gateway’s event was saved on its own, outside the payment’s transaction, before paying. That is why the retry got “repeated.”

The outbox: the notice, in the same transaction

Section titled “The outbox: the notice, in the same transaction”

The solution is to not write in two places. The job is saved in PostgreSQL, in the same transaction as the payment: either both are saved, or neither. Afterwards, another process carries it to the queue. This is the Transactional outboxA trick for not losing announcements: the order and the announcement to send are saved in the same database transaction, in an outbox table, and another program sends them afterwards. Either both are saved or neither is.Go to definition.

The new table, in migration 011:

db/migrations/011-outbox-events.sql
CREATE TABLE outbox_events (
-- bigint, not integer: it's a table that only grows, one row for each job of each payment.
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
-- The job's type (payment-notice, confirmation-email), also inside data: here, in plain sight, to
-- count or search without opening the JSON.
type text NOT NULL,
-- The whole job, the way it will go to the queue. jsonb: JSON that PostgreSQL understands inside.
data jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
-- When the relayer put it in the queue. NULL: not yet.
sent_at timestamptz
);
-- A partial index (WHERE): only the unsent rows, the ones the relayer looks for every second. The
-- sent ones, which over time are almost all, aren't in it, so it stays small.
CREATE INDEX outbox_events_unsent ON outbox_events (created_at)
WHERE sent_at IS NULL;
  • data: the whole job, just as it will go to the queue, in a jsonb (in PostgreSQL)A PostgreSQL column type that stores a whole JSON document in each row, already broken down into a binary format so you can search inside it. It’s for data that doesn’t always have the same shape, without leaving your usual database. It’s often written JSONB.Go to definition column.
  • sent_at: when it reached the queue. While it is NULL, it is pending.
  • The partial Index (database)A separate, sorted list with the values of one or more columns of a table and where each row is. With it, the database finds a few rows without reading the whole table. In exchange, it takes up disk space and every write has to update it.Go to definition (WHERE sent_at IS NULL) keeps only the pending rows: the sent ones, almost all of them over time, don’t make it grow.

The table is named outbox_events after the pattern, although each row in the shop is a command: “send this email.”

The route that receives the payment, in src/v2.ts, with the key lines marked:

src/v2.ts
// By the time it gets here, the signature is already checked and the event matches its schema.
// The response has to be quick: if the gateway doesn't get a 2xx in time, it retries. That's why the
// long work (the notifications to the delivery company, the email) is left for later (Phase 9).
// Since lesson 7, everything in one transaction: write down the gateway's event, turn the order
// into paid and save what has to be done afterwards (outbox.ts). Either all three things, or none.
// The route no longer talks to Redis: the relayer, in the worker, puts the jobs in the queue.
v2.openapi(contract.receivePayment, async (c) => {
const event = c.req.valid('json');
const order = await findOrder(event.orderId);
if (!order) {
return invalidData(c, [{ field: 'orderId', problem: 'No such order' }]);
}
const result = await db.transaction(async (tx) => {
// The same event again: receipt is acknowledged and nothing else is done.
if (!(await recordEvent(event.id, tx))) return 'repeated';
// Only a pending order becomes paid: a cancelled one stays cancelled.
const paid = await changeStatusIn(tx, order.id, 'paid', 'pending');
if (!paid) return 'unchanged';
// For later: one notification for each delivery URL (if one fails, only that one is retried)
// and the email. One id for this payment, the same in all the notifications and on every retry:
// with it, the company recognises a repeated notification.
const eventId = randomUUID();
for (const notificationId of await savedNotifications(tx)) {
await saveOutbox(tx, { type: 'payment-notice', notificationId, order: paid, eventId });
}
await saveOutbox(tx, { type: 'confirmation-email', order: paid });
return paid;
});
if (result === 'repeated') return c.json({ received: event.id, repeated: true }, 200);
// After the COMMIT, to whoever follows the order (as changeStatus does).
if (result !== 'unchanged') orderChanges.emit(result);
return c.json({ received: event.id, repeated: false }, 200);
});
  • db.transaction(async (tx) => …): everything inside, in one transaction, as in Phase 5. tx is its connection.
  • recordEvent(event.id, tx): the gateway’s event, now inside. If something fails afterwards, it is undone, and the gateway’s retry tries everything again.
  • changeStatusIn(…, 'paid', 'pending'): pays only if it is still pending, in the same UPDATE, like fix 1 in Phase 5.
  • saveOutbox(tx, …): one notice for each delivery URL, and the email.
  • orderChanges.emit, after the COMMIT, when the change can already be read.

The route no longer talks to the queue. Saving a job is one more row:

src/outbox.ts
// Saves a job for later, inside the transaction tx: with its COMMIT, it is saved with everything
// else; with a ROLLBACK, it disappears with everything else. Nothing goes to Redis yet.
export async function saveOutbox(tx: Transaction, job: Job): Promise<void> {
await tx.insert(outboxEvents).values({ type: job.type, data: job });
}

Somebody has to carry the rows to the queue: the relayer. It is not the carrier container from lesson 1, the pretend delivery company: this one lives in the WorkerA program that does not answer user requests: it keeps taking tasks from a queue and running them. It can be the same code as your server, started with a different command.Go to definition, in scripts/worker.ts:

scripts/worker.ts
// The relayer: on start, the events left unsent (by an API that went down, or a Redis that wasn't
// answering); after that, every second, the new ones.
const relayer = relayEverySecond();
  1. The payment routeone transaction: the order and its jobs

    COMMIT

  2. outbox_eventsin PostgreSQL, sent_at NULL

    every second

  3. The relayerin the worker

    enqueue

  4. The queuein Redis

    the job

  5. The emailin Mailpit

Each round, in src/outbox.ts, is a transaction in three steps: everything that follows goes inside its db.transaction(async (tx) => …). First, it takes the pending rows:

src/outbox.ts
const rows = await tx
.select()
.from(outboxEvents)
.where(isNull(outboxEvents.sentAt))
.orderBy(asc(outboxEvents.createdAt))
.limit(limit)
.for('update', { skipLocked: true });
if (rows.length === 0) return 0;

FOR UPDATE locks the rows it read until the end of the transaction, as in fix 2 in Phase 5. SKIP LOCKED skips the ones another worker has already locked, without waiting: with two workers, they never take the same ones.

Then it carries them to the queue, with a deadline:

src/outbox.ts
// One after another, each against the same deadline: the one that doesn't arrive in time, and
// the ones behind it, are left for the next round.
const deadline = sleep(QUEUE_WAIT, 'late' as const, { ref: false });
const sent: number[] = [];
for (const row of rows) {
const outcome = await Promise.race([
toQueue(row.data).then(() => 'queued' as const),
deadline,
]);
if (outcome === 'late') break;
sent.push(row.id);
}
if (sent.length === 0) throw new Error(`the queue doesn't answer in ${QUEUE_WAIT} ms`);
if (sent.length < rows.length) {
log.warn(
{ sent: sent.length, of: rows.length },
'the queue is slow: the rest, in the next round',
);
}
  • QUEUE_WAIT, 2 seconds per round. A hung Redis would never answer, and the Redis client’s limit doesn’t count once the command has been sent (lesson 2): the application sets it, with Promise.race, a race between each command and a single 2-second clock for the whole round.
  • It only writes down what Redis has confirmed. If it is slow, it keeps what has arrived and leaves the rest. If nothing arrives, it throws an error: ROLLBACK, and everything stays pending.

Last, it writes down the ones that arrived, and COMMIT:

src/outbox.ts
// clock_timestamp(): the time now, after enqueuing. now() would be the BEGIN's.
await tx
.update(outboxEvents)
.set({ sentAt: sql`clock_timestamp()` })
.where(inArray(outboxEvents.id, sent));
return sent.length;
  • It enqueues before the COMMIT. The other way round (mark as sent and enqueue afterwards), a worker that goes down in between would lose them: the same gap as before.
  • clock_timestamp(): the time after enqueuing; now() would give the time the transaction began.

There is one round when the worker starts, for whatever a crash left pending, and another every second. Without Redis, the API itself does the relaying.

A worker that disappears with the rows locked

Section titled “A worker that disappears with the rows locked”

Before reading, the round starts with a line that covers a rare and serious case:

src/outbox.ts
// If the worker disappears with the transaction open (its machine is switched off, the network
// is cut), PostgreSQL doesn't find out until TCP gives the connection up for lost, and that can
// take hours: until then, its rows stay locked and nobody relays them. With this, a transaction
// that spends 5 seconds without sending anything is cut and releases its rows. 5 seconds, more
// than QUEUE_WAIT: while it waits for Redis, the transaction isn't sending anything either.
// SET LOCAL: only for this transaction, not for the connection, which goes back to the pool.
await tx.execute(sql`SET LOCAL idle_in_transaction_session_timeout = '5s'`);

If the worker’s machine switches off abruptly, PostgreSQL can take hours to give the connection up for lost, and meanwhile its rows stay locked. With this setting, a transaction that goes 5 seconds without sending anything is cut off and releases its rows.

At least once, again: ids that absorb the repeats

Section titled “At least once, again: ids that absorb the repeats”

The outbox guarantees lesson 1’s At-least-once deliveryA queue’s promise that every message will arrive at least once, never zero times. In exchange, it may arrive twice, for example if the worker goes down just before confirming it finished. That is why what the worker does must be idempotent.Go to definition. Sometimes, twice:

  • the relayer enqueues and goes down before the COMMIT, and the next round enqueues the same thing;
  • Redis answers late, when the round had already left that job for the next one.

That is why every job carries an id taken from what it is, not a random one:

src/queue.ts
// Each job, with its id (jobId). If another one with an id that is already there reaches the queue,
// BullMQ doesn't write it down: it keeps the one it had, waiting, half done or already done. Since
// lesson 7, the same job can arrive twice (outbox.ts: the relayer enqueues it and goes down before
// marking it), and this way it is done only once. The email, one per order; the notification, one
// per payment and per URL. BullMQ remembers the ids of the jobs it keeps: the waiting ones and the
// last 1000 done and failed (JOB_OPTIONS). What repeats later would be done again: that is why the
// notifications also carry X-Event-Id (notifications.ts), so the company recognises a repeated one.
export function jobId(job: Job): string {
switch (job.type) {
case 'payment-notice':
return `notice-${job.eventId}-${job.notificationId}`;
case 'confirmation-email':
return `email-${job.order.id}`;
}
}

One email per order: email-21. BullMQ doesn’t write down a job with an id it already has, as long as it keeps it: waiting, half done or among the last 1,000 done or failed. A repeat arrives within seconds, so it almost always finds it. For what repeats later, the notices carry X-Event-Id: whoever receives them has to be IdempotentSaid of an operation that leaves things in the same state whether you do it once or ten times. In HTTP, GET, PUT and DELETE are idempotent and POST isn’t, so repeating a POST can create two orders.Go to definition, as in Phase 4’s webhooks.

A job that used up its five attempts also keeps its id, so enqueuing it again does nothing: you re-run it with BullMQ’s job.retry(). And the table doesn’t clean itself: a real shop would delete old sent rows every day.

When events help and when they hide the flow

Section titled “When events help and when they hide the flow”

Events help when several parts react to the same thing; when whoever announces must not depend on whoever listens; and when different teams own different parts, as in microservices.

They hide the flow if you use them for everything. With calls, you read the payment route and know what happens next. With events, that is spread among the subscribers, and to find out why an order didn’t ship you follow the event through each one’s logs. And things happen a little later: the Eventual consistencyThe guarantee that, if changes stop arriving, all copies of a piece of data will end up with the same value, even though for a while some show the old one. It is accepted in exchange for speed and for continuing to work when the network fails.Go to definition of lesson 6.

A practical rule: call when you need the answer now; publish an event when it is news other parts may care about.

The goal: lose an email on purpose with step 40, and watch step 41 deliver it, with the same commands.

The trick is to freeze Redis with docker compose pause, as you froze the API in Phase 8: it accepts connections, but doesn’t answer. In step 40, the payment route saves the order and waits for the queue: you kill the API right there, in the gap.

The outputs come from an Apple M1 Pro with Docker in Colima (4 CPUs and 2 GiB), on October 22, 2026, with Node 26. Your ids, times and container names may vary.

You work in your project, ~/backend-course/phase-3/shop-api, at step 40 from lesson 4. If you didn’t do it, put it at step 40 as in the introduction. Delete the practice data, so that order 21 is pending again, and start everything:

Ventana de terminal
cd ~/backend-course/phase-3/shop-api
docker compose down -v

1. The shop, with its queue and Mailpit

Ventana de terminal
docker compose up --build --wait 2>&1 | tail -n 9

What you will see:

Container shop-redis-1 Waiting
Container shop-cache-1 Waiting
Container shop-migrate-1 Exited
Container shop-mailpit-1 Healthy
Container shop-cache-1 Healthy
Container shop-redis-1 Healthy
Container shop-db-1 Healthy
Container shop-worker-1 Healthy
Container shop-api-1 Healthy

tail -n 9 keeps the last lines. Look at shop-api-1 and shop-worker-1: both are running.

2. Freeze the queue

Ventana de terminal
docker compose pause redis

What you will see:

Container shop-redis-1 Paused

Redis no longer answers, but its connections stay open: the API gets no error, only silence.

The gateway pays order 21, pending in the sample data:

3. Pay, and kill the API

Ventana de terminal
docker run --rm --network shop_default --env-file .env -e SHOP_URL=http://api:3000 -v "$PWD":/p -w /p node:26 node scripts/payment-gateway.ts 21 > payment.txt 2>&1 &
sleep 3
docker compose kill api

What you will see:

Container shop-api-1 Killing
Container shop-api-1 Killed
  • docker run … scripts/payment-gateway.ts 21: Phase 4’s gateway, in a Node 26 container inside Compose’s network, so it reaches the API by its name, api.
  • --env-file .env: your webhooks’ secret, as in lesson 1.
  • > payment.txt 2>&1 &: whatever it says goes to payment.txt, and it runs in the background: it may never get an answer. Your terminal also prints [1] and a number.
  • docker compose kill api: kills the API at once (SIGKILL), with no orderly shutdown. A real crash.

4. Unfreeze, and see what the gateway got

Ventana de terminal
sleep 5
docker compose unpause redis
sleep 1
cat payment.txt

What you will see:

Container shop-redis-1 Unpaused
→ POST /v2/webhooks/payments {"id":"evt_9e3e0bc3-b249-4284-bb36-1ca7df5bd299","type":"payment.completed","orderId":21}
node:internal/modules/run_main:111
triggerUncaughtException(
^
[TypeError: fetch failed] {
[cause]: SocketError: other side closed
…

We cut the end of the error. other side closed: the API shut down without answering.

Wait a few seconds, in case the worker has something to do, and look at what is left in each place:

5. Where is the email?

Ventana de terminal
docker compose exec -T db psql -U shop -c 'SELECT id, status FROM orders WHERE id = 21'
docker compose exec -T redis redis-cli keys 'bull:shop:*' | sort
curl -s http://localhost:8025/api/v1/messages
docker compose logs --no-log-prefix worker

What you will see:

id | status
----+--------
21 | paid
(1 row)
bull:shop:meta
bull:shop:stalled-check
{"total":0,"unread":0,"count":0,"messages_count":0,"messages_unread":0,"start":0,"tags":[],"messages":[]}
{"level":30,"time":1792673082718,"pid":1,"hostname":"5dbd23453c3e","msg":"The worker is waiting for jobs from the queue"}
  • PostgreSQL: order 21, paid. The first write happened.
  • Redis: only the queue’s own keys, no job. The second one didn’t arrive.
  • Mailpit: "total":0. The worker: its start line, and nothing else.

If the gateway retried, it would get “repeated.” The email is lost for good.

Delete step 40’s data, so that order 21 is pending again, and put your project at step 41:

Ventana de terminal
docker compose down -v
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/41-events.tar.gz
tar -xzf 41-events.tar.gz
cp -R 41-events/. shop-api/
cd shop-api

Repeat steps 1 to 4 here, the same commands. This time, the cat payment.txt of step 4 shows something else:

6. What the gateway saw, now

Ventana de terminal
cat payment.txt

What you will see:

→ POST /v2/webhooks/payments {"id":"evt_52726c8a-9612-4fd5-9f9c-5e84503b6eb1","type":"payment.completed","orderId":21}
← 200 {"received":"evt_52726c8a-9612-4fd5-9f9c-5e84503b6eb1","repeated":false}

200, with Redis frozen: the payment route no longer talks to the queue, and it answered before you killed it.

7. The outbox

Ventana de terminal
docker compose exec -T db psql -U shop -c 'SELECT id, type, created_at, sent_at FROM outbox_events'

What you will see:

id | type | created_at | sent_at
----+--------------------+------------------------------+-------------------------------
1 | confirmation-email | 2026-10-22 12:45:38.44975+00 | 2026-10-22 12:45:46.695113+00
(1 row)

One row, the email: the sample data has no delivery URLs, so there are no notices. sent_at runs about 8 seconds behind created_at: the time Redis stayed frozen, plus the time the relayer took to try again. The times are in UTC (+00). If sent_at comes out empty, wait a second and repeat.

8. The queue, the email and the worker

Ventana de terminal
docker compose exec -T redis redis-cli keys 'bull:shop:*' | sort
curl -s http://localhost:8025/api/v1/messages
docker compose logs --no-log-prefix worker

What you will see:

bull:shop:completed
bull:shop:email-21
bull:shop:events
bull:shop:id
bull:shop:meta
bull:shop:stalled-check
{"total":1,"unread":1,"count":1,…,"To":[{"Name":"","Address":"carmen@example.com"}],…,"Subject":"Your order 21 is paid",…}
{"level":30,"time":1792673128160,"pid":1,"hostname":"f3d849eee823","msg":"The worker is waiting for jobs from the queue"}
{"level":40,"time":1792673141294,"pid":1,"hostname":"f3d849eee823","reason":"the queue doesn't answer in 2000 ms","msg":"the outgoing events haven't reached the queue: it will be retried"}
{"level":40,"time":1792673144301,"pid":1,"hostname":"f3d849eee823","reason":"the queue doesn't answer in 2000 ms","msg":"the outgoing events haven't reached the queue: it will be retried"}
{"level":30,"time":1792673146698,"pid":1,"hostname":"f3d849eee823","events":1,"msg":"outgoing events relayed"}
{"level":30,"time":1792673146723,"pid":1,"hostname":"f3d849eee823","id":"email-21","type":"confirmation-email","msg":"job done"}

We cut Mailpit’s answer with “…”, because it is very long.

  • Redis: one job, bull:shop:email-21, with the id taken from the order.
  • Mailpit: “Your order 21 is paid,” for Carmen. Also at http://localhost:8025.
  • The worker: two rounds that don’t arrive (the queue doesn't answer in 2000 ms), about 3 seconds apart (time is in milliseconds: 2 seconds of waiting and 1 of pause). Then the good one, and job done.

If Redis answers before the relayer tries, you won’t see retries, and the email arrives all the same. When you finish, docker compose down -v and rm payment.txt.

Your project is already at step 41: commit and git push from shop-api, and wait for Publish. Nothing new is needed in .env. deploy.sh applies migration 011 before the handover from lesson 4, during which an old copy, which enqueues as before, and a new one, which writes to the table, live side by side. The worker is switched last: until then, those rows wait in the table, without being lost. The same if you go back to 40 (Phase 8’s rollback): step 40 doesn’t read that table, and the rows step 41 didn’t get to hand out wait there until you deploy 41 again, which hands them out then.

  • GitHub Actions. The on: push of Phase 8’s workflow is a subscription to an event: GitHub announces “a push has arrived,” and every subscribed workflow reacts on its own.
  • Saving and enqueuing separately “because it almost never fails.” If one in a hundred thousand fails, with thousands of payments a day that is several a month.
  • Marking as sent before enqueuing. If the process goes down in between, the job is lost.
  • Reading the outbox without SKIP LOCKED. With two workers, the second waits for the first; without FOR UPDATE, both enqueue the same rows.
  • Assuming each message arrives exactly once. It arrives at least once: whoever receives it recognizes the repeats by their id.
  • Using db instead of tx inside the transaction. It asks for another connection from the pool: with more simultaneous payments than connections (10), all of them wait for one more, and the shop hangs. That is why savedNotifications(tx) takes the transaction.
  • A command says what to do and goes to one party; an event tells what has happened, and whoever wants to reacts.
  • Writing to the database and to the queue separately leaves a gap where jobs are lost, in either order: that is the dual write.
  • The outbox saves the job in the same transaction as the change, and a relayer carries it to the queue with FOR UPDATE SKIP LOCKED, a time limit, and writing down only what Redis confirmed.
  • Every job arrives at least once: ids taken from the content (email-21) and X-Event-Id absorb the repeats.
  • Events help when several parts react to the same thing; used for everything, they hide the flow.
When an account is created, the shop has to send a welcome email. Which of these messages is an event?

With step 40, Carmen complains: her order is paid in the database, but the email never arrived, and there is no job of hers in Redis. What most likely happened?

A coworker proposes: “Let’s enqueue the email first and save the payment afterwards; that way the email is never lost.” What do you answer?

The relayer has put 3 jobs in the queue and, before the COMMIT, its machine switches off abruptly. What happens to those 3 rows?

You add two workers to relay faster. What does SKIP LOCKED do when both look for pending rows at the same time?

Your system publishes “order paid” and five parts react. One day order 88 isn’t marked as shipped, and nobody knows which part failed. What does that tell you?

phase-9 · lesson 7/7