AlgoViz

Multi-system synchronization

medium 30 min

When 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

0:00 / 3:36

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

  1. 2014

    PostgreSQL 9.4, released on 18 December, adds logical decoding, which streams changes out of the write-ahead log.

  2. 2016

    PostgreSQL 9.5, released on 7 January, adds SKIP LOCKED, with which several workers can share a table as a queue.

  3. 2017

    On 30 June Confluent describes exactly-once semantics in the Kafka 0.11 release, for work that stays inside Kafka.

  4. 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.

Step 1 of 4

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.

One time for the town
12Hall12School12StationAll agree

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

Publishing first is no better: others may hear of an order that was rolled back.

Rare is not never

1,000,000×0.0001=100 gaps a day1{,}000{,}000 \times 0.0001 = 100 \text{ gaps a day}
Assumed: a million changes a day and one publish in ten thousand lost to crashes, restarts and timeouts.

Four attempts that do not close the gap

AttemptWhy not
Retry the publishThe process that would retry may be gone
Publish before the commitThe commit may still fail
Catch the error and roll backA timeout does not say whether the message was stored
Publish inside the transactionThe broker is not part of it, and the lock is held during a network call
Why concurrent requests can also arrive in different orders is shown in change data capture.

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

An order service writes to one database that holds an orders table and an outbox table in one transaction. A relay reads the outbox and publishes to a broker. A stock service reads from the broker and writes to its own database, which holds a stock table and an inbox table.
Pink arrows are local transactions. Dashed orange arrows are asynchronous and may repeat.

From click to stock

SQL
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;
Both rows or none

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.

OrderCrash in betweenResult
Mark, then publishMarked but never publishedThe event is lost
Publish, then markPublished but not markedThe event is repeated
Choose the repeat. A repeat can be ignored; a lost event cannot be invented.
SQL
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;
Several relays can share the table. Locked rows are skipped, not waited for. The lock lasts until the commit, after publishing.

Delay, capacity and catching up

1002=50 ms100 rows0.1 s=1,000/s30×1,8001,000−30≈56 s\tfrac{100}{2} = 50 \text{ ms} \qquad \frac{100 \text{ rows}}{0.1 \text{ s}} = 1{,}000/\text{s} \qquad \frac{30 \times 1{,}800}{1{,}000 - 30} \approx 56 \text{ s}
Polling every 100 ms in batches of 100, if a batch itself takes no time. After a broker outage of 30 minutes at 30 events a second, 54,000 rows drain in about 56 seconds.

Poll the table or follow the log?

Polling relayLog-based CDC
HowQuery for new rowsRead the transaction log
DelayThe intervalUsually short
LoadQueries all the timeDecoding, and log kept until read
OrderDepends on the queryCommit order
To operateA small workerA connector, and often Kafka Connect
Good startYesWhen you already run CDC
How log-based capture works is in change data capture.
JSON
{  "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"}
Part of a Debezium connector with the outbox event router. By default it expects the columns id, aggregatetype, aggregateid, type and payload, and names the topic outbox.event. followed by the aggregate type. The password comes from a secret store.

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

WayIdeaNote
NaturalSet a value instead of changing itBest when possible
Inbox tableInsert the event id with the effect, in one transactionWorks for any local effect
Version checkApply only if the version is newerAlso handles late events
Idempotency keySend a key to the outside systemOnly if that system supports it
More in idempotency. A set of ids in the memory of one process is not enough: it is gone after a restart.
Python
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 unique key decides, so two consumers at once cannot both pass
Edit and run it in your browser

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

GuaranteeMeansWhen
At most onceMay be lost, never repeatedAcknowledge, then work
At least onceNever lost, may be repeatedWork, then acknowledge
Once in effectRepeats change nothingAt least once plus an idempotent consumer

Four troubles

Order, repeats, losses, formats

TroubleExampleAnswer
Out of orderUserUpdated arrives before UserCreatedKey by entity, versions, upserts
RepeatsA customer is charged twiceInbox, idempotency keys
LossesAcknowledged, then crashedWork first, acknowledge second
New formatsAn old consumer cannot read a new eventCompatible changes, a schema registry

What to do with an event

Skipping older versions is right for full-state events. If each event is a step, such as add 5, wait for the missing one instead.

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

PatternUse it whenPrice
Outbox and inboxOne change must reach othersA relay and two tables
CDCCopies must follow a database, also an old applicationExposes tables, a connector
SagaSeveral services must each do a stepCompensations: see saga
Event sourcingThe history is the businessViews, versions, replays
Two-phase commitFew databases, one team, support on all sidesLocks while waiting, a coordinator
PostgreSQL's manual says that PREPARE TRANSACTION is meant for external transaction managers, not for use in applications.

Event sourcing in three events

The events are the truth and the state is computed. There is no second write to forget, but publishing to others still has to follow the store.

A saga across systems

Each arrow between services is an outbox and an inbox. Compensations are new actions, not a rollback.

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

Stripe's v1 API may remove keys once they are at least 24 hours old. A retry after that could charge again, so ask for the state first.

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.

Python
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))
Find and repair differences, but leave recent ones alone
Edit and run it in your browser

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

  1. Interviewer

    An order must be saved, announced, and charged at a provider. How do you keep the three in step?

  2. 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.

  3. Interviewer

    The relay crashes after publishing.

  4. You

    It publishes again after the restart. The payment worker finds the id in its inbox and checks whether the intent is already finished.

  5. Interviewer

    Someone fixes a row by hand.

  6. 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