Home›Learn›Sagas and the outbox
Course · ArchitectureLesson 26 of 330 read

Sagas and the outbox

How do I update my database and publish an event without losing one of them?

The bug and the fix, animated, with the SQL.

Press Play, or step with the arrows. Start with Dual write to see the bug the outbox fixes.

In a microservice system each service owns its database, so one business action, placing an order, spans several databases. There is no transaction across them. The two tools that make this safe both live in the database: the transactional outbox and the saga.

The outbox in SQL

Go deeper
BEGIN;
INSERT INTO orders (id, customer_id, total_cents, status) VALUES ($1, $2, $3, 'placed');
INSERT INTO outbox (id, aggregate_id, type, payload)
VALUES (gen_random_uuid(), $1, 'OrderPlaced', $4::jsonb);
COMMIT;
-- A polling relay: many workers, no double publishing
SELECT id, type, payload FROM outbox
WHERE published_at IS NULL
ORDER BY created_at
LIMIT 100
FOR UPDATE SKIP LOCKED;
-- publish, then: UPDATE outbox SET published_at = now() WHERE id = ANY($1);
-- The consumer side: process each event once
CREATE TABLE processed_events (
  event_id     text PRIMARY KEY,
  processed_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO processed_events (event_id) VALUES ($1) ON CONFLICT DO NOTHING;
-- if no row was inserted, this event was already handled: skip it

The dedup only works because event_id is the primary key. Without a unique constraint, ON CONFLICT DO NOTHING never fires.

Where it breaks

Go deeper
  • The outbox grows forever. Delete or partition published rows, or the table and its index bloat.
  • A polling relay without SKIP LOCKED. Workers wait on the same rows. See a table as a queue.
  • A CDC relay with an unread replication slot. PostgreSQL keeps WAL for the slot until the disk fills.
  • Consumers that are not idempotent. At-least-once means duplicates will arrive.
Connected

Where this shows up

The same mechanism, events across services, migrations and upgrades, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 3 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. Why does the outbox fix the dual write problem?

2. The relay crashes after publishing but before marking the row sent. What happens?

3. In a saga, how is an earlier step undone?

Part 1 of 4 · Learn · 23 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.