Multi-system synchronization
medium 30 minWhen one change must reach a database, a broker and other services, two separate writes will one day disagree.
See it run
How one change reaches several systems without being lost or counted twice, and how you find out if it did not.
Operations
The dual write
Two writes without a common transaction, and a crash between them.
Step 1 of 4
Write to the database
The order is inserted and committed.
Step 1: Write to the database
db.insert(order); db.commit()broker.publish("OrderCreated") # crash here: nobody hears- Delay
- None
- Price
- Silent gaps
- 1 in 10,000 of a million a day
- 100 gaps
A retry does not help if the process that should retry is gone.
In the real world
The same multi-system synchronization doing real jobs. Pick one and step through it.
Kafka is down for 30 minutes at 30 orders a second.
Step 1 of 3
Orders go on
- Outbox rows
- 16,200 after 9 min
The service commits orders and events as always.
Step 1: Orders go on
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Marking before publishing
criticalA crash between the lines loses the event for ever.
Wrongmark_sent(rows)for row in rows: broker.publish(row)Rightfor row in rows: broker.publish(row) # wait until stored mark_sent(row)Checking outside the transaction
criticalTwo consumers both see nothing and both apply the event.
Wrongif not seen(event.id): apply(event) remember(event.id)Rightwith db.transaction(): if insert_if_absent("inbox", event.id): apply(event)Acknowledging first
majorIf the work fails after the acknowledgement, the message never comes back.
Wrongmessage.ack()handle(message)Righthandle(message)message.ack()Saying add instead of set
majorA repeated delta counts twice. A repeated value does not.
Wrongpublish({"add_points": 10})Rightpublish({"points": 120, "version": 8})
Interview tips
How to explain it
- One transaction for data and event.
- Publish later, at least once.
- Consumers record the id with the effect.
Memory trick: ATOMIC
- Atomically write. Transaction log. Outbox.
- Message broker. Idempotent consumers.
- Compensating transactions.
Watch these numbers
- Age of the oldest outbox row.
- Consumer lag and parked events.
- Repairs per day.
Be careful with
- Two-way sync without rules.
- Order with several relays.
- Outside systems that forget keys.