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.

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

COMMITOrder servicePostgreSQLordersKafkaStock service

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

commitOrder servicePostgreSQLorders + outboxRelayKafkaStock serviceStock datastock + inbox
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

    critical

    A crash between the lines loses the event for ever.

    Wrong
    mark_sent(rows)for row in rows:    broker.publish(row)
    Right
    for row in rows:    broker.publish(row)      # wait until stored    mark_sent(row)
  • Checking outside the transaction

    critical

    Two consumers both see nothing and both apply the event.

    Wrong
    if not seen(event.id):    apply(event)    remember(event.id)
    Right
    with db.transaction():    if insert_if_absent("inbox", event.id):        apply(event)
  • Acknowledging first

    major

    If the work fails after the acknowledgement, the message never comes back.

    Wrong
    message.ack()handle(message)
    Right
    handle(message)message.ack()
  • Saying add instead of set

    major

    A repeated delta counts twice. A repeated value does not.

    Wrong
    publish({"add_points": 10})
    Right
    publish({"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.