Data & consistency · Transactional outbox with change data capture
Publish an event exactly when the database change commits, without distributed transactions
The service writes the business change and the event to an outbox table in the same local transaction. A relay reads committed outbox rows (by change data capture or polling) and publishes them to the event bus. Consumers are idempotent, so a redelivered event is harmless.
By Archipelego, version 1.
When to use it
- A service must update its database and notify others reliably
- Two-phase commit is not available or too fragile
- At-least-once delivery with idempotent consumers is acceptable
When not to use it
- Consumers cannot be made idempotent
- You need exactly-once end to end across systems
- A single database transaction can serve every reader directly
Trade-offs
Gains
- No lost or phantom events: the event exists only if the change committed
- No distributed transaction
- Events keep the commit order per aggregate
Costs
- An extra table and a relay to run
- At-least-once: consumers must deduplicate
- Some delay between commit and publication
Ingredients
- Client
- Order service
- Consumers
- Orders and outbox tables
- Outbox relay (CDC)
- Event bus
- Lag monitor
How it is served
AWS
AWS · Single provider
- Order service: ECS service
- Orders and outbox tables: Aurora PostgreSQL
- Outbox relay (CDC): Debezium on MSK Connect
- Event bus: Amazon MSK
- Consumers: Lambda consumers
- Lag monitor: CloudWatch
Deploy
- Add the outbox table next to the business tables
- Turn on logical replication in Aurora
- Run the Debezium outbox event router on MSK Connect
- Store processed event ids in each consumer for idempotency
- Alarm on relay lag in CloudWatch
Open source
Open source · On premises
- Order service: Service on Kubernetes
- Orders and outbox tables: PostgreSQL
- Outbox relay (CDC): Debezium (Kafka Connect)
- Event bus: Apache Kafka
- Consumers: Kafka consumers
- Lag monitor: Prometheus + Grafana
Deploy
- Add the outbox table and write to it in the same transaction
- Enable logical replication in PostgreSQL
- Deploy Debezium with the outbox event router
- Deduplicate in consumers by event id
- Watch connector lag in Grafana
Tags: events, cdc, microservices, consistency, kafka, database
Open this recipe in Archipelego to pick a variant, follow the method and cook it into a board.