Sub topic 8
Avoiding conflicts with write ownership and partitioning
This chapter assumes you know the basics of cross-region replication, the difference between synchronous and asynchronous replication, and what a conflict is when two regions accept writes to the same record. It covers the strategy that avoids most conflicts instead of resolving them: make sure only one region can write a given piece of data at a time.
Why prevent conflicts instead of resolving them
Conflict resolution (last-writer-wins, version tracking, CRDTs) works after two regions have already accepted competing writes. Some of those writes are then lost or merged in ways the user did not expect. Write ownership moves the decision earlier. Each record has one owning region, and only that region accepts writes for it. Other regions hold read-only replicas.
The result is that every record has a single ordered history. Ordinary database transactions, unique constraints and foreign keys keep working inside the owning region. The system is still active-active, because every region serves live traffic and owns a share of the data.
The cost is that a write issued in a non-owning region must travel to the owner or be rejected. You trade some write latency for simpler correctness.
Partitioning strategies
Write ownership needs a rule that maps each record to a region. That rule is a partition key (also called a home region or shard key).
| Strategy | Owner is chosen by | Good fit | Main weakness |
|---|---|---|---|
| User home region | The region closest to where the user signed up | Per-user data such as profiles, carts, settings | Travelling users get slow writes |
| Geographic or tenant | Country, or the tenant a customer belongs to | B2B SaaS, data residency rules | Large tenants create uneven load |
| Hash of key | A hash of the record ID maps to a region | Even load across regions | Ignores user location, so many writes are remote |
| Per-table or per-service | The service decides, for example billing in one region | Shared reference data, global counters | That region is a single point of write failure for that data |
Pick the key so that most writes land in the owning region. For a consumer app, the user ID with a home region works well, because a user usually acts on their own data from one place. A bad key, such as a global "inventory" row touched by every region, sends nearly all writes across the ocean.
How a request finds its owner
A region needs a way to learn who owns a record. Two common approaches:
- Embed the home region in the key. For example, an ID such as
eu-west-1:user:8841carries its owner. Lookup needs no extra call, but moving the record means changing its ID. - Keep a directory. A small, highly available mapping from key (or user) to region. It lets you move owners, at the price of one more component that every request depends on. Cache it aggressively.
The sketch below shows a router that applies a directory with an embedded fallback.
HOME_REGION = {"u100": "eu-west-1", "u200": "us-east-1"} # directory
LOCAL_REGION = "eu-west-1"
def owner_of(user_id):
"""Return the owning region, defaulting to the local region for new users."""
return HOME_REGION.get(user_id, LOCAL_REGION)
def route_write(user_id, write):
owner = owner_of(user_id)
if owner == LOCAL_REGION:
return f"applied locally: {write}"
return f"forwarded to {owner}: {write}"
print(route_write("u100", "set theme=dark")) # applied locally
print(route_write("u200", "set theme=dark")) # forwarded to us-east-1Assigning new users to the local region is a deliberate choice. It gives a new user fast writes right away, and the directory records the choice so every region agrees afterward.
What happens to a write in a non-owning region
A region that receives a write for data it does not own has three options.
- Forward the request to the owning region and return its response. The user sees one cross-region round trip, often 80 to 200 ms between continents.
- Redirect the client to the owner, for example with an HTTP 307 or by returning the owner's endpoint. This costs the client an extra request but keeps the proxy stateless.
- Reject the write with a clear error. This is acceptable for rare cases, such as a user editing a profile while abroad, if the product can tolerate it.
Notice the last arrow. After the owner commits, the change reaches the EU replica asynchronously. A read in EU immediately after the write may still return the old value. To avoid confusing the user, either read from the owner after a write, or return the new value in the write response and let the client cache it for a short time.
Reading data you do not own
Reads are the easy half. Every region can serve reads from its local replica. The catch is staleness. A replica lags the owner by the current replication delay, usually tens to hundreds of milliseconds, and much more during an incident. Choose per endpoint:
- Tolerant of staleness (product catalog, public profiles): read locally.
- Needs read-your-writes (the user just changed a setting): route to the owner for a short window after a write, or pin the session to the owner's region.
- Needs the latest value for a decision (stock check before purchase): read from the owner, or do the check as part of the owner's transaction.
Failure of an owning region
Ownership is only useful while the owner is reachable. When a region fails, its data has no writer. You have three choices, and each has a price.
- Wait. Writes to that region's data fail until it recovers. This preserves consistency but loses availability for those records. Reads continue from replicas.
- Promote another region. A replica region becomes the owner. Because replication is asynchronous, the replica may be missing the last few writes the failed region accepted. That is your RPO showing up as real lost data. If the old region later returns and still believes it is the owner, you have two writers and a split brain.
- Fail over with fencing. Promotion includes a token, such as an incrementing epoch number stored in the directory. Every write carries the epoch, and storage rejects writes with an older one. The recovered region sees its epoch is stale and stops.
class Directory:
def __init__(self):
self.owner = {"u200": ("us-east-1", 1)} # (region, epoch)
def promote(self, key, new_region):
_, epoch = self.owner[key]
self.owner[key] = (new_region, epoch + 1)
class Store:
def __init__(self, directory):
self.directory = directory
self.data = {}
def write(self, key, value, region, epoch):
owner_region, current_epoch = self.directory.owner[key]
if (region, epoch) != (owner_region, current_epoch):
raise PermissionError(f"stale owner {region} epoch {epoch}")
self.data[key] = value
d = Directory()
s = Store(d)
s.write("u200", "v1", "us-east-1", 1) # accepted
d.promote("u200", "eu-west-1") # us-east-1 failed, eu-west-1 takes over
s.write("u200", "v2", "eu-west-1", 2) # accepted
try:
s.write("u200", "v3", "us-east-1", 1) # old owner returns
except PermissionError as e:
print(e) # stale owner us-east-1 epoch 1In a real system the check must happen atomically with the write, inside the storage layer or a conditional write, not in a separate application step. Otherwise a write can pass the check just before the promotion and land just after it.
Decide in advance whether promotion is automatic or manual. Automatic promotion shortens the outage but can fire on a network partition when the old owner is still healthy. Many teams automate for per-user data, where the damage is small, and require a human for high-value data such as payments.
Hot spots and rebalancing
Ownership concentrates load. If one tenant generates a large share of writes, its owning region carries that load alone. Watch these signals:
- Write rate per owning region compared with its capacity.
- Share of writes that arrive in a non-owning region and must be forwarded. A rising share means the partition key no longer matches user behaviour.
- Directory lookup latency and cache hit rate.
To move an owner, follow a fixed order: stop writes to the key (or fence the old epoch), copy the final state, update the directory with a new epoch, then resume writes at the new owner. Move small units, such as one user, so the pause is brief.
When ownership does not fit
Some data is genuinely written from many places at once: counters, shared documents, sets of tags. Forcing one owner makes every region pay a cross-region trip for each write. For these, combine strategies. Use ownership for records with a natural home, and use a CRDT (covered in the next chapter on conflict resolution) for data that must accept concurrent writes everywhere.
Summary of trade-offs
| Property | Write ownership | Multi-writer with conflict resolution |
|---|---|---|
| Local write latency | Only for owned data | Yes, everywhere |
| Transactions and constraints | Work within the owner | Hard or impossible across regions |
| Data loss on conflict | None, writes are ordered | Possible, depending on the merge rule |
| Behaviour when the owner is down | Writes blocked or promoted | Writes continue everywhere |
| Operational burden | Directory, fencing, rebalancing | Merge logic, conflict testing |
Exercise
A user whose home region is us-east-1 travels to Europe and updates their profile through eu-west-1. Name two ways the system can handle the write and one downside of each.
Show answer
(1) Forward the write to us-east-1. The user gets a correct, ordered write, but pays a cross-region round trip, and the write fails if us-east-1 is down. (2) Reject the write or redirect the client to us-east-1. This keeps the proxy simple, but the user sees an error or extra latency. A further option, changing the user's home region, avoids repeated slow writes but requires a fenced ownership move.
Exercise
us-east-1 fails, and eu-west-1 is promoted to owner of its users' data. Later us-east-1 recovers and still accepts writes from clients with cached routing. What mechanism prevents two writers, and what must be true of how it is checked?
Show answer
A fencing token such as an epoch number. The promotion increments the epoch, every write carries its epoch, and the storage layer rejects writes with an older one. The check must be atomic with the write, for example a conditional write in the database, so no write can pass the check before the promotion and commit after it.