Sub topic 10
Replicating Events and Messages Between Regions
This chapter assumes you know basic cloud networking, how queues and topics work, and the replication ideas from the previous chapters (asynchronous replication, write ownership, conflict resolution). It covers how events travel between regions and what that means for correctness.
Why events need their own treatment
In an active-active system, regions exchange more than database rows. They also exchange events such as "order placed", "user email changed" and "payment captured". Other regions consume these events to update caches, search indexes, read models and downstream services.
Cross-region links are slower and less reliable than links inside a region. A message crossing an ocean takes tens to hundreds of milliseconds and can be delayed, dropped, duplicated or reordered. Your design must assume all four.
Delivery guarantees
Messaging systems offer three delivery semantics.
| Guarantee | Meaning | Cost |
|---|---|---|
| At-most-once | A message is delivered zero or one times. | Messages can be lost. |
| At-least-once | A message is delivered one or more times. | Consumers see duplicates. |
| Exactly-once | Each message has exactly one effect. | Needs coordination, and usually works only inside one system. |
Across regions, at-least-once is the practical default. A producer retries until it gets an acknowledgement. If the acknowledgement is lost, the producer sends the message again, and the consumer sees a duplicate. Exactly-once delivery between independent regions is not something you can buy. What you can build is effectively-once processing: at-least-once delivery combined with idempotent consumers, covered in the next chapter.
Ordering
Ordering is the second hard problem. Two events about the same entity, such as AddressChanged then AddressChanged, can arrive out of order if they take different paths or are retried.
Common approaches:
- Partition by key. Route all events for one entity (for example one customer ID) to the same partition. Ordering holds within a partition, not across partitions.
- Single writer per key. If write ownership gives one region authority over an entity, that region produces its events in a single sequence. Consumers can rely on that order.
- Sequence numbers or versions. The producer stamps each event with a per-entity version. The consumer applies an event only if its version is newer than the stored one, and discards stale events.
- Do not depend on order. Design events so they commute, for example by using CRDT-style merges from the previous chapter.
Global ordering across all entities and regions needs a single sequencer. It adds latency and a single point of failure, so avoid it unless a requirement forces it.
Topologies for replicating messages
There are three common layouts.
- Regional queues with a replicator. Each region has its own broker. A replicator process reads from the local broker and writes to the remote one. Examples: Kafka MirrorMaker 2 or Cluster Linking, and RabbitMQ Shovel or Federation.
- Managed global replication. The platform copies events for you. Examples: Amazon EventBridge global endpoints, SNS-to-SQS fan-out across regions, and DynamoDB Streams feeding a consumer in another region.
- Event bus per region, cross-posted. Each service publishes to its local bus and a rule forwards selected events to the other regions' buses.
The diagram shows the common local-publish pattern with a replicator.
Avoiding replication loops
If both regions replicate to each other, an event copied from EU to US will be copied back to EU, and so on forever. Prevent this by tagging each event with its origin region and having a replicator skip events whose origin is the destination. Kafka MirrorMaker 2 does this by prefixing remote topic names, so eu.orders in the US cluster is never sent back to the EU.
Publishing reliably: the outbox pattern
A service often has to update its database and publish an event. If it writes to the database and then crashes before publishing, the event is lost. If it publishes first and the database write fails, the event describes something that never happened.
The transactional outbox fixes this. The service writes the business change and an event row to an outbox table in one local transaction. A separate relay process reads unpublished rows and sends them to the broker, marking each as sent. The relay can crash and retry, so delivery is at-least-once, but no event is lost.
import json
import sqlite3
import uuid
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id TEXT PRIMARY KEY, status TEXT)")
db.execute(
"CREATE TABLE outbox (event_id TEXT PRIMARY KEY, payload TEXT, sent INTEGER DEFAULT 0)"
)
def place_order(order_id):
# One local transaction: the order and its event commit together or not at all.
with db:
db.execute("INSERT INTO orders VALUES (?, ?)", (order_id, "placed"))
event = {"event_id": str(uuid.uuid4()), "type": "OrderPlaced",
"order_id": order_id, "origin": "eu-west-1"}
db.execute("INSERT INTO outbox (event_id, payload) VALUES (?, ?)",
(event["event_id"], json.dumps(event)))
def relay(publish):
rows = db.execute("SELECT event_id, payload FROM outbox WHERE sent = 0").fetchall()
for event_id, payload in rows:
publish(payload) # may raise; the row stays unsent and is retried later
with db:
db.execute("UPDATE outbox SET sent = 1 WHERE event_id = ?", (event_id,))
place_order("order-1")
relay(lambda payload: print("published", payload))If publish succeeds but the process dies before the UPDATE, the relay sends the event again after restart. That is the duplicate that consumers must tolerate.
Consuming events safely
A consumer in the remote region should do three things.
- Deduplicate using the
event_id, or make the operation naturally idempotent. - Check versions and ignore events older than the state it already holds.
- Acknowledge only after the effect is durable. Acknowledging first and failing later loses the event. Acknowledging last causes a redelivery, which step 1 absorbs.
Events that keep failing should go to a dead-letter queue (DLQ) after a bounded number of attempts. Otherwise one malformed message blocks a partition forever. Monitor the DLQ and have a replay procedure, since a DLQ nobody reads is just silent data loss.
Replication lag and its effects
Replication is asynchronous, so a remote region sees an event some time after it was produced. This delay is replication lag. Consequences:
- A user who writes in one region and reads in another may not see their own change. Keep a user's session sticky to one region, or carry a version token so the read waits until that version arrives.
- If a region fails, events not yet replicated are stuck in the failed region. That gap is your effective RPO for event data. Measure it. Do not assume it is zero.
- After an outage, a backlog of events replays all at once. Consumers must handle bursts, and ordering rules must still hold during catch-up.
Schema evolution
Regions rarely deploy at the same instant. During a rollout, one region may publish a new event shape while another still runs the old consumer. Use backward and forward compatible changes: add optional fields, never rename or repurpose fields, and have consumers ignore unknown fields. A schema registry helps enforce this.
Common mistakes
- Assuming the broker gives exactly-once delivery across regions.
- Publishing from application code without an outbox, so events and data drift apart.
- Replicating in both directions without origin tagging, causing loops.
- Relying on global ordering that no component actually guarantees.
- Retaining events for too short a time. If the remote region is down longer than the retention window, it cannot catch up from the broker and needs a full resync.
Exercise
A service in eu-west-1 saves an order and then calls the broker to publish OrderPlaced. The process crashes between the two steps. Which pattern prevents the lost event, and what new problem does it introduce for consumers in us-east-1?
Show answer
The transactional outbox prevents it: the order and the event row commit in one local transaction, and a relay publishes the row later. The relay can publish the same event twice if it crashes after sending but before marking the row as sent, so consumers must be idempotent (deduplicate by event_id or check versions).
Exercise
Both regions run a replicator that copies every topic to the other region. Events start multiplying. What is happening, and how do you stop it?
Show answer
Each event is copied to the remote region and then copied back, creating an endless loop. Tag events with their origin region and have each replicator skip events whose origin equals the destination, or use topic prefixes per origin region as Kafka MirrorMaker 2 does.