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.
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.
The same mechanism, events across services, migrations and upgrades, elsewhere on the site: in real incidents, in measurements, and in designs.
Pick an answer. You will see whether it is right, and why.
1. Why does the outbox fix the dual write problem?
Both rows commit together or not at all; the relay only publishes what committed.
2. The relay crashes after publishing but before marking the row sent. What happens?
The outbox gives at least once delivery. Idempotent consumers make that effectively once.
3. In a saga, how is an earlier step undone?
Each service runs its own undo step, such as cancelling the order or releasing the stock.
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.