Change Data Capture & the Outbox Pattern
How to reliably propagate database changes to search indexes, caches, and other services — without dual writes, and without losing events.
#The dual-write problem
You update the database and you need to tell someone — reindex in Elasticsearch, invalidate a cache, publish an event, notify another service.
The obvious implementation is broken:
BROKEN
db.save(order) ✓ succeeded
queue.publish(event) ✗ network blip
→ the order exists; nothing downstream knows.
Search index, cache, and every consumer are now
permanently wrong, with no self-healing.
BROKEN THE OTHER WAY
queue.publish(event) ✓
db.save(order) ✗ constraint violation
→ an event announcing an order that doesn't exist.Two systems, no shared transaction. You cannot make two independent writes atomic by ordering them cleverly — there is always a window.
And you can't fix it with a distributed transaction. 2PC across a database and a message broker is possible in theory, unavailable in most stacks, and blocks under coordinator failure: if the process coordinating the commit dies at the wrong moment, both the database and the broker are left holding locks, waiting for a decision that never arrives. It's the wrong tool.
The insight: you don't need two atomic writes. You need one write, and a reliable way to derive the second from it.
#The outbox pattern
The fix is to stop making two writes. Put the event in an ordinary table — the outbox — in the same database and the same transaction as the business change, so the database's own atomicity guarantees they both land or neither does. A separate process then reads that table and does the publishing.
The outbox is just a mailbox: the transaction drops a letter in it, and someone else posts it.
BEGIN;
INSERT INTO orders (id, customer, total) VALUES (...);
INSERT INTO outbox (id, aggregate, type, payload, created_at)
VALUES (..., 'Order', 'OrderPlaced', '{...}', now());
COMMIT; ← atomic: both rows or neither
│
▼ relay process
┌──────────────────────────────────────────┐
│ read unpublished outbox rows │
│ publish to Kafka/SQS │
│ mark as published (or delete) │
└──────────────────────────────────────────┘Now atomicity is a local transaction — trivially guaranteed. The event either exists alongside the order or neither exists.
The relay gives at-least-once delivery — every event is published, but some may be published twice. That's exactly right. If publishing fails, the row is still unmarked, so the relay simply retries. If the relay publishes and then crashes before marking the row, it publishes the same event again after restarting. That duplicate is harmless as long as consumers are idempotent — processing the same event twice has the same effect as processing it once.
#Two ways to run the relay
Polling. SELECT * FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 100. Simple, works on any database, no special permissions. Costs a little latency (your poll interval) and constant query load. Index on (published_at, id), and delete or archive published rows so the table doesn't grow forever.
Log tailing (CDC). Read the database's replication log directly — no polling, no query load, latency in milliseconds. This is the better option at scale and leads directly to the next section.
#Change Data Capture
Change Data Capture takes a different route to the same goal. Every database already keeps an ordered log of what it changed, because that's how it does crash recovery and how it feeds its replicas. CDC simply reads that log and turns each committed change into an event.
The appeal: your application code doesn't change at all. It writes rows as it always did, and the events fall out of the database's own record of those writes.
┌────────────┐ WAL / binlog ┌─────────┐
│ Postgres │ ────────────────► │ Debezium│──► Kafka
│ (truth) │ logical decoding │ or │ │
└────────────┘ │ similar │ ├─► search index
└─────────┘ ├─► cache
├─► data warehouse
└─► other servicesWhy this is powerful:
- The application doesn't change at all. No outbox table, no publish calls. Existing code keeps writing to the database.
- Nothing can be missed. The log is the record of what committed — there's no code path that could forget to emit.
- Commit order is preserved, exactly as the database saw it.
- Low latency, typically milliseconds.
- Snapshot + stream. Most CDC tools take an initial consistent snapshot and then switch to streaming, so a new consumer gets full history plus live updates.
Costs and constraints:
- Events mirror your schema, not your domain. A CDC event says "row in
orderschanged:status_cdwent from 2 to 3", not "OrderShipped". Consumers become coupled to your table structure — a real problem, since you can no longer rename a column or split a table without breaking them. This is the strongest argument for the outbox pattern even when you have CDC: the outbox lets you publish a deliberately designed event, while CDC publishes whatever your tables look like. - Operational setup — replication slots, permissions, log retention. A replication slot is Postgres's bookmark for a log reader: it promises to keep every WAL segment the reader hasn't consumed yet. So if the CDC consumer stalls, the database keeps all WAL from that point on and can fill the primary's disk, taking down the database. This is a genuine production hazard and an excellent detail to mention.
- Schema changes ripple to consumers. You want a schema registry — a service that stores each version of the event format and rejects a change that would break existing consumers (such as removing a field they read).
- Deletes and TTL expiries may appear differently than you expect. A delete event may carry only the row's key and none of its old values unless you configure the table to log them, and some databases emit nothing at all when a row silently expires by TTL.
The combination that's best in practice: write to an outbox table for deliberate, well-designed domain events, and use CDC to tail that outbox table. You get the low latency and guaranteed capture of CDC with the clean, decoupled contract of the outbox. This is the answer that actually holds up under scrutiny.
#What this pattern is for
1. Keeping derived stores in sync. Search indexes, caches, denormalized read models, and analytics warehouses are all derived from the primary database. CDC guarantees they converge — and lets you rebuild any of them from scratch by replaying.
2. Cache invalidation. Rather than each write path remembering to invalidate, a CDC consumer invalidates on every change. Nothing is forgotten because nothing has to remember.
3. Cross-service integration without the source service knowing its consumers. The orders service just writes orders; a new loyalty-points service can start reading the change stream without anyone touching the orders code.
4. The strangler pattern. Migrating off a legacy system: stream its changes into the new one, run both in parallel, verify equivalence, then cut over. CDC is the standard mechanism for large migrations with no downtime.
5. Building an audit log — every change, in order, with before and after values.
#The consistency contract
State this clearly whenever you propose it, because it's the tradeoff being bought:
DB commit ──► log ──► relay ──► broker ──► consumer ──► derived store
t=0 t+1ms t+10ms t+20ms t+50ms t+100ms
The derived store is EVENTUALLY consistent — typically
tens to hundreds of ms behind, occasionally much more
under load or during a consumer restart.Consequences to design around:
- A user may write and not immediately see the change in search or a derived view. If that matters, read the user's own recent items from the primary and merge — a targeted read-your-writes fix rather than making the whole pipeline synchronous.
- Monitor consumer lag in time, not message count. "We're 4 minutes behind" maps to user impact; "12,000 messages" doesn't.
- Consumers must be idempotent — the pipeline is at-least-once end to end.
- Consumers must tolerate out-of-order arrival across different keys. Brokers like Kafka only guarantee order within one partition. So partition by the entity's ID: every event for order 42 then goes to the same partition and arrives in order, even if events for order 42 and order 43 interleave unpredictably.
#Comparison
| Approach | Atomicity | App changes | Coupling | Latency |
|---|---|---|---|---|
| Dual write | ✗ broken | Yes | Low | Low |
| 2PC | ✓ | Yes | High | High, blocks |
| Outbox (polling) | ✓ | Some | Low | Seconds |
| CDC on tables | ✓ | None | High (schema) | Milliseconds |
| Outbox + CDC | ✓ | Some | Low | Milliseconds |
The bottom row is the one to recommend when the design warrants it. The middle rows are fine when it doesn't — and knowing that a polling outbox is perfectly adequate for a system doing 100 events per second is as valuable as knowing the sophisticated version exists.
#Check yourself
What is the dual-write problem?Show answer
How does the outbox pattern fix dual writes?Show answer
Why must outbox consumers be idempotent?Show answer
What ordering bug hits a polling relay that follows an ID cursor?Show answer
What is change data capture, and why is it attractive?Show answer
Name CDC's two biggest costs.Show answer
What combination is best in practice?Show answer
What must derived stores fed by CDC handle?Show answer
#What to carry forward
- Two independent writes can't be made atomic by ordering them — derive the second from the first.
- Outbox: the event commits in the same local transaction; a relay delivers it at least once.
- CDC reads the database's own log: no app changes and nothing missed, but schema coupling and replication-slot risk.
- Outbox plus CDC on the outbox table gives the clean contract and the low latency.
- Derived stores are eventually consistent: idempotent consumers, per-entity ordering, lag measured in seconds.