Home›Learn›Many servers 6: across services
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, unless you set max_slot_wal_keep_size, which invalidates the slot instead.
  • Consumers that are not idempotent. At-least-once means duplicates will arrive.
Next · chapter 7A thousand databasesRunning a fleet, not a server← Chapter 5: Split the data
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?

One database decision a weekA short email each week: one real decision, the trade-off, and the command to check it. Unsubscribe in one click.

Part 1 of 4 · Learn · 56 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.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect