Multi-system synchronization
medium 30 minWhen one change must reach a database, a broker and other services, two separate writes will one day disagree.
Video lesson · Chapter 1 of 5
The order exists, but the warehouse never hears
Three clock towers, one time, in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Multi-system synchronization keeps the same fact consistent in several systems: an order in the database, a message for shipping, a document in search, a record at a payment provider.
No ordinary transaction spans these systems. So the work is cut into steps that can each be repeated: commit the change and its event together, publish the event, apply it once in effect, and compare the results.
Why it exists
Writing to two systems one after the other looks harmless. But a crash, a timeout or a deployment between the two writes leaves one of them without the change, and no error tells anybody.
A customer is charged and has no order. A subscriber is stored and never receives an email. At a million changes a day, even a tiny share of such gaps means work for people every day.
The patterns here trade a short delay for a promise: what was committed will arrive, and arriving twice does no harm.
A short history
2014
PostgreSQL 9.4, released on 18 December, adds logical decoding, which streams changes out of the write-ahead log.
2016
PostgreSQL 9.5, released on 7 January, adds SKIP LOCKED, with which several workers can share a table as a queue.
2017
On 30 June Confluent describes exactly-once semantics in the Kafka 0.11 release, for work that stays inside Kafka.
2019
On 19 February the Debezium blog publishes an article on reliable data exchange between microservices with the outbox pattern.
Words to know
- Dual write
- Changing two systems without a common transaction.
- Source of truth
- The one system whose value wins when two disagree.
- Outbox
- A table for events, written in the same transaction as the data.
- Relay
- The worker that moves outbox rows to the broker.
- Inbox
- A table of handled event ids, written in the same transaction as the effect.
- Idempotent
- Doing it twice has the same result as doing it once.
- Reconciliation
- Comparing two systems and repairing the differences.
How it works
Step through the idea, or press Play.
Commit. Data and event together
Understand it
Start here
Three clock towers
A town has three clock towers: the hall, the school and the station. Sam looks after them. When the hour changes, all three should agree, but Sam can be at only one tower at a time.
A newsletter works the same way: save the address and the task send welcome together, and let a worker send it later.
The problem
Two writes, one crash
The dual write
Rare is not never
Four attempts that do not close the gap
| Attempt | Why not |
|---|---|
| Retry the publish | The process that would retry may be gone |
| Publish before the commit | The commit may still fail |
| Catch the error and roll back | A timeout does not say whether the message was stored |
| Publish inside the transaction | The broker is not part of it, and the lock is held during a network call |
First decision
One source of truth
Before any pattern: which system decides? Give every fact one owner that accepts writes. All other places are derived and can be rebuilt. This is the idea behind database per service.
One direction
- Writes enter at one place
- Copies are read-only
- A broken copy is rebuilt from the owner
- Differences have a clear answer
Both directions
- Both sides accept writes
- Two people change the same field at once
- Updates can echo back and forth
- Every conflict needs a rule
Sometimes both directions are required, for example a calendar on a phone and on a server. Then mark each change with its origin so that it does not echo, and choose a rule per field: a named owner, a merge, or asking a person. Last write wins by wall clock quietly loses one of the two changes, and the clocks may differ.
Pattern
The transactional outbox
Outbox on one side, inbox on the other
From click to stock
BEGIN;INSERT INTO orders (id, user_id, status)VALUES ('o1', 'u1', 'CREATED');INSERT INTO outbox (id, aggregate_type, aggregate_id, type, payload)VALUES ('e1', 'order', 'o1', 'OrderCreated', '{"items": 2}');COMMIT;What you get
Atomicity
Data and event are stored together.
Reliability
A committed event waits until it is published.
Repeats
It may be published more than once.
Order
Per entity, if the relay and the key keep it.
Later consistency
Others follow after a short delay.
Independence
Placing an order works while the broker is down.
The worker
The relay: order of two lines
The relay also touches two systems: it publishes, and it marks the row. Which comes first decides what a crash does.
| Order | Crash in between | Result |
|---|---|---|
| Mark, then publish | Marked but never published | The event is lost |
| Publish, then mark | Published but not marked | The event is repeated |
BEGIN;SELECT id, aggregate_id, payloadFROM outboxWHERE sent_at IS NULLORDER BY idLIMIT 100FOR UPDATE SKIP LOCKED;-- publish each row, wait for the broker's answerUPDATE outbox SET sent_at = now() WHERE id = ANY(:ids);COMMIT;Delay, capacity and catching up
Poll the table or follow the log?
| Polling relay | Log-based CDC | |
|---|---|---|
| How | Query for new rows | Read the transaction log |
| Delay | The interval | Usually short |
| Load | Queries all the time | Decoding, and log kept until read |
| Order | Depends on the query | Commit order |
| To operate | A small worker | A connector, and often Kafka Connect |
| Good start | Yes | When you already run CDC |
{ "table.include.list": "public.outbox", "database.password": "FROM_YOUR_SECRET_STORE", "transforms": "outbox", "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", "transforms.outbox.route.topic.replacement": "${routedByValue}.events"}With this router the outbox behaves like a queue: rows are inserted and may be deleted, but updates are not allowed. So there is no sent column to update. Deletes are filtered out, which keeps the table small. The event id travels as a message header and the aggregate id becomes the message key.
The other side
The idempotent consumer
Safe to repeat
- SET status = 'PAID'
- DELETE WHERE id = 1
- INSERT ... ON CONFLICT DO NOTHING
- UPDATE ... WHERE version = 5
Not safe to repeat
- balance = balance + 10
- INSERT without a key
- Send an email
- Charge a card
Four ways to make it safe
| Way | Idea | Note |
|---|---|---|
| Natural | Set a value instead of changing it | Best when possible |
| Inbox table | Insert the event id with the effect, in one transaction | Works for any local effect |
| Version check | Apply only if the version is newer | Also handles late events |
| Idempotency key | Send a key to the outside system | Only if that system supports it |
import sqlite3db = sqlite3.connect(":memory:")db.executescript(""" CREATE TABLE inbox (event TEXT PRIMARY KEY); CREATE TABLE stock (item TEXT PRIMARY KEY, reserved INT); INSERT INTO stock VALUES ('lamp', 0);""")def handle(event_id, item, n, crash=False): with db: # one transaction new = db.execute("INSERT OR IGNORE INTO inbox VALUES (?)", (event_id,)).rowcount if not new: return "ignored" db.execute("UPDATE stock SET reserved = reserved + ? WHERE item = ?", (n, item)) if crash: raise RuntimeError("crash before commit") return "applied"try: handle("e1", "lamp", 2, crash=True)except RuntimeError as error: print(error)print(handle("e1", "lamp", 2), handle("e1", "lamp", 2))print(db.execute("SELECT reserved FROM stock").fetchone())The inbox row and the effect commit together. Checking first and inserting later, in two steps, leaves a gap through which a second consumer slips. Keep inbox ids for longer than a message can possibly return, replays included.
Promises
At least once, once in effect
| Guarantee | Means | When |
|---|---|---|
| At most once | May be lost, never repeated | Acknowledge, then work |
| At least once | Never lost, may be repeated | Work, then acknowledge |
| Once in effect | Repeats change nothing | At least once plus an idempotent consumer |
Four troubles
Order, repeats, losses, formats
| Trouble | Example | Answer |
|---|---|---|
| Out of order | UserUpdated arrives before UserCreated | Key by entity, versions, upserts |
| Repeats | A customer is charged twice | Inbox, idempotency keys |
| Losses | Acknowledged, then crashed | Work first, acknowledge second |
| New formats | An old consumer cannot read a new event | Compatible changes, a schema registry |
What to do with an event
Add optional fields freely. Never change the meaning of a field or remove one that is still read. A parked event goes to a dead-letter queue, with a person who is told. But mind the order: the later events of the same entity may have to wait as well.
Wider
Related patterns
| Pattern | Use it when | Price |
|---|---|---|
| Outbox and inbox | One change must reach others | A relay and two tables |
| CDC | Copies must follow a database, also an old application | Exposes tables, a connector |
| Saga | Several services must each do a step | Compensations: see saga |
| Event sourcing | The history is the business | Views, versions, replays |
| Two-phase commit | Few databases, one team, support on all sides | Locks while waiting, a coordinator |
Event sourcing in three events
A saga across systems
Outside
Systems you do not own
A payment provider has no outbox in your database. Write the intent first, then call with an idempotency key derived from it, then record the answer. After a timeout you do not know what happened, so repeat the call with the same key or ask for its state.
Charge once, even after a timeout
Incoming news from such systems arrives as webhooks. They can repeat and come in any order, so record their ids in an inbox as well.
Safety net
Reconciliation
Bugs, manual fixes and restored backups create differences that no event describes. So compare the systems regularly: counts first, then checksums per range, then rows that differ. Repair towards the source of truth, and count what you repaired, because that number should be near zero.
def reconcile(truth, copy, now, grace): """Both: id -> (value, changed_at). Returns the repairs.""" repairs = [] for key in sorted(truth.keys() | copy.keys()): a, b = truth.get(key), copy.get(key) if (a and a[0]) == (b and b[0]): continue changed = max(x[1] for x in (a, b) if x) if now - changed < grace: continue # probably still on its way repairs.append((key, "delete" if a is None else "write", a and a[0])) return repairstruth = {1: ("paid", 100), 2: ("new", 998), 3: ("shipped", 300)}copy = {1: ("paid", 101), 3: ("paid", 200), 4: ("ghost", 50)}print(reconcile(truth, copy, now=1000, grace=60))Decide
How much do you need?
Choose the smallest thing that works
Do
- Use an outbox for events that must not be lost
- Make every consumer idempotent
- Store event ids with the effect
- Key events by entity
- Reconcile on a schedule
Avoid
- Writing to a database and a broker in one request
- Assuming that messages arrive once
- Ignoring order
- Two-phase commit as the default
- Forgetting compensations
In an interview
Interviewer
An order must be saved, announced, and charged at a provider. How do you keep the three in step?
You
The order database is the truth. One transaction stores the order and an OrderCreated row in the outbox. A relay publishes it, keyed by order. The payment worker records the event id and an intent in one transaction, then calls the provider with the order's idempotency key.
Interviewer
The relay crashes after publishing.
You
It publishes again after the restart. The payment worker finds the id in its inbox and checks whether the intent is already finished.
Interviewer
Someone fixes a row by hand.
You
Then no event exists. A nightly reconciliation compares orders with the provider's list and reports the difference. I also alert when the oldest outbox row is older than a minute.
Summary
The whole topic in one minute.
Choose one source of truth. Write the change and its event in one local transaction, let a relay publish, and let every consumer record the event id together with its effect. Delivery is at least once; the effect is once.
Keep events of one entity in order with a key and a version. Give outside systems an idempotency key. And because bugs, manual fixes and lost files exist, compare the systems on a schedule and repair.
- Never write to two systems and hope.
- Outbox: data and event in one transaction. Publish first, mark second.
- Inbox: event id and effect in one transaction.
- At least once plus idempotent is once in effect.
- Order per entity, and reconcile against one source of truth.
Sources
- microservices.io: Transactional outbox
- AWS Prescriptive Guidance: transactional outbox
- Debezium: outbox event router
- Debezium blog: the outbox pattern (2019)
- PostgreSQL: SELECT and SKIP LOCKED
- PostgreSQL: PREPARE TRANSACTION
- Apache Kafka: design, delivery semantics
- Stripe: webhooks
- Stripe: idempotent requests