Replication Topologies: Leader-Follower, Multi-Leader, Leaderless Quorums, Conflict Resolution, Federation
"This requirement forces us to push the complexity of conflict resolution to the reads in order to ensure that writes are never rejected." — DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007
Summary: Replication keeps copies of the same data on several machines; the topology decides which copies may accept writes (one leader, several leaders, or any replica), and that single choice decides what can go wrong: stale reads, lost writes at failover, or write conflicts that something must resolve. Focus: Single-leader (synchronous, asynchronous, semi-synchronous), replica lag and read-your-writes, failover, promotion, split brain and fencing; multi-leader and active-active with circular, star and all-to-all topologies; leaderless Dynamo-style quorums (N, R, W, sloppy quorums, hinted handoff, read repair, anti-entropy); version vectors and conflict resolution (LWW, merge, siblings, CRDTs, OT); bounded staleness, geo-replication patterns, Redis and Kafka replication, federation and failover tooling, with a Go simulator and Laravel 13 read/write connections. Learning goal: Given a workload and a failure budget, pick the topology and its knobs, state exactly which writes can be lost or conflict and when, route reads so users see their own writes, and design the failover so that two leaders can never both accept writes.
This chapter is the system-level decision. The engine mechanics live in the database path: streaming and logical replication, pg_stat_replication, MySQL binlog/GTID replication and Patroni setup in Replication, Read Replicas & Failover; consensus (Raft, Paxos, 2PC) in Distributed SQL, Consensus & 2PC; Cassandra internals in Cassandra & ScyllaDB. The theory this page leans on has its own pages: CAP & PACELC, Consistency Models, Vector Clocks, Merkle Trees & Anti-Entropy, CRDTs, Leader Election and Sharding at System Level. Here you choose between them and wire them together.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why copies exist and what they cost | Why it exists |
| Gray, Bayou, Dynamo, Kafka, CRDTs | Where it comes from |
| One leader: sync, async, semi-sync | Single-leader |
| Stale reads, read-your-writes, monotonic reads | Replica lag |
| Promotion, split brain, STONITH, epochs | Failover and fencing |
| Active-active and its conflicts | Multi-leader, Circular, star, all-to-all |
| N, R, W and why R + W > N is not enough | Leaderless quorums, Sloppy quorums and hinted handoff, Read repair and anti-entropy |
| Detecting concurrency | Version vectors and DVVs |
| LWW, merge, siblings, CRDTs, OT | Conflict resolution |
| Lag dashboards and staleness bounds | Bounded staleness |
| Regions, home region, follow-the-sun | Geo-replication patterns |
Redis replicas, Kafka ISR and acks | Caches and queues |
| Independent clusters per tenant or region; Mastodon and Matrix | Federation |
| Patroni, Orchestrator, Vitess, ProxySQL | Failover tooling |
| Knobs, arithmetic, error messages | Mechanics |
| Code | Go, Laravel |
| Classic failures and their fixes | Solving the classic problems |
| Which topology for which workload | Choosing |
| Monolith to multi-region | In architecture |
| Simulator and engine experiments | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three topologies.
| Topology | Who accepts writes | In plain words | What goes wrong | Typical products |
|---|---|---|---|---|
| Single-leader (leader-follower, primary-replica) | One leader per dataset or partition | One cashier takes orders, the others copy the order book | Stale reads on followers; acknowledged writes lost at failover (async); split brain if the old leader is not fenced | PostgreSQL streaming replication, MySQL replication, Redis, MongoDB replica sets, Kafka partitions |
| Multi-leader (active-active) | One leader per region or device | Every branch office takes orders and posts copies to the others | Write conflicts on the same key; replication loops and out-of-order delivery | MySQL Group Replication multi-primary, DynamoDB global tables, CouchDB, pgEdge/BDR for PostgreSQL, offline-first mobile apps |
| Leaderless (Dynamo-style) | Any replica | The client writes to several notebooks and reads several, trusting the newest | Stale reads when R + W is not greater than N, sloppy quorums, LWW data loss, deleted data coming back | Cassandra, ScyllaDB, Riak, Amazon Dynamo (the 2007 paper; DynamoDB is a different design) |
The four guarantees people actually ask for.
| Guarantee | Question | Who breaks it | Cheapest fix |
|---|---|---|---|
| Durability of acknowledged writes | "If you said OK, will it survive a crash?" | Async replication + failover | Synchronous or semi-synchronous commit to one more node; Kafka acks=all + min.insync.replicas=2 |
| Read-your-writes | "Do I see what I just saved?" | Reading a lagging follower | Route the user's reads to the leader for a few seconds, or to a replica that replayed the user's LSN/GTID |
| Monotonic reads | "Can the page go back in time on refresh?" | Reading a different, more-lagging replica each time | Pin a session to one replica, or carry a minimum position |
| Single writer | "Can two nodes both believe they lead?" | Partition + failover without fencing | Fencing (STONITH, leases, epochs, fencing tokens) |
Conflict resolution in one table.
| Strategy | What it keeps | Loses data? | Where you meet it |
|---|---|---|---|
| Last-writer-wins (LWW) | The write with the highest timestamp | Yes, silently: every concurrent loser | Cassandra (per cell), DynamoDB global tables (MREC), Riak with allow_mult=false |
| Application merge | What your code computes from all versions | No, if the merge is right | Dynamo shopping cart, CouchDB conflict documents |
| Siblings (keep all) | Every concurrent version, returned on read | No, but readers must resolve | Riak with allow_mult=true and dotted version vectors |
| CRDT | A merge that is mathematically order-free | No, for the operations the type supports | Riak data types, Redis Enterprise Active-Active, Automerge/Yjs |
| Operational transformation (OT) | Each edit, transformed against concurrent edits by a server | No, for text-like data | Google Docs style collaborative editing |
| Avoid conflicts | One writer per key: home region, single-leader per partition | Nothing to resolve | Region pinning, CockroachDB REGIONAL BY ROW |
Why it exists
One machine is a single point of failure, sits in one place on the planet and serves a finite number of reads. Copies fix all three: a follower can take over (availability), a copy near the user cuts latency (geography), and several copies serve more reads (scale). The cost is that the copies are never all equal at the same instant, and the system must decide what a reader sees and what a writer is promised while they differ.
| Choice | Simpler, faster | Safer, slower |
|---|---|---|
| When to acknowledge a write | After the leader's local commit (asynchronous) | After one or more replicas have it (semi-sync, synchronous, quorum) |
| Who may write | One leader (no conflicts) | Many leaders or any replica (no single bottleneck, but conflicts) |
| Where to read | Any replica (stale) | Leader or a replica proven fresh enough (more load, more latency) |
| How to resolve concurrent writes | Last-writer-wins (data loss) | Version vectors + merge or CRDTs (complexity) |
| How to fail over | Automatic on timeout (fast, risk of split brain) | Fenced, consensus-based (slower, safe) |
The everyday picture used through this page: a restaurant chain's booking book. One head office book that branches phone into is single-leader; every branch keeping its own book and faxing changes to the others is multi-leader; and writing the booking in three of five shared notebooks and reading three before answering is leaderless. The problems follow from the picture: a branch reading a stale fax (lag), two branches booking the last table (conflict), and the head office phone going dead while a deputy starts taking bookings and the old office later wakes up still taking them (split brain).
Three common misunderstandings, up front
- "Replication is a backup." A
DROP TABLEor a buggy migration replicates in milliseconds. Backups and point-in-time recovery are a separate concern: Backup, PITR & Disaster Recovery. - "Synchronous replication means replicas are always up to date for reads." PostgreSQL's default synchronous commit waits for the standby to flush WAL, not to replay it; a read on that standby can still miss the row unless you use
synchronous_commit = remote_apply. - "A quorum (R + W > N) makes reads linearizable." Sloppy quorums, concurrent writes, LWW clock skew, failed writes that partially succeeded and replicas restored from old data all break it. Quorums give "usually fresh", not a linearizability guarantee; see Consistency Models.
Where it comes from
- 1980s, primary-copy and log shipping. Database replication grew from shipping the recovery log to a standby; the leader/follower vocabulary and the "who is primary" problem are as old as hot standbys. Jim Gray, Pat Helland, Patrick O'Neil and Dennis Shasha's The Dangers of Replication and a Solution (SIGMOD 1996) showed that update-anywhere (multi-leader) replication's reconciliation rate grows quickly with the number of nodes, which is why most databases stayed single-leader.
- 1994–1995, Bayou (Xerox PARC). Weakly connected, multi-leader replication for mobile devices, with application-supplied conflict detection and merge procedures and the session guarantees (read-your-writes, monotonic reads, writes-follow-reads, monotonic writes) of Terry et al. 1994.
- 2007, Dynamo. Amazon's paper combined consistent hashing, N/R/W quorums, sloppy quorums with hinted handoff, vector clocks and Merkle-tree anti-entropy for an "always writeable" store; the opening quote is its design stance. Cassandra (2008) and Riak (2009) followed, Cassandra replacing vector clocks with per-cell last-write-wins timestamps.
- 2011, CRDTs. Shapiro, Preguiça, Baquero and Zawirski formalised conflict-free replicated data types, giving multi-leader systems merges that do not depend on order. Riak 2.0 shipped them, together with dotted version vectors.
- 2011 onwards, the log as the replication primitive. Kafka replicates each partition with a leader and an in-sync replica set (ISR); consensus-based systems (Raft in etcd, CockroachDB, TiDB; Paxos in Spanner) made single-leader-per-range with automatic, fenced failover the default for new distributed SQL.
- 2016 onwards, federation in the open. ActivityPub (W3C Recommendation, 2018, used by Mastodon) and Matrix federate independent servers instead of replicating one database, a deliberate contrast to replication inside one organisation.
- Today's synthesis is Kleppmann's Designing Data-Intensive Applications (ch. 5, Replication), which organises the field into exactly the three topologies used here.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, how products provide it, and the fix.
Single-leader replication: synchronous, asynchronous, semi-synchronous Must-know
In plain words: one node (the leader, primary or source) accepts every write and sends a stream of changes to the others (followers, replicas, standbys), which apply it in the same order and serve reads.
Common misunderstanding: "If the client got OK, the data is on two machines." Only if the commit waited for a replica. PostgreSQL's docs are explicit: "PostgreSQL streaming replication is asynchronous by default"; MySQL replication is asynchronous by default too, and Redis "uses by default asynchronous replication".
Definition: a topology where exactly one node per dataset (or per partition) orders all writes. The acknowledgement mode decides durability:
- Asynchronous replication: the leader acknowledges after its own commit; followers catch up later. Fast and available, loses the unshipped tail on failover.
- Synchronous replication: the commit waits until one or more named standbys confirm. PostgreSQL waits "until confirmation is received that the commit has been written to the write-ahead log on disk of both the primary and standby server".
- Semi-synchronous: the commit waits for at least one replica to receive (and, in MySQL's
AFTER_SYNCmode, persist to its relay log) the change, then falls back to asynchronous after a timeout (rpl_semi_sync_source_timeout, 10 s by default) so that a dead replica does not stop writes. - Quorum commit: wait for any k of n standbys (
synchronous_standby_names = 'ANY 1 (a, b)'), so one slow standby does not stall commits.
Client Leader (PostgreSQL) Standby A (sync) Standby B (async)
1 COMMIT -> write WAL, fsync
2 ship WAL -> receive, fsync
3 <- flush confirmed
4 <- COMMIT OK (synchronous_commit = on)
5 ship WAL ------------------------------------------> receives 200 ms later
6 reads on A may still miss the row until A replays it (remote_apply waits for that)Real scenario: a payments ledger that must not lose an acknowledged transfer (synchronous to one standby in another availability zone); a product catalogue with ten read replicas (asynchronous, staleness is fine); a SaaS app where losing the last second of writes on a rare failover is acceptable but a stalled primary is not (semi-sync with timeout).
What provides it:
| Product | Default | Stronger option | Knob |
|---|---|---|---|
| PostgreSQL | Asynchronous streaming | Sync / quorum commit; remote_write, on, remote_apply | synchronous_standby_names, synchronous_commit |
| MySQL 8.4 | Asynchronous binlog replication | Semi-sync plugin; Group Replication (Paxos-based) | rpl_semi_sync_source_wait_point=AFTER_SYNC |
| Redis | Asynchronous | WAIT numreplicas timeout per write; refuse writes when replicas are stale | min-replicas-to-write, min-replicas-max-lag |
| MongoDB | Majority write concern since 5.0 | w: "majority", j: true | write concern per operation |
| Kafka | acks=all since 3.0 producers | min.insync.replicas=2 on the topic | acks, min.insync.replicas |
| CockroachDB, Spanner, etcd | Raft/Paxos majority per range | Built in | Not optional: consensus replication |
Fix / how to use it: decide per dataset how many machines must have a write before the user sees OK, and configure exactly that. Put one synchronous (or quorum) copy in a different availability zone for anything financial; leave read replicas asynchronous; let individual low-value transactions opt out (SET LOCAL synchronous_commit = 'local'). The SQL for all of this:
-- PostgreSQL: synchronous replication, lag monitoring and read-your-writes.
-- 1. On the primary: commit waits for any 1 of two standbys (quorum commit).
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (replica_a, replica_b)';
ALTER SYSTEM SET synchronous_commit = 'on'; -- remote_write | remote_apply | local | off
SELECT pg_reload_conf();
-- A single transaction may relax it (bulk import, analytics staging):
BEGIN;
SET LOCAL synchronous_commit = 'local';
INSERT INTO audit_events (kind, payload) VALUES ('import', '{}');
COMMIT;
-- 2. On the primary: who is connected, how far behind, sync or async.
SELECT application_name,
state, -- streaming | catchup | backup
sync_state, -- sync | quorum | potential | async
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_bytes_behind,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication
ORDER BY application_name;
-- 3. On a replica: how stale am I?
SELECT pg_is_in_recovery() AS is_replica,
pg_last_wal_receive_lsn() AS received,
pg_last_wal_replay_lsn() AS replayed,
CASE WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
ELSE EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp())
END AS lag_seconds;
-- 4. Read-your-writes by position: after the user's commit on the primary ...
SELECT pg_current_wal_lsn()::text; -- e.g. 16/B374D848 -> session
-- ... and on the replica before serving that user's read:
SELECT pg_last_wal_replay_lsn() >= '16/B374D848'::pg_lsn AS caught_up;
-- 5. Logical replication (per-table, cross-version, the basis of most multi-leader add-ons).
CREATE PUBLICATION orders_pub FOR TABLE orders, order_lines;
-- on the subscriber:
-- CREATE SUBSCRIPTION orders_sub CONNECTION 'host=192.0.2.10 dbname=shop user=repl'
-- PUBLICATION orders_pub;
-- 6. Promotion (what Patroni does for you, after fencing the old primary).
-- SELECT pg_promote(wait => true, wait_seconds => 60);-- MySQL 8.4: semi-synchronous replication, lag, and read-your-writes by GTID.
-- On the source (plugin names and variables use the 8.4 "source/replica" terms).
INSTALL PLUGIN rpl_semi_sync_source SONAME 'semisync_source.so';
SET PERSIST rpl_semi_sync_source_enabled = ON;
SET PERSIST rpl_semi_sync_source_wait_for_replica_count = 1;
SET PERSIST rpl_semi_sync_source_wait_point = 'AFTER_SYNC'; -- lossless variant
SET PERSIST rpl_semi_sync_source_timeout = 10000; -- ms, then falls back to async
-- On each replica.
INSTALL PLUGIN rpl_semi_sync_replica SONAME 'semisync_replica.so';
SET PERSIST rpl_semi_sync_replica_enabled = ON;
SET PERSIST super_read_only = ON; -- replicas refuse client writes
-- Is semi-sync actually on right now, or did it time out to async?
SHOW STATUS LIKE 'Rpl_semi_sync_source_status';
-- Lag on a replica (Seconds_Behind_Source, Retrieved/Executed_Gtid_Set).
SHOW REPLICA STATUS;
-- Read-your-writes: after the write, the app keeps the GTID set it produced ...
SELECT @@GLOBAL.gtid_executed;
-- ... and on the replica waits up to 1 s for it before reading (0 = reached, 1 = timeout).
SELECT WAIT_FOR_EXECUTED_GTID_SET('3E11FA47-71CA-11E1-9E33-C80AA9429562:1-77', 1);Replica lag, read-your-writes and monotonic reads Must-know
In plain words: an asynchronous follower is a little behind, usually milliseconds, sometimes minutes. Reading from it can show the past: your own order missing, a counter going backwards, a reply before the question.
Common misunderstanding: "Our lag is 50 ms, so nobody will notice." Lag is a distribution with a long tail: a long-running query on the replica, a vacuum, a big UPDATE, a network blip or a replica restart pushes it to seconds or minutes, and the redirect after a form submit arrives within one network round trip.
Definition: replica lag is the distance between the leader's latest committed position and the follower's replayed position, measured in bytes (pg_wal_lsn_diff), transactions (GTID sets) or time (replay_lag, Seconds_Behind_Source). Three client-centric guarantees fight its symptoms:
- Read-your-writes (read-after-write consistency): a user always sees their own committed writes.
- Monotonic reads: a user never sees an older state after having seen a newer one.
- Consistent prefix reads: a reader sees writes in an order that respects causality (no answer before the question), the concern of partitioned systems.
Browser Leader Replica (lag 800 ms)
1 POST /checkout -> INSERT order 1001; COMMIT
2 <- 303 See Other /orders/1001
3 GET /orders/1001 -------------------------------------> SELECT ... id = 1001 -> no row
4 <- 404 "order not found" (replays 1001 at t = 800 ms)
5 refresh lands on replica 2 (lag 50 ms) -> sees 1001; refresh again on replica 1 -> 404 (not monotonic)Real scenario: "order not found" after checkout; a user changes a password and the next request still accepts the old one (auth reads from a replica); a comment that disappears on refresh; a support agent who closes a ticket and still sees it open; an inventory check that oversells because the replica has the old stock.
What provides it:
| Technique | How | Products |
|---|---|---|
| Read from leader after a write | Session flag for N seconds | Laravel 'sticky' => true (same request), PreventStaleDatabaseReads middleware (same session, 2 s default) |
| Position tracking | Store the commit LSN/GTID, read only from a replica past it | PostgreSQL pg_current_wal_lsn() / pg_last_wal_replay_lsn(); MySQL WAIT_FOR_EXECUTED_GTID_SET |
| Commit waits for replay | Replicas are fresh at commit time | PostgreSQL synchronous_commit = remote_apply |
| Session pinning | Same replica for the whole session (monotonic reads) | Consistent hashing on session ID in ProxySQL or the app router |
| Causal tokens | Database tracks it | MongoDB causally consistent sessions; CockroachDB/Spanner are linearizable by default |
Fix / how to use it: classify every read as fresh (money, stock, permissions, the page right after a write), bounded (a few seconds stale is fine) or stale-tolerant (lists, search, reports) and route accordingly. The position check behind read-your-writes is two queries:
-- on the primary, right after the user's COMMIT: keep this in the session
SELECT pg_current_wal_lsn()::text AS commit_lsn; -- 16/B374D848
-- on a candidate replica, before serving that user's read
SELECT pg_last_wal_replay_lsn() >= '16/B374D848'::pg_lsn AS caught_up;
-- MySQL equivalent: wait up to 1 s for the GTID set the write produced
SELECT WAIT_FOR_EXECUTED_GTID_SET('3E11FA47-71CA-11E1-9E33-C80AA9429562:1-77', 1);The Go router and the Laravel replica-aware repository do exactly that.
Failover, promotion, split brain and fencing Must-know
In plain words: when the leader dies, a follower is promoted. The hard parts are deciding that it is really dead, choosing the follower with the most data, and making sure the old leader can never accept another write.
Common misunderstanding: "If the old primary is down, it cannot write." It may only be unreachable from you: a partition, a GC pause, a saturated NIC. PostgreSQL's docs warn that you need "a mechanism for informing the old primary that it is no longer the primary", known as STONITH, "to avoid situations where both systems think they are the primary, which will lead to confusion and ultimately data loss."
Definition:
- Failover: detect the failure (heartbeats, a lease in etcd/Consul/ZooKeeper that expires), choose a candidate (the most advanced replica within a lag bound), promote it (
pg_ctl promote,pg_promote(),STOP REPLICA; RESET REPLICA ALL), repoint the others and the clients (VIP, DNS, proxy, service discovery). - Split brain: two nodes accept writes for the same data at the same time; their histories diverge and one side's writes must later be discarded or hand-merged.
- Fencing: making the old leader harmless. STONITH ("shoot the other node in the head": power off through IPMI or the cloud API), revoking its lease, a watchdog that reboots a primary that cannot renew its lease, blocking its port, or an epoch / fencing token that storage and followers check, rejecting anything from a lower epoch (see Distributed Locking for fencing tokens).
- Switchover: a planned, clean promotion (maintenance); no data loss because the old leader stops first.
t Old leader N0 Failover manager (Patroni + etcd) Follower N1
1 0 s holds leader key, ttl 30 s
2 5 s partitioned from etcd and N1; clients in its zone still connect
3 35 s leader key expired
4 36 s N1 lag 0.4 MB <= maximum_lag_on_failover -> promote N1 (timeline 2)
5 36 s watchdog: could not renew -> demote / reboot itself (fenced)
6 without step 5: N0 accepts "seat 12A = alice" while N1 accepts "seat 12A = bob"
7 heal: N0 must be rewound (pg_rewind) to N1's timeline; alice's booking is goneReal scenario: an AWS availability-zone network event isolates the primary for 90 seconds; a VM live-migration freezes the primary for 40 seconds and it wakes up still believing it leads; a two-node cluster with no witness where each node sees the other as dead; a manual failover where the operator forgot to stop the old primary's application traffic; a Redis Sentinel failover that loses the last second of writes.
What provides it:
| Product | Detection | Promotion | Fencing | Data-loss bound |
|---|---|---|---|---|
| PostgreSQL + Patroni | Leader key TTL in etcd/Consul/ZooKeeper/Kubernetes | Most advanced healthy replica | Self-demotion when the key cannot be renewed; Linux watchdog (mode: required) | maximum_lag_on_failover bytes, or none with synchronous_mode |
| MySQL + Orchestrator | Holistic: replicas also cannot see the source | Best replica by GTID position | Hooks (PreFailoverProcesses), super_read_only on the old source | Semi-sync AFTER_SYNC: none for acknowledged writes |
| MySQL Group Replication | Group membership (Paxos) | Automatic primary election in single-primary mode | Minority partition stops accepting writes | None for committed transactions |
| Redis Sentinel / Cluster | Quorum of sentinels / masters | Replica with the best offset | min-replicas-to-write limits the window on an isolated master | Up to the async lag |
| Kafka (KRaft) | Controller sees the broker session end | First live replica in the ISR | Leader epoch on every fetch and produce | None for acks=all with min.insync.replicas=2, unless unclean election is enabled |
| Raft systems (etcd, CockroachDB) | Election timeout | Candidate with the most up-to-date log wins a majority | Term numbers; leases | None for committed entries |
Fix / how to use it: never fail over without fencing; prefer a consensus store (etcd, Consul, ZooKeeper) or built-in consensus over two-node heartbeats; bound the data-loss window (synchronous standby or maximum_lag_on_failover); practise switchovers monthly; after failover, rewind or re-clone the old leader, never just "start it again". Patroni's configuration is the reference shape:
# Patroni (excerpt): leader election via a DCS, failover limits, fencing.
scope: shop
name: pg-eu-1
etcd3:
hosts: 192.0.2.51:2379,192.0.2.52:2379,192.0.2.53:2379
bootstrap:
dcs:
ttl: 30 # leader key lease in the DCS
loop_wait: 10
retry_timeout: 10
maximum_lag_on_failover: 1048576 # bytes; a replica further behind is not promoted
synchronous_mode: true # promote only a replica known to hold every acked commit
synchronous_mode_strict: false # true: block writes rather than run without a sync standby
postgresql:
use_pg_rewind: true # rewind a former primary instead of re-cloning it
parameters:
wal_level: replica
hot_standby: "on"
max_wal_senders: 10
watchdog:
mode: required # Linux watchdog reboots a primary that cannot demote itself
device: /dev/watchdog
tags:
nofailover: false
noloadbalance: falseMulti-leader replication and active-active Important
In plain words: more than one node accepts writes, typically one per region (or each user's laptop and phone), and each forwards its changes to the others asynchronously.
Common misunderstanding: "Active-active gives us strong consistency in two regions." Two leaders that accept writes without waiting for each other can both accept conflicting writes; the speed of light means a cross-region synchronous write costs 70–150 ms per round trip, which is exactly what active-active was meant to avoid.
Definition: a topology with two or more leaders, each a single-leader cluster for its local followers, exchanging changes asynchronously. Every write must carry enough metadata (origin, version, timestamp) for the others to detect a write conflict, which is two concurrent writes to the same key, and to resolve it identically on every node so that the copies converge.
t EU leader US leader
1 0 ms UPDATE profile 9 SET name = 'Ana Silva' UPDATE profile 9 SET name = 'Ana S.'
2 0 ms COMMIT, user sees OK COMMIT, user sees OK
3 80 ms receives US change: base version differs -> conflict
4 80 ms receives EU change: conflict
5 both apply the same rule (LWW: higher timestamp, tie-break by region id) -> 'Ana S.'
6 'Ana Silva' is gone and neither user was toldReal scenario: a SaaS product with EU and US data centres where users write locally; offline-first mobile apps (each device is a leader; sync on reconnect); calendar and notes apps on laptop and phone; collaborative editing (every client is a leader with real-time sync); retail point-of-sale terminals that keep selling while the link to head office is down.
What provides it:
| Product | Multi-leader feature | Conflict handling |
|---|---|---|
| MySQL Group Replication | Multi-primary mode | Certification: conflicting transactions on the same rows are rolled back on commit (first committer wins) |
| DynamoDB global tables (MREC) | Every replica region writable | "last writer wins" per item on the latest internal timestamp |
| DynamoDB global tables (MRSC) | Synchronous multi-region replication | A concurrent conflicting write fails with ReplicatedWriteConflictException (retriable) |
| PostgreSQL | Logical replication both ways; pgEdge Spock, EDB BDR (Postgres Distributed) | Configurable: last-update-wins, keep-local, custom handlers |
| CouchDB / PouchDB | Master-master sync | Deterministic winner plus conflict list readable by the app |
| Redis Enterprise Active-Active | CRDT-based geo-replication | CRDT semantics per data type |
| Cassandra multi-DC | Every DC writable | Per-cell LWW timestamps |
Fix / how to use it: first try to avoid conflicts: give every key a home (one region or one user owns it) and route its writes there (Geo-replication patterns). Where concurrent writes are inherent (offline devices, collaboration), model the data so that writes commute (append-only events, per-origin counters, CRDTs) and test the merge function. Use LWW only for data where losing one of two concurrent writes is acceptable (a "last seen" timestamp, a cache).
Multi-leader topologies: circular, star, all-to-all Good to know
In plain words: with more than two leaders you must decide which leader sends to which: around a ring, through a hub, or everyone to everyone.
Common misunderstanding: "All-to-all is strictly better because it has no single point of failure." It is more fault-tolerant, but changes race over different links, so a node can receive an update to a row before the insert that created it; that needs causal ordering (version vectors), not arrival order.
Definition:
- Circular topology: each leader forwards its own and received changes to the next; changes are tagged with the IDs of nodes they passed to stop loops. One failed node breaks the ring until it is reconfigured (classic MySQL circular replication).
- Star topology: one hub relays to all spokes (a tree in general). Easy to reason about; the hub is a single point of failure and two hops of latency.
- All-to-all topology (mesh): every leader sends to every other. Survives any single failure; needs causality tracking because messages overtake each other.
All-to-all with 3 leaders; L1 -> L3 link is slow
1 L1: INSERT row 7
2 L2: receives INSERT from L1 at 20 ms, then UPDATE row 7 (sends to L1 and L3)
3 L3: receives L2's UPDATE row 7 at 30 ms -> row does not exist yet
4 L3: receives L1's INSERT row 7 at 200 ms
5 without version vectors L3 either errors at step 3 or ends with the INSERT's old valuesReal scenario: a three-region active-active deployment (all-to-all, the default of DynamoDB global tables and Group Replication); branch offices that sync through head office (star); legacy MySQL rings that broke whenever one server was down for maintenance (circular).
| Topology | Fault tolerance | Ordering risk | Latency | Use |
|---|---|---|---|---|
| Circular | One failure stops propagation | Low (single path) | Up to n-1 hops | Avoid; legacy MySQL rings |
| Star / tree | Hub failure stops propagation | Low | Two hops | Hub-and-spoke sync (head office, cloud hub for devices) |
| All-to-all | Any single failure tolerated | High: needs version vectors | One hop | Multi-region active-active |
Fix / how to use it: prefer all-to-all with per-key version vectors (or a CRDT) and idempotent, origin-tagged changes; if you must use a ring or star, monitor the hub/ring health and automate reconfiguration.
Leaderless replication and quorums: N, R, W Must-know
In plain words: there is no leader. The client (or any node acting as coordinator) sends a write to all N replicas of the key and waits for W acknowledgements; a read asks replicas and waits for R answers, keeping the newest.
Common misunderstanding: "W=2 means the write went to only two nodes." Cassandra's docs: "Write operations are always sent to all replicas, regardless of consistency level. The consistency level simply controls how many responses the coordinator waits for." A failed W=2 write may still be on one replica, and a later read can return it.
Definition: Dynamo's protocol: "R is the minimum number of nodes that must participate in a successful read operation. W is the minimum number of nodes that must participate in a successful write operation. Setting R and W such that R + W > N yields a quorum-like system." With N=3, W=2, R=2 every read set overlaps every write set in at least one node. Latency "is dictated by the slowest of the R (or W) replicas", which is why R and W are usually below N.
N = 3 (A, B, C), W = 2, R = 2
1 coordinator -> A, B, C : PUT cart:5 = v2
2 A ack, B ack -> success (W = 2); C is slow, receives v2 later
3 reader -> B, C : GET cart:5
4 B returns v2, C returns v1 -> newest (v2) wins; coordinator writes v2 back to C (read repair)
5 with W = 1, R = 1 the reader may ask only C and get v1: fast but staleReal scenario: shopping carts and session stores that must accept writes during partial outages; time-series and IoT ingestion where W=1 is fine; user-profile reads at LOCAL_QUORUM so one dead node per data centre does not matter; tuning a hot table to R=1, W=ALL for read-heavy data.
What provides it:
| Cassandra / ScyllaDB level | Waits for | Note |
|---|---|---|
ONE, TWO, THREE | That many replicas | ONE read + ONE write: no overlap |
QUORUM | Majority of all replicas: n/2 + 1 | Crosses data centres |
LOCAL_QUORUM | Majority in the coordinator's DC | The usual multi-DC choice |
EACH_QUORUM | Majority in every DC | Writes only in practice; slow |
LOCAL_ONE | One replica, never remote | Cheapest read |
ALL | Every replica | Any replica down fails the request |
ANY | One replica or a stored hint | Writes only; weakest durability |
Fix / how to use it: pick levels per query so that read and write sets overlap when you need freshness (LOCAL_QUORUM both ways in each DC), keep clocks synchronized if the store resolves with timestamps, and make writes idempotent so that a timeout-then-retry is safe.
-- Cassandra: leaderless replication per datacenter, tunable consistency.
CREATE KEYSPACE shop
WITH replication = {'class': 'NetworkTopologyStrategy', 'eu-west': 3, 'us-east': 3};
CREATE TABLE shop.carts (
cart_id uuid,
sku text,
qty int,
PRIMARY KEY (cart_id, sku)
) WITH read_repair = 'BLOCKING'; -- or 'NONE' for write atomicity of partitions
-- cqlsh: LOCAL_QUORUM = 2 of the 3 replicas in the coordinator's DC.
CONSISTENCY LOCAL_QUORUM;
INSERT INTO shop.carts (cart_id, sku, qty) VALUES (5b6962dd-3f90-4c93-8f61-eabfb4a03e78, 'book', 1);
SELECT * FROM shop.carts WHERE cart_id = 5b6962dd-3f90-4c93-8f61-eabfb4a03e78;
-- Anti-entropy (Merkle-tree repair), run on a schedule shorter than gc_grace_seconds:
-- nodetool repair -pr shop
-- Hinted handoff window (cassandra.yaml): max_hint_window: 3hSloppy quorums and hinted handoff Important
In plain words: if some of a key's home replicas are unreachable, the coordinator stores the write on other healthy nodes with a note saying who it really belongs to, and those nodes forward it when the owner comes back.
Common misunderstanding: "A sloppy quorum is still a quorum." It is not: the W nodes that acknowledged may not be among the N home replicas, so a strict R-quorum read can miss the write until the hints are delivered.
Definition: Dynamo: "it does not enforce strict quorum membership and instead it uses a 'sloppy quorum'; all read and write operations are performed on the first N healthy nodes from the preference list". The substitute keeps the replica with "a hint in its metadata that suggests which node was the intended recipient" and delivers it on recovery: hinted handoff. Cassandra keeps hints on the coordinator for up to max_hint_window (3 hours by default); a node down longer than that needs a full repair.
N = 3: home replicas A, B, C; D is the next healthy node; W = 2
1 A is down; write cart:5 = v3 goes to B (ack) and D (ack, hint "for A")
2 success: W = 2 acknowledgements, but only one home replica (B) has v3
3 read R = 2 from A's partner C and A (A back, not yet hinted) -> returns v2: stale
4 D detects A is up, hands v3 to A, deletes its copy
5 down longer than max_hint_window (Cassandra: 3 h) -> hints dropped, run nodetool repairReal scenario: a rack or AZ outage in Cassandra where writes keep succeeding; a rolling restart where every node is briefly down; a node replaced after a disk failure (hints expired, repair required).
| Product | Sloppy quorum? | Hint storage | Window |
|---|---|---|---|
| Amazon Dynamo (paper) | Yes | Separate local store on the substitute node | Until delivered |
| Cassandra | Hints, but consistency levels count only home replicas (except ANY) | Coordinator's hints directory | max_hint_window, 3 h default |
| Riak | Yes (fallback vnodes) | Fallback partition | Until handoff |
| ScyllaDB | Hints like Cassandra | Coordinator | max_hint_window_in_ms |
Fix / how to use it: treat hinted handoff as a latency optimisation for short outages, never as the repair mechanism; schedule anti-entropy repair; alert on hint backlog and on nodes down longer than the hint window.
Read repair and anti-entropy with Merkle trees Important
In plain words: replicas drift. Read repair fixes the keys people read; anti-entropy compares whole replicas in the background and fixes the rest.
Common misunderstanding: "Read repair will eventually fix everything." Keys nobody reads are never repaired, and a deleted key whose tombstone was purged before every replica saw it comes back to life ("zombie" data).
Definition:
- Read repair: when a read sees differing versions among the replicas it asked, the coordinator writes the newest back to the stale ones. Cassandra's
read_repairtable option isBLOCKING(default; the read waits for the repair, giving monotonic quorum reads) orNONE. - Anti-entropy: a background process that compares replicas. Dynamo, Cassandra (
nodetool repair) and Riak (active anti-entropy) build Merkle trees, "a hierarchy of hashes" (Cassandra docs), per token range and exchange only the subtrees whose hashes differ. Mechanics: Merkle Trees, Read Repair, Anti-Entropy & Tombstones.
1 reader asks B and C for cart:5 at QUORUM
2 B: v3 (ts 1700000003), C: v2 (ts 1700000002)
3 coordinator returns v3, writes v3 to C before answering (BLOCKING read repair)
4 nightly: nodetool repair -pr builds Merkle trees for each range on A, B, C
5 roots differ for range 7 -> compare children -> 3 leaf ranges differ -> stream only those rowsReal scenario: a node returns after a 6-hour outage (hints expired); tombstones in Cassandra must reach every replica within gc_grace_seconds (10 days default) or deleted rows resurrect; a ScyllaDB cluster where repair is automated by Scylla Manager.
Fix / how to use it: run repair on every node at least once per gc_grace_seconds; keep read repair on for quorum reads that need monotonicity; watch repair duration as data grows.
Version vectors and dotted version vectors Must-know
In plain words: each version of a value carries a small table "node A has made 3 writes, node B 1 write". Comparing two tables tells you whether one version already includes the other (just replace) or whether they were written without seeing each other (a conflict).
Common misunderstanding: "Timestamps tell us which write is newer." Wall clocks drift, and "newer" is the wrong question: two writes that did not see each other are concurrent whatever their clocks say. Only causal metadata can tell concurrency from succession; see Vector Clocks.
Definition: a version vector is a map from replica ID to a counter, one per object. a dominates b if every counter in a is greater than or equal to b's; if neither dominates, the versions are concurrent. Dynamo: "A vector clock is effectively a list of (node, counter) pairs." The client reads a value with its context (the merged vector) and sends it back with the next write, so the server knows which versions the write replaces. Dotted version vectors (DVVs) add the exact "dot" (node, counter) of each write, which stops the sibling explosion that plain vectors cause when many clients write through the same server; Riak recommends them: DVVs "are far better at limiting the number of siblings produced in a cluster".
Replica EU Replica US
1 PUT cart {book} -> [eu:1]
2 replicate [eu:1] -> has [eu:1]
3 PUT {book,pen} ctx [eu:1] -> [eu:2] PUT {book,lamp} ctx [eu:1] -> [eu:1, us:1]
4 receives [eu:1, us:1]: neither dominates [eu:2] -> keep both as siblings
5 reader gets 2 siblings + context [eu:2, us:1]; app merges -> {book,pen,lamp}
6 PUT merged ctx [eu:2, us:1] -> [eu:3, us:1] dominates both -> siblings collapseReal scenario: the Dynamo shopping cart (merge on read); Riak buckets with allow_mult=true; CouchDB revision trees; detecting conflicting edits in an offline-first app before choosing a merge.
Fix / how to use it: in your own multi-leader code, carry a version vector per object, send the context back with every write, and keep concurrent versions until a merge resolves them. The Go version-vector cart implements exactly this timeline and its tests.
Conflict resolution: LWW, merge, siblings, CRDTs, OT Must-know
In plain words: once two concurrent versions exist, something must turn them into one. You can throw one away (LWW), let the application combine them (merge), give both to the reader (siblings), use a data type whose merge is automatic (CRDT), or transform edits against each other on a server (OT).
Common misunderstanding: "LWW is safe because the last write is the one the user wanted." "Last" means "highest timestamp", which with skewed clocks may be the earlier write, and with concurrent writes discards one user's change without an error. Cassandra and DynamoDB global tables do this by design.
Definition:
- Last-writer-wins (LWW): keep the version with the highest timestamp (tie-break by node ID). Converges, loses data. Cassandra "uses a simpler last-write-wins model where every mutation is timestamped (including deletes)". DynamoDB MREC: "referred to as a 'last writer wins' conflict resolution method".
- Application merge (semantic reconciliation): read all versions, compute one. Dynamo's cart unions items, so "an 'add to cart' operation is never lost. However, deleted items can resurface."
- Siblings (keep all): store every concurrent version and return them all; the reader merges and writes back with the context. Riak:
allow_mult=truecreates "sibling values, aka siblings". - CRDTs: counters, sets, maps and registers whose merge is commutative, associative and idempotent, so replicas converge without coordination. Mechanics: CRDTs.
- Operational transformation (OT): a central server orders concurrent edit operations and transforms each against those it did not see (insert at 5 becomes insert at 8 after a concurrent 3-character insert). Used by Google Docs-style editors; CRDTs (Automerge, Yjs) are the decentralised alternative.
- Conflict avoidance: route all writes for a key to one leader. The most effective strategy of all.
LWW with skewed clocks: US clock is 2 s behind
1 10:00:00.000 EU SET stock:42 = 0 (sold the last one) ts = 10:00:00.000
2 10:00:00.500 US SET stock:42 = 5 (restock arrives) ts = 09:59:58.500 (skew)
3 replicate: EU keeps 0 (higher ts), US switches to 0
4 the restock is lost, although it happened later in real timeReal scenario: a user's profile edited on phone and laptop (LWW per field is usually acceptable); a shopping cart (union merge, accepting resurrected deletions, or an OR-Set CRDT that handles removals); a like counter (PN-counter CRDT); collaborative text (OT or a sequence CRDT); bank balances (never multi-leader: single-leader per account).
| Strategy | Loses writes | Developer effort | Read cost | Best for |
|---|---|---|---|---|
| LWW | Yes | None | Low | Caches, "last seen", idempotent overwrites |
| Merge in app | No (if correct) | High: custom per type | Medium | Carts, documents with known structure |
| Siblings | No | High: every reader resolves | High: many versions | Riak-style stores with rich merges |
| CRDT | No (per type semantics) | Medium: choose types | Medium | Counters, sets, collaborative state |
| OT | No | High: transformation functions + server | Low | Real-time text editing |
| Avoidance | Nothing to lose | Routing work | Low | Almost every business system |
Fix / how to use it: default to conflict avoidance (single leader per key); use CRDTs for counters and sets; use LWW only where a lost concurrent write is harmless; when you merge, write the merge as a pure function and test it with concurrent histories like the Go tests do.
Replication lag monitoring and bounded staleness Important
In plain words: measure how far behind each copy is, alert on it, and give readers a contract: "this read is at most 5 seconds old, otherwise it goes to the leader".
Common misunderstanding: "Seconds_Behind_Source is the lag." It measures the timestamp of the event the SQL thread is applying, so it reads 0 when the replica has stopped receiving anything; and replay_lag in PostgreSQL is empty when the primary is idle. Measure with both positions and a heartbeat row.
Definition: bounded staleness is a consistency level in which reads may lag the latest write by at most a time (or version) bound. Azure Cosmos DB offers it by name; CockroachDB offers AS OF SYSTEM TIME with_max_staleness('10s'); in a home-grown setup the router enforces it from measured lag.
Router poll every 1 s Read with policy "bounded 2 s"
1 replica-a: replay lag 0.3 s, LSN 16/B3... -> eligible
2 replica-b: replay lag 7.9 s (long query) -> excluded
3 user's last write LSN 16/B4... > replica-a LSN -> read-your-writes fails on a
4 no replica qualifies -> read goes to the primary
5 alert: replica-b lag > 5 s for 2 min (and pg_stat_replication row missing = critical)Real scenario: a dashboard that may be 10 s stale; a reporting replica allowed 15 minutes; a "my orders" page that must include the user's last order (read-your-writes); a lag spike caused by max_standby_streaming_delay letting a long query pause replay.
| Metric | PostgreSQL | MySQL | Redis | Kafka |
|---|---|---|---|---|
| Lag in bytes / positions | pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) | GTID sets: Retrieved_Gtid_Set vs Executed_Gtid_Set | master_repl_offset vs replica offset in INFO replication | Consumer lag; follower LogEndOffset vs leader |
| Lag in time | write_lag, flush_lag, replay_lag in pg_stat_replication | Seconds_Behind_Source; heartbeat table (pt-heartbeat) | lag field per replica | replica.lag.time.max.ms (30 s default) defines ISR membership |
| Health | state, sync_state | Replica_IO_Running, Replica_SQL_Running | master_link_status | UnderReplicatedPartitions, UnderMinIsrPartitionCount |
Fix / how to use it: export lag per replica in bytes and seconds, alert at a bound tied to the read policy, write a heartbeat row every second on the leader and read its age on each replica (works when the leader is idle), and let the router exclude replicas above the bound.
Geo-replication patterns: follow-the-sun, region pinning, home region, read-local write-global Must-know
In plain words: put copies near users, but give each piece of data one home region that takes its writes; read locally from replicas, send writes home.
Common misunderstanding: "Multi-region means every region writes everything." That is multi-leader with conflicts. Most global products are single-leader per tenant or per row with the leaders spread over regions.
Definition:
- Geo-replication: replicas in several regions; cross-region links add 60–200 ms of round trip and seconds of lag under load.
- Home region (region pinning): each tenant, user or row is pinned to one region, whose leader takes its writes; data residency (GDPR) often requires it.
- Read-local, write-global: reads go to the nearest replica (stale by the cross-region lag), writes go to the home region (one long round trip), with read-your-writes routing for the writer.
- Follow-the-sun: move the home (or the leaseholder) of a dataset with the working day: Asia in the morning, Europe at noon, Americas in the evening. CockroachDB's leaseholder and
REGIONAL BY ROWpatterns implement it per row. - Re-homing: moving a tenant: freeze writes, wait for the target to catch up, flip the directory, unfreeze.
Tenant 7 (home EU), user travelling in the US
1 GET /projects -> US region: reads US replica of EU data (lag 1.2 s)
2 POST /projects -> US edge: directory says home = EU -> 307 to eu.api (or forward)
3 EU primary commits; response carries LSN; session marks "fresh until LSN"
4 GET /projects -> US replica not past LSN -> read forwarded to EU (or wait up to 1 s)
5 1.5 s later US replica passes LSN -> local reads againReal scenario: a B2B SaaS where each customer chooses EU or US hosting; a game with regional shards and a global friends list; a bank with a home region per account and read-only replicas elsewhere; a global e-commerce site with GLOBAL currency tables and REGIONAL BY ROW orders.
| Pattern | Write latency | Read latency | Conflicts | Products |
|---|---|---|---|---|
| Single global leader | High for remote users | Local (stale) | None | PostgreSQL/MySQL with cross-region replicas, Aurora Global Database |
| Home region per tenant | Local for home users | Local | None | App routing + one cluster per region; CockroachDB REGIONAL BY ROW |
| Multi-leader active-active | Local everywhere | Local | Yes | DynamoDB global tables, Cassandra multi-DC, Redis Enterprise Active-Active |
| Consensus across regions | One cross-region quorum round trip | Local with follower reads (stale) or leaseholder | None | Spanner, CockroachDB SURVIVE REGION FAILURE |
Fix / how to use it: start with home region per tenant; make the directory the only global table; return 307 (or proxy) for writes in the wrong region; carry the commit position for read-your-writes; rehearse a region evacuation. The CockroachDB version:
-- CockroachDB: home region per row, global reference data, region survival.
ALTER DATABASE shop SET PRIMARY REGION "eu-west1";
ALTER DATABASE shop ADD REGION "us-east1";
ALTER DATABASE shop ADD REGION "asia-southeast1";
ALTER DATABASE shop SURVIVE REGION FAILURE; -- default is SURVIVE ZONE FAILURE
-- Each row is homed where its tenant lives (hidden crdb_region column).
ALTER TABLE orders SET LOCALITY REGIONAL BY ROW;
-- Read-mostly reference data: fast reads everywhere, slower writes.
ALTER TABLE currencies SET LOCALITY GLOBAL;
-- Stale-but-local read (bounded staleness, served by the nearest replica).
SELECT * FROM orders AS OF SYSTEM TIME with_max_staleness('10s') WHERE id = 42;Replicating caches and queues: Redis replication, Kafka ISR and acks Must-know
In plain words: caches and logs replicate too, with the same single-leader trade-offs. Redis copies asynchronously; Kafka copies each partition from a leader to followers and lets the producer choose how many must have it.
Common misunderstanding: "Redis WAIT makes Redis strongly consistent" and "acks=all means all replicas". The Redis docs say WAIT "does not turn a set of Redis instances into a CP system with strong consistency"; Kafka's acks=all waits for the current in-sync replicas, which can be just the leader if the others fell out.
Definition:
- Redis replication: asynchronous; each master has a replication ID and offset; replicas reconnect with a partial resync from the backlog or a full sync.
min-replicas-to-write N+min-replicas-max-lag Smake the master refuse writes when fewer than N replicas are within S seconds, bounding the loss window. Deep dive: Redis. - Kafka ISR: "A message is considered committed only when all replicas in the in-sync replicas (ISR) for that partition have applied it to their log." A follower that cannot catch up within
replica.lag.time.max.ms(30 s default) leaves the ISR. Withacks=allandmin.insync.replicas=2, a write needs at least two in-sync copies or the producer getsNOT_ENOUGH_REPLICAS.unclean.leader.election.enable=false(the default) keeps a partition offline rather than electing a replica that may lack committed messages. Deep dive: Kafka.
Kafka topic orders, RF = 3, min.insync.replicas = 2, producer acks=all
1 ISR = {B1 leader, B2, B3}: produce -> committed when B1, B2, B3 have it
2 B3 lags > 30 s: ISR = {B1, B2}; produce still OK (2 >= 2)
3 B2 dies: ISR = {B1}; produce -> NOT_ENOUGH_REPLICAS (retriable); consumers keep reading
4 with acks=1 instead: B1 acknowledges alone; if B1 dies now, those records are gone
5 B1 dies too: partition offline until an ISR member returns (unclean election disabled)Real scenario: a Redis session store that loses the last second of sessions on Sentinel failover (usually acceptable); a Redis rate limiter that briefly allows extra requests after failover; Kafka order events that must survive one broker loss (RF=3, min.insync.replicas=2, acks=all); a metrics topic using acks=1 for throughput.
| Setting | Redis | Kafka |
|---|---|---|
| Replication mode | Async, offset-based | Leader + ISR per partition |
| Per-write durability | WAIT 1 100 | acks=0, acks=1, acks=all (-1) |
| Refuse writes when under-replicated | min-replicas-to-write, min-replicas-max-lag | min.insync.replicas (topic/broker) |
| Leader choice on failure | Sentinel/Cluster: best offset | Controller picks from the ISR |
| Choose availability over safety | Default | unclean.leader.election.enable=true |
# Kafka: durable topic for orders (3 replicas, survive one broker loss without losing acks).
# kafka-topics.sh --create --topic orders --partitions 12 --replication-factor 3 \
# --config min.insync.replicas=2 --config unclean.leader.election.enable=false
replication.factor=3
min.insync.replicas=2
unclean.leader.election.enable=false
# Broker: a follower that has not caught up within this time leaves the ISR.
replica.lag.time.max.ms=30000
# Producer:
acks=all
enable.idempotence=true# Redis primary: refuse writes when too few replicas are recent (bounded loss window).
min-replicas-to-write 1
min-replicas-max-lag 10
# Redis replica:
# replicaof 192.0.2.30 6379
# replica-read-only yes
# replica-serve-stale-data yes # answer reads while disconnected from the primary
# Per-write durability hint from the client: wait for 1 replica ack, up to 100 ms.
# SET order:42 PAID
# WAIT 1 100Fix / how to use it: treat Redis as a cache or a best-effort store unless losing the last second is acceptable; for Kafka topics that carry business facts use RF=3, min.insync.replicas=2, acks=all, idempotent producers and no unclean election.
Federation: sharding by tenant or region into independent clusters Important
In plain words: instead of one big replicated database, run many independent clusters, each owning a slice (a tenant, a region, a product line), with a thin directory or router in front.
Common misunderstanding: "Federation is just sharding." Sharding splits one logical database whose router may run cross-shard queries; federation runs separate systems with separate schemas, versions, failure domains and sometimes owners. Cross-cluster queries are an application concern.
Definition:
- Database federation (functional or tenant partitioning): independent clusters per function (users, orders, search) or per tenant/region (sharding by tenant into cells), each with its own replication topology. A failure or a bad migration hits one cell. See Multi-Tenancy Strategies and Sharding at System Level.
- API federation: a gateway combines independent services behind one API (GraphQL federation, BFFs); data is not replicated, it is composed per request.
- Open federation (by contrast): ActivityPub (Mastodon) servers and Matrix homeservers are run by different organisations. ActivityPub defines "a federated server to server API"; Matrix describes "a global open federation of servers with no single point of control". Each server owns its users' data and pushes activities or room events to the others: replication across trust boundaries, with server signatures, eventual delivery and per-server moderation.
Cell-based SaaS (federation by tenant)
1 request with tenant 7 -> edge router reads directory: tenant 7 -> cell eu-2
2 cell eu-2: its own PostgreSQL primary + 2 replicas + Redis + queue
3 migration v42 rolls out cell by cell; eu-2 fails -> only its 3 % of tenants affected
4 cross-tenant report: each cell exports to the warehouse (CDC), joined there
5 Mastodon by contrast: server A pushes a post to followers' servers B and C via ActivityPub inboxesReal scenario: Slack-style workspace sharding; Salesforce-style "pods"/cells per customer group; a marketplace that federates search, orders and payments into separate databases; GitHub-style functional partitioning of a monolith's tables into separate clusters.
| Kind | Unit | Consistency between units | Example |
|---|---|---|---|
| Functional federation | Bounded context / feature | Eventual, via events or CDC | Users DB, orders DB, search cluster |
| Tenant / regional cells | Tenant group or region | None needed (tenants isolated) | SaaS cells, home region per tenant |
| API federation | Service | Composed per request | GraphQL federation gateway |
| Open federation | Independent server | Eventual, signed, best-effort | Mastodon (ActivityPub), Matrix |
Fix / how to use it: federate when failure isolation and independent operation matter more than cross-unit queries; keep a small, highly available directory; plan tenant moves; feed cross-cell analytics through Change Data Capture.
Failover tooling: Patroni, Orchestrator, Vitess, ProxySQL Good to know
In plain words: databases ship the replication; separate tools decide when to fail over and how clients find the new leader.
Common misunderstanding: "PostgreSQL fails over by itself." Its docs: "PostgreSQL does not provide the system software required to identify a failure on the primary and notify the standby database server."
Definition: one line per tool:
| Tool | Role |
|---|---|
| Patroni | PostgreSQL HA template: leader key in etcd/Consul/ZooKeeper/Kubernetes, automatic promotion, synchronous_mode, maximum_lag_on_failover, watchdog, pg_rewind |
| Orchestrator | "MySQL replication topology management and HA": discovers the topology, refactors it, recovers from source failure with hooks |
| Vitess | MySQL clustering for horizontal scaling (sharding behind VTGate) with VTOrc for automated failover; runs PlanetScale |
| ProxySQL | MySQL-protocol proxy: read/write split by query rules, routes to the current writer hostgroup, monitors read_only |
| pgBouncer / HAProxy | Connection pooling and health-checked routing to the current PostgreSQL primary (HAProxy can query Patroni's REST API) |
| Redis Sentinel | Monitors Redis masters, promotes replicas, tells clients the new master address |
| MySQL InnoDB Cluster | Group Replication + MySQL Shell + MySQL Router as one package |
| Cloud managed | Amazon RDS Multi-AZ, Aurora, Cloud SQL HA: failover and endpoint flip built in |
Patroni + HAProxy
1 HAProxy health-checks GET /primary on each Patroni REST API (port 8008): 200 only on the leader
2 leader dies; key expires; Patroni on pg2 promotes
3 HAProxy sees pg2 return 200 on /primary within its check interval -> new connections go to pg2
4 application retries the failed transaction once (it was rolled back, not half-applied)Real scenario: a self-hosted PostgreSQL cluster on Kubernetes (Patroni via the Zalando or Crunchy operators); a MySQL fleet with Orchestrator and ProxySQL; a sharded MySQL estate on Vitess.
Fix / how to use it: use one of these (or a managed service) rather than scripts; test failover monthly; make sure the client path (proxy, DNS TTL, driver retry) converges as fast as the promotion.
Mechanics
Quorum arithmetic
| N | W | R | R + W > N? | Survives (writes / reads) | Character |
|---|---|---|---|---|---|
| 3 | 2 | 2 | Yes | 1 node down / 1 node down | The default balanced choice |
| 3 | 3 | 1 | Yes | 0 / 2 | Fast reads, fragile writes |
| 3 | 1 | 3 | Yes | 2 / 0 | Fast writes, fragile reads |
| 3 | 1 | 1 | No | 2 / 2 | Fast, may be stale |
| 5 | 3 | 3 | Yes | 2 / 2 | Two failures tolerated |
| 6 (3+3 DCs) | LOCAL_QUORUM = 2 | LOCAL_QUORUM = 2 | Within a DC | 1 per DC | Multi-DC Cassandra standard |
Data-loss window arithmetic
Asynchronous replication loses, on failover, every write acknowledged in the last lag interval. At 2,000 writes per second and a p99 lag of 300 ms, an unlucky failover loses about 600 acknowledged writes; at a lag spike of 20 s, 40,000. Patroni bounds this with maximum_lag_on_failover (a replica further behind is not promoted) and states that the loss is "worst case bounded by maximum_lag_on_failover bytes of transaction log plus the amount that is written in the last ttl seconds". A synchronous or semi-synchronous (AFTER_SYNC) copy reduces it to zero for acknowledged writes, at the cost of one extra round trip per commit (about 0.5–2 ms within a region, 60–150 ms across regions).
The knobs, per product
| Product | Knob | Values / default | Effect |
|---|---|---|---|
| PostgreSQL | synchronous_commit | on (default), remote_apply, remote_write, local, off | How far the commit waits |
| PostgreSQL | synchronous_standby_names | empty (async) / FIRST k (...) / ANY k (...) | Which standbys are synchronous |
| PostgreSQL | max_standby_streaming_delay | 30 s | How long replay waits for conflicting replica queries |
| PostgreSQL | hot_standby_feedback | off | Prevents query cancellations, causes primary bloat |
| MySQL | rpl_semi_sync_source_wait_point | AFTER_SYNC (default) / AFTER_COMMIT | Lossless vs visible-before-replicated |
| MySQL | rpl_semi_sync_source_timeout | 10000 ms | Fallback to async |
| MySQL | super_read_only | OFF | Replicas refuse writes even from admins |
| Redis | min-replicas-to-write / min-replicas-max-lag | 0 / 10 | Refuse writes when under-replicated |
| Kafka | acks | all (default since 3.0) | Producer durability |
| Kafka | min.insync.replicas | 1 | Minimum ISR for acks=all |
| Kafka | replica.lag.time.max.ms | 30000 | When a follower leaves the ISR |
| Kafka | unclean.leader.election.enable | false | Availability over durability |
| Cassandra | max_hint_window | 3 h | How long hints are kept |
| Cassandra | read_repair (table) | BLOCKING | Read repair mode |
| Riak | allow_mult, last_write_wins | bucket-type properties | Siblings vs LWW |
| Patroni | ttl, loop_wait, maximum_lag_on_failover, synchronous_mode | 30 s, 10 s, 1 MB, false | Detection speed, loss bound |
Error messages you will actually see
| Message | Product | Meaning | What to do |
|---|---|---|---|
ERROR: cannot execute INSERT in a read-only transaction (SQLSTATE 25006) | PostgreSQL | A write reached a standby (stale DNS, wrong pool) | Fix routing; retry on the primary |
ERROR: canceling statement due to conflict with recovery (SQLSTATE 40001) | PostgreSQL standby | Replay needed rows your query was reading | Retry; tune max_standby_streaming_delay or hot_standby_feedback |
ERROR 1290 (HY000): The MySQL server is running with the --super-read-only option so it cannot execute this statement | MySQL | Write sent to a replica or a demoted source | Route to the current source |
NOREPLICAS Not enough good replicas to write. | Redis | min-replicas-to-write not met | Back off; the master is isolated or replicas lag |
NOT_ENOUGH_REPLICAS / NotEnoughReplicasException | Kafka | ISR smaller than min.insync.replicas | Retriable; fix the brokers |
NOT_LEADER_OR_FOLLOWER | Kafka | Leadership moved | Client refreshes metadata and retries |
Cannot achieve consistency level QUORUM (UnavailableException) | Cassandra | Too few replicas alive before the request | Fail fast or lower the level for that query |
WriteTimeoutException ... (1 replica were required but only 0 acknowledged the write) | Cassandra | Replicas alive but slow; the write may still apply | Retry only idempotent writes |
Go
The Go module (academy/replication-topologies, standard library only) has four packages: a naive "before" store, a freshness-aware read router, a version-vector shopping cart, and a deterministic simulator of the three topologies with a chaos program.
Before
Every read goes to a random replica, including the read right after the write. Nothing is broken in development, where lag is zero.
// Package before shows the common first version of read scaling: every read
// goes to a randomly chosen replica, including the read right after a write.
// It compiles and "works" in development, where replica lag is zero.
package before
import (
"context"
"database/sql"
"math/rand/v2"
)
// Store splits traffic without any notion of freshness.
type Store struct {
Primary *sql.DB
Replicas []*sql.DB
}
func (s *Store) reader() *sql.DB { return s.Replicas[rand.IntN(len(s.Replicas))] }
// PlaceOrder writes on the primary ...
func (s *Store) PlaceOrder(ctx context.Context, userID int64, totalCents int64) (int64, error) {
var id int64
err := s.Primary.QueryRowContext(ctx,
`INSERT INTO orders (user_id, total_cents, status) VALUES ($1, $2, 'PLACED') RETURNING id`,
userID, totalCents).Scan(&id)
return id, err
}
// OrderStatus ... and the confirmation page reads from a replica that may be
// 200 ms or 20 minutes behind: "order not found" right after checkout.
func (s *Store) OrderStatus(ctx context.Context, orderID int64) (string, error) {
var status string
err := s.reader().QueryRowContext(ctx,
`SELECT status FROM orders WHERE id = $1`, orderID).Scan(&status)
return status, err
}After
A read router with read-your-writes and bounded staleness. The session stores the commit LSN of the user's last write; Pick chooses the least-lagged healthy replica that has replayed it and is within the bound, otherwise the primary. Probe reads pg_last_wal_replay_lsn() and replay age once a second.
// Package router chooses where a read may run: on a replica that has replayed
// the caller's last write (read-your-writes) and is within a staleness bound,
// or on the primary. It works with PostgreSQL LSNs; MySQL GTID sets follow the
// same idea with WAIT_FOR_EXECUTED_GTID_SET.
package router
import (
"context"
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
"time"
)
// LSN is a PostgreSQL write-ahead log position ("16/B374D848").
type LSN uint64
// ParseLSN parses the text form returned by pg_current_wal_lsn()::text.
func ParseLSN(s string) (LSN, error) {
hi, lo, ok := strings.Cut(s, "/")
if !ok {
return 0, fmt.Errorf("invalid LSN %q", s)
}
h, err := strconv.ParseUint(hi, 16, 32)
if err != nil {
return 0, fmt.Errorf("invalid LSN %q: %w", s, err)
}
l, err := strconv.ParseUint(lo, 16, 32)
if err != nil {
return 0, fmt.Errorf("invalid LSN %q: %w", s, err)
}
return LSN(h<<32 | l), nil
}
func (l LSN) String() string { return fmt.Sprintf("%X/%X", uint64(l)>>32, uint64(l)&0xffffffff) }
// Replica is the router's view of one standby, refreshed by a poller.
type Replica struct {
Name string
ReplayLSN LSN // pg_last_wal_replay_lsn()
Lag time.Duration // now() - pg_last_xact_replay_timestamp(), or replay_lag
Healthy bool
}
// Session carries the position of the user's last write (cookie, JWT claim or session).
type Session struct {
LastWrite LSN
}
// Policy is the freshness contract for one kind of read.
type Policy struct {
ReadYourWrites bool // the reader must see its own last write
MaxStaleness time.Duration // bounded staleness; 0 means "primary only"
}
// ErrUsePrimary tells the caller no replica satisfies the policy.
var ErrUsePrimary = errors.New("no replica satisfies the freshness policy; use the primary")
// Pick returns the replica with the smallest lag that satisfies the policy.
func Pick(s Session, p Policy, replicas []Replica) (Replica, error) {
if p.MaxStaleness == 0 {
return Replica{}, ErrUsePrimary
}
var best *Replica
for i := range replicas {
r := &replicas[i]
if !r.Healthy || r.Lag > p.MaxStaleness {
continue
}
if p.ReadYourWrites && r.ReplayLSN < s.LastWrite {
continue
}
if best == nil || r.Lag < best.Lag {
best = r
}
}
if best == nil {
return Replica{}, ErrUsePrimary
}
return *best, nil
}
// CurrentLSN reads the primary's WAL position right after a commit; store it in the session.
func CurrentLSN(ctx context.Context, primary *sql.DB) (LSN, error) {
var s string
if err := primary.QueryRowContext(ctx, `SELECT pg_current_wal_lsn()::text`).Scan(&s); err != nil {
return 0, err
}
return ParseLSN(s)
}
// Probe refreshes one replica's position and lag (run every second per replica).
func Probe(ctx context.Context, name string, db *sql.DB) Replica {
var lsn string
var lagSeconds sql.NullFloat64
err := db.QueryRowContext(ctx, `
SELECT pg_last_wal_replay_lsn()::text,
CASE WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
ELSE EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()) END`).
Scan(&lsn, &lagSeconds)
if err != nil {
return Replica{Name: name}
}
l, err := ParseLSN(lsn)
if err != nil {
return Replica{Name: name}
}
return Replica{
Name: name,
ReplayLSN: l,
Lag: time.Duration(lagSeconds.Float64 * float64(time.Second)),
Healthy: true,
}
}package router
import (
"errors"
"testing"
"time"
)
func TestParseLSN(t *testing.T) {
l, err := ParseLSN("16/B374D848")
if err != nil {
t.Fatal(err)
}
if l != LSN(0x16<<32|0xB374D848) || l.String() != "16/B374D848" {
t.Fatalf("got %v", l)
}
if _, err := ParseLSN("nonsense"); err == nil {
t.Fatal("want error")
}
}
func TestPick(t *testing.T) {
replicas := []Replica{
{Name: "r1", ReplayLSN: 100, Lag: 50 * time.Millisecond, Healthy: true},
{Name: "r2", ReplayLSN: 180, Lag: 300 * time.Millisecond, Healthy: true},
{Name: "r3", ReplayLSN: 200, Lag: 10 * time.Millisecond, Healthy: false},
}
cases := []struct {
name string
s Session
p Policy
want string // "" means primary
}{
{"strong read goes to primary", Session{}, Policy{}, ""},
{"bounded staleness picks least lag", Session{}, Policy{MaxStaleness: time.Second}, "r1"},
{"read-your-writes skips replicas behind the session", Session{LastWrite: 150}, Policy{ReadYourWrites: true, MaxStaleness: time.Second}, "r2"},
{"tight bound excludes the only fresh replica", Session{LastWrite: 150}, Policy{ReadYourWrites: true, MaxStaleness: 100 * time.Millisecond}, ""},
{"unhealthy replica never chosen", Session{LastWrite: 190}, Policy{ReadYourWrites: true, MaxStaleness: time.Second}, ""},
}
for _, c := range cases {
got, err := Pick(c.s, c.p, replicas)
if c.want == "" {
if !errors.Is(err, ErrUsePrimary) {
t.Errorf("%s: got %v, want primary", c.name, got.Name)
}
continue
}
if err != nil || got.Name != c.want {
t.Errorf("%s: got %q %v, want %q", c.name, got.Name, err, c.want)
}
}
}A version-vector merge for a shopping cart. Concurrent adds become siblings, the read merges them, the write with the merged context collapses them; the tests also show the documented cost (a removed item resurfaces) and why a blind write without context creates a sibling instead of overwriting.
// Package vv implements version vectors and a Dynamo-style shopping cart
// that keeps concurrent versions as siblings and merges them on read.
package vv
import (
"maps"
"slices"
"sort"
)
// VV maps a replica (node) id to the number of writes it coordinated.
type VV map[string]uint64
// Order is the causal relation between two version vectors.
type Order int
const (
Equal Order = iota // same history
Before // a happened before b (b dominates a)
After // a happened after b (a dominates b)
Concurrent // neither saw the other: a real conflict
)
func (o Order) String() string {
return [...]string{"equal", "before", "after", "concurrent"}[o]
}
// Compare returns how a relates to b.
func (a VV) Compare(b VV) Order {
aLess, bLess := false, false
for _, k := range keys(a, b) {
switch {
case a[k] < b[k]:
aLess = true
case a[k] > b[k]:
bLess = true
}
}
switch {
case aLess && bLess:
return Concurrent
case aLess:
return Before
case bLess:
return After
default:
return Equal
}
}
// Merge returns the element-wise maximum: a clock that has seen both histories.
func (a VV) Merge(b VV) VV {
out := maps.Clone(a)
if out == nil {
out = VV{}
}
for k, v := range b {
if v > out[k] {
out[k] = v
}
}
return out
}
// Descends reports whether a has seen everything b has seen.
func (a VV) Descends(b VV) bool {
o := a.Compare(b)
return o == Equal || o == After
}
func keys(a, b VV) []string {
set := map[string]struct{}{}
for k := range a {
set[k] = struct{}{}
}
for k := range b {
set[k] = struct{}{}
}
out := make([]string, 0, len(set))
for k := range set {
out = append(out, k)
}
sort.Strings(out)
return out
}
// Cart is a shopping cart value: SKU -> quantity.
type Cart map[string]int
// Sibling is one version of the value together with its causal history.
type Sibling struct {
Clock VV
Cart Cart
}
// Replica stores every causally unrelated version of one key (Riak allow_mult=true).
type Replica struct {
ID string
siblings []Sibling
}
// NewReplica returns an empty replica.
func NewReplica(id string) *Replica { return &Replica{ID: id} }
// Get returns all siblings and a context (merged clock) to send back with the next write.
func (r *Replica) Get() ([]Sibling, VV) {
ctx := VV{}
out := make([]Sibling, 0, len(r.siblings))
for _, s := range r.siblings {
ctx = ctx.Merge(s.Clock)
out = append(out, Sibling{Clock: maps.Clone(s.Clock), Cart: maps.Clone(s.Cart)})
}
return out, ctx
}
// Put coordinates a client write. ctx is the context from the client's last Get;
// every sibling the context has seen is replaced, unseen ones stay as siblings.
func (r *Replica) Put(ctx VV, cart Cart) Sibling {
clock := ctx.Merge(nil)
for _, s := range r.siblings {
// the coordinator also folds in its own counter so it never reuses a dot
if s.Clock[r.ID] > clock[r.ID] {
clock[r.ID] = s.Clock[r.ID]
}
}
clock[r.ID]++
s := Sibling{Clock: clock, Cart: maps.Clone(cart)}
r.store(s)
return s
}
// Receive applies a version replicated from another node (or read repair).
func (r *Replica) Receive(s Sibling) { r.store(s) }
func (r *Replica) store(s Sibling) {
kept := make([]Sibling, 0, len(r.siblings)+1)
for _, old := range r.siblings {
if old.Clock.Descends(s.Clock) {
return // we already have this version or a newer one
}
if s.Clock.Descends(old.Clock) {
continue // the new version has seen this one: discard it
}
kept = append(kept, old)
}
r.siblings = append(kept, Sibling{Clock: maps.Clone(s.Clock), Cart: maps.Clone(s.Cart)})
}
// MergeCarts is the application's semantic reconciliation: union of items,
// maximum quantity per SKU. An "add to cart" is never lost, but an item removed
// in one sibling and still present in another comes back (Dynamo: "deleted items can resurface").
func MergeCarts(sibs []Sibling) Cart {
out := Cart{}
for _, s := range sibs {
for sku, q := range s.Cart {
if q > out[sku] {
out[sku] = q
}
}
}
return out
}
// SKUs returns the cart's SKUs in a stable order (for printing and tests).
func (c Cart) SKUs() []string {
return slices.Sorted(maps.Keys(c))
}package vv
import (
"reflect"
"testing"
)
func TestCompare(t *testing.T) {
cases := []struct {
a, b VV
want Order
}{
{VV{"a": 1}, VV{"a": 1}, Equal},
{VV{"a": 1}, VV{"a": 2}, Before},
{VV{"a": 2, "b": 1}, VV{"a": 1}, After},
{VV{"a": 2}, VV{"a": 1, "b": 1}, Concurrent},
{VV{}, VV{"b": 1}, Before},
}
for _, c := range cases {
if got := c.a.Compare(c.b); got != c.want {
t.Errorf("%v vs %v = %v, want %v", c.a, c.b, got, c.want)
}
}
}
// Two regions add to the same cart without seeing each other: two siblings.
// The next read merges them, the write with the merged context collapses them.
func TestConcurrentAddsBecomeSiblingsThenMerge(t *testing.T) {
eu, us := NewReplica("eu"), NewReplica("us")
first := eu.Put(VV{}, Cart{"book": 1})
us.Receive(first) // both start from the same version
_, ctxEU := eu.Get()
_, ctxUS := us.Get()
a := eu.Put(ctxEU, Cart{"book": 1, "pen": 1}) // add pen in eu
b := us.Put(ctxUS, Cart{"book": 1, "lamp": 1}) // add lamp in us, concurrently
if got := a.Clock.Compare(b.Clock); got != Concurrent {
t.Fatalf("clocks %v and %v: got %v, want concurrent", a.Clock, b.Clock, got)
}
eu.Receive(b) // anti-entropy / replication delivers the other write
sibs, ctx := eu.Get()
if len(sibs) != 2 {
t.Fatalf("want 2 siblings, got %d", len(sibs))
}
merged := MergeCarts(sibs)
if want := (Cart{"book": 1, "pen": 1, "lamp": 1}); !reflect.DeepEqual(merged, want) {
t.Fatalf("merged %v, want %v", merged, want)
}
resolved := eu.Put(ctx, merged)
if sibs, _ := eu.Get(); len(sibs) != 1 {
t.Fatalf("write with merged context must collapse siblings, got %d", len(sibs))
}
us.Receive(a)
us.Receive(resolved)
if sibs, _ := us.Get(); len(sibs) != 1 || !reflect.DeepEqual(sibs[0].Cart, merged) {
t.Fatalf("us did not converge: %+v", sibs)
}
}
// The documented price of union merge: a removal in one sibling is undone.
func TestDeletedItemResurfaces(t *testing.T) {
eu, us := NewReplica("eu"), NewReplica("us")
base := eu.Put(VV{}, Cart{"book": 1, "pen": 1})
us.Receive(base)
_, c1 := eu.Get()
_, c2 := us.Get()
x := eu.Put(c1, Cart{"book": 1}) // pen removed in eu
y := us.Put(c2, Cart{"book": 1, "pen": 1, "mug": 1}) // mug added in us
eu.Receive(y)
_ = x
sibs, _ := eu.Get()
if got := MergeCarts(sibs); got["pen"] != 1 {
t.Fatalf("expected the removed pen to resurface, got %v", got)
}
}
// An old version arriving late (stale replica, read repair) is ignored.
func TestDominatedVersionIsDiscarded(t *testing.T) {
r := NewReplica("eu")
v1 := r.Put(VV{}, Cart{"book": 1})
_, ctx := r.Get()
r.Put(ctx, Cart{"book": 2})
r.Receive(v1)
sibs, _ := r.Get()
if len(sibs) != 1 || sibs[0].Cart["book"] != 2 {
t.Fatalf("stale version must not create a sibling: %+v", sibs)
}
}
// Writing without a context (a blind write) creates a sibling instead of
// silently overwriting: this is why clients must send the context back.
func TestBlindWriteCreatesSibling(t *testing.T) {
r := NewReplica("eu")
other := NewReplica("us")
r.Receive(other.Put(VV{}, Cart{"book": 1}))
r.Put(VV{}, Cart{"lamp": 1})
if sibs, _ := r.Get(); len(sibs) != 2 {
t.Fatalf("blind write should leave 2 siblings, got %d", len(sibs))
}
}A simulator of the three topologies. Replication messages arrive after Lag ticks and wait while a link is partitioned. Counters expose stale reads, rejected writes, conflicts, writes lost to LWW, writes lost at failover, split-brain acceptances, hints and read repairs.
// Package sim is a deterministic, single-process simulator of the three
// replication topologies: single-leader, multi-leader and leaderless quorums.
// Time is a tick counter; replication messages arrive Lag ticks after they are
// sent and wait in a queue while the link is partitioned. Counters make the
// trade-offs visible: stale reads, rejected writes, conflicts, writes lost to
// last-writer-wins, writes lost at failover, hints and read repairs.
package sim
import (
"errors"
"fmt"
)
// Topology selects who may accept writes.
type Topology int
const (
SingleLeader Topology = iota
MultiLeader
Leaderless
)
func (t Topology) String() string {
return [...]string{"single-leader", "multi-leader", "leaderless"}[t]
}
var (
ErrNotLeader = errors.New("not the leader: write rejected")
ErrFenced = errors.New("node is fenced: write rejected")
ErrNoQuorum = errors.New("quorum not reached")
ErrNoSync = errors.New("synchronous standby unreachable: commit waits")
)
// Version is a stored value. TS is a hybrid "timestamp" ((tick+1)*100 + node id)
// so ties never happen; Base is the TS the writer had seen (for conflict detection).
type Version struct {
Value string
TS int64
Base int64
Epoch int
Node int
}
// Config describes one cluster.
type Config struct {
Topology Topology
Nodes int
Lag int // ticks for an asynchronous replication message
SyncCopies int // single-leader: followers that must confirm before commit
W, R int // leaderless quorum sizes (N = Nodes)
Sloppy bool // leaderless: accept hints on reachable nodes when replicas are cut off
}
// Stats are the counters the tests and the chaos program print.
type Stats struct {
Writes, Rejected, StaleReads int
Conflicts, LostToLWW, LostAtFailover int
HintsStored, HintsDelivered, ReadRepairs int
PartialWritesAfterQuorumFailure, SplitBrainAcc int
}
type message struct {
from, to int
key string
v Version
due int
hint bool
}
type node struct {
id int
data map[string]Version
fenced bool
epoch int
}
// Cluster is the simulated system.
type Cluster struct {
cfg Config
now int
leader int
epoch int
nodes []*node
cut map[[2]int]bool
queue []message
latest map[string]Version // ground truth: last acknowledged write per key
conflicts map[[2]int64]bool
refused map[int64]bool
Stats Stats
Journal []string
}
// New builds a cluster; node 0 is the first leader.
func New(cfg Config) *Cluster {
c := &Cluster{cfg: cfg, cut: map[[2]int]bool{}, latest: map[string]Version{}, conflicts: map[[2]int64]bool{}, refused: map[int64]bool{}, epoch: 1}
for i := 0; i < cfg.Nodes; i++ {
c.nodes = append(c.nodes, &node{id: i, data: map[string]Version{}, epoch: 1})
}
return c
}
func (c *Cluster) logf(format string, a ...any) {
c.Journal = append(c.Journal, fmt.Sprintf("t=%02d ", c.now)+fmt.Sprintf(format, a...))
}
// Note adds a line to the journal (used by the chaos program).
func (c *Cluster) Note(format string, a ...any) { c.logf(format, a...) }
// Leader returns the current leader id (single-leader only).
func (c *Cluster) Leader() int { return c.leader }
// Partition cuts the link between a and b in both directions.
func (c *Cluster) Partition(a, b int) { c.cut[[2]int{a, b}], c.cut[[2]int{b, a}] = true, true }
// Isolate cuts n from every other node.
func (c *Cluster) Isolate(n int) {
for i := range c.nodes {
if i != n {
c.Partition(n, i)
}
}
c.logf("node %d isolated", n)
}
// Heal removes every partition.
func (c *Cluster) Heal() { c.cut = map[[2]int]bool{}; c.logf("partition healed") }
func (c *Cluster) reachable(a, b int) bool { return a == b || !c.cut[[2]int{a, b}] }
func (c *Cluster) stamp(n int) int64 { return int64(c.now+1)*100 + int64(n) }
func (c *Cluster) send(from, to int, key string, v Version, hint bool) {
c.queue = append(c.queue, message{from: from, to: to, key: key, v: v, due: c.now + c.cfg.Lag, hint: hint})
}
// Write sends a client write to node n (the client's local node or region).
func (c *Cluster) Write(n int, key, value string) error {
switch c.cfg.Topology {
case SingleLeader:
return c.writeSingle(n, key, value)
case MultiLeader:
return c.writeMulti(n, key, value)
default:
return c.writeLeaderless(n, key, value)
}
}
func (c *Cluster) writeSingle(n int, key, value string) error {
nd := c.nodes[n]
if nd.fenced {
c.Stats.Rejected++
return ErrFenced
}
if n != c.leader && nd.epoch == c.epoch {
c.Stats.Rejected++
return ErrNotLeader
}
if n != c.leader {
// an old leader that was not fenced still believes it leads: split brain
c.Stats.SplitBrainAcc++
}
v := Version{Value: value, TS: c.stamp(n), Epoch: nd.epoch, Node: n}
// synchronous followers must be reachable before the commit is acknowledged
confirmed := 0
for i := range c.nodes {
if i != n && confirmed < c.cfg.SyncCopies && c.reachable(n, i) {
c.nodes[i].data[key] = v
confirmed++
}
}
if confirmed < c.cfg.SyncCopies {
c.Stats.Rejected++
return ErrNoSync
}
nd.data[key] = v
for i := range c.nodes {
if i != n {
c.send(n, i, key, v, false)
}
}
c.Stats.Writes++
if n == c.leader {
c.latest[key] = v
}
c.logf("node %d (epoch %d) commits %s=%s", n, nd.epoch, key, value)
return nil
}
func (c *Cluster) writeMulti(n int, key, value string) error {
nd := c.nodes[n]
v := Version{Value: value, TS: c.stamp(n), Base: nd.data[key].TS, Node: n}
nd.data[key] = v
for i := range c.nodes {
if i != n {
c.send(n, i, key, v, false)
}
}
c.Stats.Writes++
if v.TS > c.latest[key].TS {
c.latest[key] = v
}
c.logf("leader %d accepts %s=%s locally", n, key, value)
return nil
}
func (c *Cluster) writeLeaderless(coord int, key, value string) error {
v := Version{Value: value, TS: c.stamp(coord), Node: coord}
acks := 0
var missed []int
for i := range c.nodes {
if c.reachable(coord, i) {
c.apply(i, key, v)
acks++
} else {
missed = append(missed, i)
}
}
if acks < c.cfg.W && c.cfg.Sloppy {
// sloppy quorum: the coordinator keeps a hint per missed replica and counts it
for _, m := range missed {
if acks >= c.cfg.W {
break
}
c.send(coord, m, key, v, true)
c.Stats.HintsStored++
acks++
}
}
if acks < c.cfg.W {
// the replicas that did get the write keep it: a failed quorum is not a rollback
c.Stats.Rejected++
c.Stats.PartialWritesAfterQuorumFailure++
return fmt.Errorf("%w: %d of W=%d", ErrNoQuorum, acks, c.cfg.W)
}
c.Stats.Writes++
c.latest[key] = v
c.logf("coordinator %d writes %s=%s with %d acks (W=%d)", coord, key, value, acks, c.cfg.W)
return nil
}
// apply stores v on node i if it is newer (last-writer-wins on TS).
func (c *Cluster) apply(i int, key string, v Version) {
if cur, ok := c.nodes[i].data[key]; !ok || v.TS > cur.TS {
c.nodes[i].data[key] = v
}
}
// Read returns the value seen by a client on node n. Leaderless reads ask R
// reachable replicas, return the newest and repair the stale ones they asked.
func (c *Cluster) Read(n int, key string) (string, bool) {
if c.cfg.Topology != Leaderless {
v := c.nodes[n].data[key]
stale := v.TS != c.latest[key].TS
if stale {
c.Stats.StaleReads++
}
return v.Value, !stale
}
var asked []int
for i := 0; i < len(c.nodes) && len(asked) < c.cfg.R; i++ {
j := (n + i) % len(c.nodes)
if c.reachable(n, j) {
asked = append(asked, j)
}
}
var best Version
for _, j := range asked {
if v := c.nodes[j].data[key]; v.TS > best.TS {
best = v
}
}
for _, j := range asked {
if c.nodes[j].data[key].TS < best.TS {
c.nodes[j].data[key] = best
c.Stats.ReadRepairs++
}
}
stale := best.TS != c.latest[key].TS
if stale {
c.Stats.StaleReads++
}
return best.Value, !stale
}
// Tick advances time and delivers due messages whose link is up.
func (c *Cluster) Tick() {
c.now++
var pending []message
for _, m := range c.queue {
if m.due > c.now || !c.reachable(m.from, m.to) {
pending = append(pending, m)
continue
}
c.deliver(m)
}
c.queue = pending
}
// Run ticks k times.
func (c *Cluster) Run(k int) {
for i := 0; i < k; i++ {
c.Tick()
}
}
func (c *Cluster) deliver(m message) {
to := c.nodes[m.to]
switch c.cfg.Topology {
case SingleLeader:
if m.v.Epoch < to.epoch {
// replication from a deposed leader is refused: its writes are gone
if !c.refused[m.v.TS] {
c.refused[m.v.TS] = true
c.Stats.LostAtFailover++
c.logf("node %d refuses %s=%s from epoch %d", m.to, m.key, m.v.Value, m.v.Epoch)
}
return
}
if m.v.Epoch > to.epoch {
// the receiver is a deposed leader with its own history: it must be rewound first
c.logf("node %d (epoch %d) diverged, ignores epoch %d until rewound", m.to, to.epoch, m.v.Epoch)
return
}
c.apply(m.to, m.key, m.v)
case MultiLeader:
cur, ok := to.data[m.key]
if ok && cur.TS > m.v.Base && cur.TS != m.v.TS && cur.Base != m.v.TS {
// the sender did not see the version this node holds: concurrent writes
pair := [2]int64{min(cur.TS, m.v.TS), max(cur.TS, m.v.TS)}
if !c.conflicts[pair] {
c.conflicts[pair] = true
c.Stats.Conflicts++
c.Stats.LostToLWW++ // the older of the two is silently discarded by LWW
c.logf("node %d detects conflict on %s: %q vs %q, LWW keeps %q",
m.to, m.key, cur.Value, m.v.Value, newer(cur, m.v).Value)
}
}
c.apply(m.to, m.key, m.v)
default:
c.apply(m.to, m.key, m.v)
if m.hint {
c.Stats.HintsDelivered++
c.logf("hint for %s handed off to node %d", m.key, m.to)
}
}
}
// Failover promotes the most up-to-date reachable follower of the current
// leader. With fence=true the old leader is fenced (STONITH) first.
// Acknowledged writes that never reached the new leader are counted as lost.
func (c *Cluster) Failover(newLeader int, fence bool) {
old := c.leader
if fence {
c.nodes[old].fenced = true
}
c.epoch++
c.leader = newLeader
for i, nd := range c.nodes {
if c.reachable(newLeader, i) {
nd.epoch = c.epoch
}
}
for key, v := range c.latest {
if c.nodes[newLeader].data[key].TS < v.TS {
c.Stats.LostAtFailover++
c.latest[key] = c.nodes[newLeader].data[key]
c.logf("promotion loses acknowledged %s=%s", key, v.Value)
}
}
c.logf("node %d promoted (epoch %d), fenced old leader: %v", newLeader, c.epoch, fence)
}
// Rejoin rewinds node n to the current leader's data (pg_rewind or a fresh
// base backup) and makes it a follower of the current epoch. It returns the
// number of keys whose local, divergent version was thrown away.
func (c *Cluster) Rejoin(n int) int {
nd, ld := c.nodes[n], c.nodes[c.leader]
dropped := 0
for key, v := range nd.data {
if ld.data[key].TS != v.TS {
dropped++
}
}
nd.data = map[string]Version{}
for key, v := range ld.data {
nd.data[key] = v
}
nd.epoch, nd.fenced = c.epoch, false
c.logf("node %d rewound and rejoined as follower, %d divergent keys dropped", n, dropped)
return dropped
}
func newer(a, b Version) Version {
if a.TS > b.TS {
return a
}
return b
}
// Value returns what node n stores for key (for assertions).
func (c *Cluster) Value(n int, key string) string { return c.nodes[n].data[key].Value }
// Converged reports whether every node stores the same version of key.
func (c *Cluster) Converged(key string) bool {
first := c.nodes[0].data[key]
for _, nd := range c.nodes[1:] {
if nd.data[key].TS != first.TS {
return false
}
}
return true
}package sim
import (
"errors"
"testing"
)
// Asynchronous single-leader: a read on a follower inside the lag window is stale.
func TestSingleLeaderAsyncReplicaLag(t *testing.T) {
c := New(Config{Topology: SingleLeader, Nodes: 3, Lag: 3})
if err := c.Write(0, "order:1", "PAID"); err != nil {
t.Fatal(err)
}
if _, fresh := c.Read(1, "order:1"); fresh {
t.Fatal("follower read inside the lag window should be stale")
}
c.Run(3)
if v, fresh := c.Read(1, "order:1"); !fresh || v != "PAID" {
t.Fatalf("after lag: got %q fresh=%v", v, fresh)
}
if c.Stats.StaleReads != 1 {
t.Fatalf("stale reads = %d, want 1", c.Stats.StaleReads)
}
}
// Followers refuse client writes; only the leader accepts them.
func TestSingleLeaderRejectsWritesOnFollower(t *testing.T) {
c := New(Config{Topology: SingleLeader, Nodes: 3, Lag: 1})
if err := c.Write(2, "k", "v"); !errors.Is(err, ErrNotLeader) {
t.Fatalf("got %v, want ErrNotLeader", err)
}
}
// Async failover loses the acknowledged writes the new leader never received.
func TestAsyncFailoverLosesAcknowledgedWrite(t *testing.T) {
c := New(Config{Topology: SingleLeader, Nodes: 3, Lag: 5})
_ = c.Write(0, "balance:7", "100")
c.Run(5)
_ = c.Write(0, "balance:7", "40") // acknowledged, still in flight
c.Isolate(0) // leader dies before shipping it
c.Failover(1, true)
if c.Stats.LostAtFailover != 1 {
t.Fatalf("lost = %d, want 1", c.Stats.LostAtFailover)
}
if v := c.Value(1, "balance:7"); v != "100" {
t.Fatalf("new leader has %q, want the older 100", v)
}
}
// One synchronous standby: the same failure loses nothing.
func TestSyncStandbyFailoverLosesNothing(t *testing.T) {
c := New(Config{Topology: SingleLeader, Nodes: 3, Lag: 5, SyncCopies: 1})
_ = c.Write(0, "balance:7", "100")
_ = c.Write(0, "balance:7", "40")
c.Isolate(0)
c.Failover(1, true)
if c.Stats.LostAtFailover != 0 || c.Value(1, "balance:7") != "40" {
t.Fatalf("lost=%d value=%q", c.Stats.LostAtFailover, c.Value(1, "balance:7"))
}
}
// With SyncCopies set and every follower unreachable, the commit cannot complete.
func TestSyncStandbyUnreachableBlocksCommit(t *testing.T) {
c := New(Config{Topology: SingleLeader, Nodes: 2, Lag: 1, SyncCopies: 1})
c.Isolate(0)
if err := c.Write(0, "k", "v"); !errors.Is(err, ErrNoSync) {
t.Fatalf("got %v, want ErrNoSync", err)
}
}
// Split brain: the old leader is only partitioned, not fenced, and keeps
// accepting writes. After healing they are refused and thrown away.
func TestSplitBrainWithoutFencing(t *testing.T) {
c := New(Config{Topology: SingleLeader, Nodes: 3, Lag: 1})
c.Isolate(0)
c.Failover(1, false)
if err := c.Write(0, "seat:12A", "alice"); err != nil {
t.Fatalf("unfenced old leader should still accept: %v", err)
}
_ = c.Write(1, "seat:12A", "bob")
c.Heal()
c.Run(2)
if c.Stats.SplitBrainAcc != 1 || c.Stats.LostAtFailover < 1 {
t.Fatalf("split brain stats: %+v", c.Stats)
}
if dropped := c.Rejoin(0); dropped != 1 {
t.Fatalf("rewind dropped %d keys, want 1", dropped)
}
if c.Value(0, "seat:12A") != "bob" {
t.Fatal("old leader must converge to the new leader after rewind")
}
}
// Fencing (STONITH) turns the same scenario into a clean rejection.
func TestFencingStopsTheOldLeader(t *testing.T) {
c := New(Config{Topology: SingleLeader, Nodes: 3, Lag: 1})
c.Isolate(0)
c.Failover(1, true)
if err := c.Write(0, "seat:12A", "alice"); !errors.Is(err, ErrFenced) {
t.Fatalf("got %v, want ErrFenced", err)
}
}
// Multi-leader: concurrent writes in two regions are a conflict, LWW keeps one
// and silently drops the other, and the regions converge.
func TestMultiLeaderConflictAndLWWLoss(t *testing.T) {
c := New(Config{Topology: MultiLeader, Nodes: 2, Lag: 2})
_ = c.Write(0, "profile:9", "name=Ana")
c.Run(2)
_ = c.Write(0, "profile:9", "name=Ana Silva") // eu
_ = c.Write(1, "profile:9", "name=Ana S.") // us, same tick, did not see eu
c.Run(2)
if c.Stats.Conflicts != 1 || c.Stats.LostToLWW != 1 {
t.Fatalf("conflicts=%d lost=%d", c.Stats.Conflicts, c.Stats.LostToLWW)
}
if !c.Converged("profile:9") {
t.Fatal("regions did not converge")
}
if v := c.Value(0, "profile:9"); v != "name=Ana S." {
t.Fatalf("LWW winner %q; node 1 has the higher tie-break", v)
}
}
// Sequential writes across leaders are not conflicts.
func TestMultiLeaderSequentialWritesNoConflict(t *testing.T) {
c := New(Config{Topology: MultiLeader, Nodes: 3, Lag: 1})
_ = c.Write(0, "k", "a")
c.Run(1)
_ = c.Write(1, "k", "b")
c.Run(1)
if c.Stats.Conflicts != 0 || !c.Converged("k") {
t.Fatalf("conflicts=%d", c.Stats.Conflicts)
}
}
// Leaderless N=3, W=2, R=2: R+W>N, so a read overlaps the latest write and
// read repair fixes the stale replica it touched.
func TestLeaderlessQuorumOverlapAndReadRepair(t *testing.T) {
c := New(Config{Topology: Leaderless, Nodes: 3, Lag: 1, W: 2, R: 2})
c.Partition(0, 2)
if err := c.Write(0, "cart:5", "v1"); err != nil {
t.Fatal(err)
}
c.Heal()
// node 2 missed the write; read coordinated by node 1 asks nodes 1 and 2
if v, fresh := c.Read(1, "cart:5"); !fresh || v != "v1" {
t.Fatalf("quorum read got %q fresh=%v", v, fresh)
}
if c.Stats.ReadRepairs != 1 || c.Value(2, "cart:5") != "v1" {
t.Fatalf("read repair: %+v, node2=%q", c.Stats, c.Value(2, "cart:5"))
}
}
// W=1, R=1: fast, but a read can miss the write.
func TestLeaderlessWeakQuorumStaleRead(t *testing.T) {
c := New(Config{Topology: Leaderless, Nodes: 3, Lag: 1, W: 1, R: 1})
c.Isolate(0)
_ = c.Write(0, "k", "v1")
c.Heal()
if _, fresh := c.Read(1, "k"); fresh {
t.Fatal("R=1 read from a replica that missed the write should be stale")
}
}
// Strict quorum fails during a partition, but the replicas that were reached
// keep the write: a failed quorum is not a rollback.
func TestStrictQuorumFailureLeavesPartialWrite(t *testing.T) {
c := New(Config{Topology: Leaderless, Nodes: 3, Lag: 1, W: 2, R: 2})
c.Isolate(0)
if err := c.Write(0, "k", "v1"); !errors.Is(err, ErrNoQuorum) {
t.Fatalf("got %v, want ErrNoQuorum", err)
}
if c.Value(0, "k") != "v1" || c.Stats.PartialWritesAfterQuorumFailure != 1 {
t.Fatal("the coordinator's own replica keeps the partial write")
}
}
// Sloppy quorum + hinted handoff: the write succeeds during the partition and
// the hints are delivered once the link heals.
func TestSloppyQuorumHintedHandoff(t *testing.T) {
c := New(Config{Topology: Leaderless, Nodes: 3, Lag: 1, W: 2, R: 2, Sloppy: true})
c.Isolate(0)
if err := c.Write(0, "k", "v1"); err != nil {
t.Fatalf("sloppy quorum should accept: %v", err)
}
c.Run(3)
if c.Stats.HintsDelivered != 0 {
t.Fatal("hints cannot be delivered across a partition")
}
c.Heal()
c.Run(1)
if c.Stats.HintsStored != 1 || c.Stats.HintsDelivered != 1 {
t.Fatalf("hints: %+v", c.Stats)
}
}The chaos program replays four scenarios and prints their timelines (output in the Lab):
// Command chaos replays four failure scenarios against the simulator and
// prints each timeline plus the counters. It is deterministic.
package main
import (
"fmt"
"academy/replication-topologies/sim"
)
func main() {
scenario("1. async single-leader: leader dies with an unshipped write",
sim.Config{Topology: sim.SingleLeader, Nodes: 3, Lag: 4},
func(c *sim.Cluster) {
_ = c.Write(0, "balance:7", "100")
c.Run(4)
_ = c.Write(0, "balance:7", "40")
c.Isolate(0)
c.Failover(1, true)
})
scenario("2. split brain: old leader partitioned, not fenced",
sim.Config{Topology: sim.SingleLeader, Nodes: 3, Lag: 1},
func(c *sim.Cluster) {
c.Isolate(0)
c.Failover(1, false)
_ = c.Write(0, "seat:12A", "alice")
_ = c.Write(1, "seat:12A", "bob")
c.Heal()
c.Run(2)
c.Rejoin(0)
})
scenario("3. multi-leader: same key edited in two regions",
sim.Config{Topology: sim.MultiLeader, Nodes: 2, Lag: 2},
func(c *sim.Cluster) {
_ = c.Write(0, "profile:9", "Ana")
c.Run(2)
_ = c.Write(0, "profile:9", "Ana Silva")
_ = c.Write(1, "profile:9", "Ana S.")
c.Run(2)
})
scenario("4. leaderless N=3 W=2 R=2 sloppy: partition, hint, heal, read repair",
sim.Config{Topology: sim.Leaderless, Nodes: 3, Lag: 1, W: 2, R: 2, Sloppy: true},
func(c *sim.Cluster) {
c.Isolate(0)
_ = c.Write(0, "cart:5", "v1")
v, fresh := c.Read(1, "cart:5")
c.Note("read via node 1 during the partition: %q fresh=%v", v, fresh)
c.Heal()
c.Run(1)
v, fresh = c.Read(1, "cart:5")
c.Note("read via node 1 after hint delivery: %q fresh=%v", v, fresh)
})
}
func scenario(title string, cfg sim.Config, steps func(*sim.Cluster)) {
fmt.Println("== " + title)
c := sim.New(cfg)
steps(c)
for _, line := range c.Journal {
fmt.Println(" ", line)
}
s := c.Stats
fmt.Printf(" writes=%d rejected=%d stale=%d conflicts=%d lostLWW=%d lostFailover=%d splitBrain=%d hints=%d/%d repairs=%d\n\n",
s.Writes, s.Rejected, s.StaleReads, s.Conflicts, s.LostToLWW, s.LostAtFailover, s.SplitBrainAcc,
s.HintsDelivered, s.HintsStored, s.ReadRepairs)
}The Go angle
| Go feature | Use in replication | Note |
|---|---|---|
database/sql with two *sql.DB pools | One pool for the primary, one per replica | Pools are per host; size them separately |
github.com/jackc/pgx/v5 pgxpool | PostgreSQL driver; target_session_attrs=read-write in the DSN picks the primary among several hosts | Multi-host DSNs: host=a,b,c |
pgconn / pglogrepl | Logical replication protocol clients (CDC, custom replicators) | For building multi-leader or CDC tooling |
github.com/go-sql-driver/mysql | MySQL driver | Combine with ProxySQL for read/write split |
github.com/redis/go-redis/v9 | rdb.Wait(ctx, 1, 100*time.Millisecond), NewFailoverClient for Sentinel | Failover client follows promotions |
github.com/twmb/franz-go/pkg/kgo | kgo.RequiredAcks(kgo.AllISRAcks()), idempotent producer by default | See Kafka |
github.com/gocql/gocql | Consistency = gocql.LocalQuorum, DC-aware host policy | Cassandra/ScyllaDB |
go.etcd.io/etcd/client/v3/concurrency | Leader election and leases for your own leader-based services | Fencing token = lease revision; see Leader Election |
context.Context deadlines | Bound how long a read waits for a replica to catch up | Fall back to the primary on timeout |
Laravel
Before
Read/write split without any freshness rule: the redirect after checkout starts a new request, so even sticky would not help and the confirmation page reads a replica that has not replayed the insert.
<?php
namespace App\Http\Controllers\Before;
use App\Models\Order;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
// Before: read/write split configured, 'sticky' => false, no session freshness.
// The redirect starts a NEW request, so even 'sticky' => true would not help:
// the confirmation page reads a replica that has not replayed the INSERT yet.
class OrderControllerBefore
{
public function store(Request $request): RedirectResponse
{
$order = Order::create([
'user_id' => $request->user()->id,
'total_cents' => (int) $request->input('total_cents'),
'status' => 'PLACED',
]);
return redirect()->route('orders.show', $order->id);
}
public function show(int $id): View
{
// 404 for a few hundred milliseconds after checkout, longer under load.
$order = Order::findOrFail($id);
return view('orders.show', ['order' => $order]);
}
}After
Read and write connections per home region. Laravel's docs: "If the sticky option is enabled and a 'write' operation has been performed against the database during the current request cycle, any further 'read' operations will use the 'write' connection." When several hosts are listed, "a database host will be randomly chosen for each request".
<?php
// config/database.php (excerpt): one read/write-split connection per home region.
// Documentation-range addresses (192.0.2.0/24, 198.51.100.0/24) stand in for real hosts.
return [
'default' => env('DB_CONNECTION', 'pgsql_eu'),
'connections' => [
// EU home region: one primary, two streaming replicas in the same region.
'pgsql_eu' => [
'driver' => 'pgsql',
'read' => [
'host' => [
env('DB_EU_REPLICA_1', '192.0.2.21'),
env('DB_EU_REPLICA_2', '192.0.2.22'),
],
],
'write' => [
'host' => [env('DB_EU_PRIMARY', '192.0.2.10')],
],
// Reads after a write in the same request go to the write PDO.
'sticky' => true,
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'shop'),
'username' => env('DB_USERNAME', 'shop'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'public',
'sslmode' => 'verify-full',
],
// US home region: same shape, independent cluster (federation by region).
'pgsql_us' => [
'driver' => 'pgsql',
'read' => [
'host' => [
env('DB_US_REPLICA_1', '198.51.100.21'),
env('DB_US_REPLICA_2', '198.51.100.22'),
],
],
'write' => [
'host' => [env('DB_US_PRIMARY', '198.51.100.10')],
],
'sticky' => true,
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'shop'),
'username' => env('DB_USERNAME', 'shop'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'public',
'sslmode' => 'verify-full',
],
// Global directory: which tenant lives in which region. Small, read-mostly.
'directory' => [
'driver' => 'pgsql',
'host' => env('DB_DIRECTORY_HOST', '192.0.2.5'),
'port' => env('DB_PORT', '5432'),
'database' => 'directory',
'username' => env('DB_USERNAME', 'shop'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'public',
'sslmode' => 'verify-full',
],
],
];Cross-request read-your-writes and region pinning. Laravel 13's PreventStaleDatabaseReads middleware "allows subsequent requests in the same session to read recently written data from the write connection"; by default for two seconds, here five. PinTenantRegion runs first and selects the tenant's home-region connection.
<?php
use App\Http\Middleware\PinTenantRegion;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Region pinning must run first so later middleware talks to the right cluster.
$middleware->prepend(PinTenantRegion::class);
// Laravel 13: requests within 5 s of this session's last write read from the
// write connection (cross-request read-your-writes). Needs the session, so web only.
$middleware->web(append: [
PreventStaleDatabaseReads::for(5),
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();<?php
namespace App\Support;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/**
* Home region per tenant. The directory is the only global table; everything
* else about a tenant lives in its home region's cluster.
*/
final class TenantDirectory
{
/** @var array<string, string> region => connection name */
private const CONNECTIONS = [
'eu' => 'pgsql_eu',
'us' => 'pgsql_us',
];
public function homeRegion(int $tenantId): string
{
return Cache::remember("tenant-home:{$tenantId}", 300, function () use ($tenantId): string {
$region = DB::connection('directory')
->table('tenants')
->where('id', $tenantId)
->value('home_region');
return is_string($region) ? $region : 'eu';
});
}
public function connectionFor(string $region): string
{
return self::CONNECTIONS[$region] ?? self::CONNECTIONS['eu'];
}
}<?php
namespace App\Http\Middleware;
use App\Support\TenantDirectory;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
/**
* Region pinning: read locally, write globally (in the tenant's home region).
*
* - The tenant's home region decides the default database connection.
* - A write that reaches the wrong region is redirected with 307 (method and
* body preserved) instead of being written cross-region.
* - The default connection is restored afterwards, which matters under
* Laravel Octane where the application instance is reused between requests.
*/
final class PinTenantRegion
{
public function __construct(private readonly TenantDirectory $directory)
{
}
public function handle(Request $request, Closure $next): Response
{
$tenantId = (int) $request->header('X-Tenant-Id', '0');
if ($tenantId === 0) {
return $next($request);
}
$home = $this->directory->homeRegion($tenantId);
$here = (string) config('app.region', 'eu');
if ($home !== $here && ! $request->isMethodSafe()) {
return redirect()->away(
"https://{$home}.api.example.com".$request->getRequestUri(),
307
);
}
$previous = DB::getDefaultConnection();
DB::setDefaultConnection($this->directory->connectionFor($home));
try {
return $next($request);
} finally {
DB::setDefaultConnection($previous);
}
}
}A replica-aware repository. Each read declares its freshness: fresh() uses usingWritePdo() (documented in Laravel 13: it "returns the callback's result and restores the connection's previous read preference"), bounded() checks the measured lag first, stale() reads the replica.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
// No $connection here: the region middleware sets the default connection,
// so the same model talks to pgsql_eu or pgsql_us depending on the tenant.
protected $fillable = ['tenant_id', 'user_id', 'total_cents', 'status'];
}<?php
namespace App\Repositories;
use App\Models\Order;
use Illuminate\Database\Connection;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* A replica-aware repository: every read states the freshness it needs.
*
* - fresh(): must see the latest committed data (money, stock, auth) -> write PDO
* - bounded(): may be a little stale, but never more than $maxLagSeconds -> replica
* if the replica is within the bound, otherwise the write PDO
* - stale(): lists and reports that tolerate replica lag -> read PDO
*/
final class OrderRepository
{
public function __construct(private readonly ReplicaLag $lag)
{
}
private function connection(): Connection
{
return DB::connection(); // the region middleware chose the default
}
public function fresh(int $orderId): ?Order
{
return $this->connection()->usingWritePdo(
fn () => Order::query()->find($orderId)
);
}
public function bounded(int $orderId, float $maxLagSeconds = 1.0): ?Order
{
if ($this->lag->secondsBehind($this->connection()->getName()) > $maxLagSeconds) {
return $this->fresh($orderId);
}
return Order::query()->find($orderId);
}
/** @return Collection<int, Order> */
public function stale(int $userId, int $limit = 20): Collection
{
return Order::query()
->where('user_id', $userId)
->latest()
->limit($limit)
->get();
}
public function place(int $tenantId, int $userId, int $totalCents): Order
{
// Writes always use the write PDO; with 'sticky' => true the rest of this
// request reads from the primary too.
return Order::query()->create([
'tenant_id' => $tenantId,
'user_id' => $userId,
'total_cents' => $totalCents,
'status' => 'PLACED',
]);
}
}<?php
namespace App\Repositories;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/**
* Measures how far the read side of a connection is behind, cached for 1 s so
* the probe costs one query per second per worker, not one per request.
* A random replica is picked per request by Laravel, so this is the lag of
* whichever replica this worker's read PDO is connected to.
*/
final class ReplicaLag
{
public function secondsBehind(string $connection): float
{
return Cache::store('array')->remember("replica-lag:{$connection}", 1, function () use ($connection): float {
$row = DB::connection($connection)->selectOne(<<<'SQL'
SELECT CASE
WHEN NOT pg_is_in_recovery() THEN 0
WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
ELSE COALESCE(EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()), 0)
END AS lag_seconds
SQL);
return (float) ($row->lag_seconds ?? INF);
});
}
}The Laravel angle
| Laravel 13 feature | Use | Note |
|---|---|---|
'read' / 'write' / 'sticky' connection keys | Read/write split per connection | Hosts in read.host are chosen at random per request |
PreventStaleDatabaseReads::for($seconds) | Read-your-writes across requests in one session | Web group only (needs the session); default connection only |
DB::withoutAffectingStickiness(fn) | Writes (job progress, audit timestamps) that should not force later reads to the primary | Keeps replica reads |
DB::connection()->usingWritePdo(fn) | Force fresh reads for one block (Eloquent included) | Restores the previous preference even on exception |
DB::connection('pgsql::direct') | Bypass a pooler (PgBouncer) for migrations and maintenance | Laravel uses it automatically for migrations when configured |
DB::connection('mysql')->olap(fn) | Vitess/PlanetScale analytical workload | Vitess-specific |
DB::setDefaultConnection() | Region pinning per request | Reset it afterwards under Octane |
| Queued jobs | Run in a new process without the web session | Dispatch with IDs, read with usingWritePdo() in the job when freshness matters |
ShouldQueueAfterCommit / afterCommit() | Do not dispatch before the write commits | Still read from the primary in the job: the replica may lag |
Solving the classic problems
"Order not found" right after checkout
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Primary for the session for N seconds | Laravel PreventStaleDatabaseReads, a cookie with an expiry | One line | Guesses N; extra primary load after writes |
| Position-based routing | Store commit LSN/GTID; read from a replica past it | Exact | Needs probes or WAIT_FOR_EXECUTED_GTID_SET |
| Render from the write's result | Return the created resource in the POST response | No read at all | Only for the page right after the write |
remote_apply on the commit | Commit waits for replay on sync standbys | Replicas always fresh | Commit latency includes replay |
Writes lost after an automatic failover
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Synchronous / quorum standby | ANY 1 (a, b); Patroni synchronous_mode | No acknowledged write lost | Commit latency; writes block if no standby (strict mode) |
Semi-sync AFTER_SYNC | MySQL plugin | Lossless while enabled | Silently async after timeout: alert on Rpl_semi_sync_source_status |
| Bound the window | maximum_lag_on_failover, Redis min-replicas-max-lag | Predictable loss | Not zero |
| Idempotent re-submission | Clients retry with idempotency keys after failover | Recovers lost user actions | Needs API Idempotency |
Split brain
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Consensus-held lease | Patroni/etcd leader key, Raft | Majority decides; minority side cannot win | Needs 3+ voters in separate failure domains |
| STONITH / watchdog | Power off or reboot the old leader | Physical certainty | Needs out-of-band access |
| Epochs and fencing tokens | Storage rejects lower epochs | Works across pauses | Every write path must check |
| Witness / tie-breaker | Third site votes | Two-site clusters become safe | One more site to run |
Conflicting edits in active-active
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Home region per key | Route writes to the owner | No conflicts | Remote writes for travellers |
| CRDT data types | Counters, OR-sets, maps | Automatic convergence | Limited types; metadata growth |
| Version vectors + app merge | Siblings resolved on read | No silent loss | Every reader must merge |
| Per-origin rows | One row per (key, region), aggregate on read | Plain SQL | Aggregation on every read |
-- Schema for the lab and the Laravel examples (PostgreSQL).
-- Global directory (one small cluster, replicated everywhere for reads).
CREATE TABLE tenants (
id bigint PRIMARY KEY,
name text NOT NULL,
home_region text NOT NULL CHECK (home_region IN ('eu', 'us')),
moved_at timestamptz
);
-- Per-region cluster (identical schema in pgsql_eu and pgsql_us).
CREATE TABLE orders (
id bigserial PRIMARY KEY,
tenant_id bigint NOT NULL,
user_id bigint NOT NULL,
total_cents bigint NOT NULL CHECK (total_cents >= 0),
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_user_created ON orders (user_id, created_at DESC);
-- Multi-leader friendly cart: one row per (cart, sku, origin region) so two
-- regions never update the same row; the cart is the sum per sku (a PN-counter
-- in disguise) and a removal is a negative row, not a DELETE.
CREATE TABLE cart_lines (
cart_id uuid NOT NULL,
sku text NOT NULL,
origin text NOT NULL, -- 'eu' | 'us'
delta integer NOT NULL,
PRIMARY KEY (cart_id, sku, origin)
);
-- Each region only increments its own row:
-- INSERT INTO cart_lines VALUES ($1, $2, 'eu', 1)
-- ON CONFLICT (cart_id, sku, origin) DO UPDATE SET delta = cart_lines.delta + EXCLUDED.delta;
-- SELECT sku, sum(delta) AS qty FROM cart_lines WHERE cart_id = $1 GROUP BY sku HAVING sum(delta) > 0;Quorum reads that are still stale
| Cause | Fix |
|---|---|
R + W not greater than N (ONE/ONE) | Use LOCAL_QUORUM on both sides for fresh data |
| Sloppy quorum during an outage | Wait for hinted handoff; repair; do not rely on freshness during outages |
| Concurrent writes resolved by LWW with skewed clocks | NTP/chrony with alerts; avoid read-modify-write; use LWT (Paxos) or CRDTs |
| Failed write left on one replica | Idempotent retries; treat timeouts as "unknown" |
| Node restored from an old snapshot | Repair before it serves reads |
Region outage
| Topology | What happens | Recovery |
|---|---|---|
| Single global leader in the failed region | All writes stop; promote a replica in another region (async: lose the lag) | Fail over with fencing; re-home tenants back later |
| Home region per tenant | Only that region's tenants lose writes; others unaffected | Promote that region's cross-region replica for its tenants |
| Multi-leader | Other regions keep writing; unreplicated writes of the failed region reappear (and may conflict) when it returns | Conflict resolution on reconnect |
Consensus with SURVIVE REGION FAILURE | Survives: majority still elsewhere | Automatic |
Choosing
| Workload / situation | Topology | Extra technique | Reason |
|---|---|---|---|
| Typical OLTP app in one region | Single-leader, async replicas | One sync/quorum standby in another AZ; read-your-writes routing | No conflicts; simplest failover |
| Payments, ledgers, inventory | Single-leader (or consensus) per account/item | Synchronous commit; idempotency keys | One lost or conflicting write costs more than latency |
| Global SaaS with data residency | Single-leader per tenant, leaders in several regions | Directory, 307 to home, cross-region replicas | Local writes for home users, no conflicts |
| Offline-first mobile / desktop | Multi-leader (each device) | CRDTs or version vectors + merge | Devices must write while disconnected |
| Collaborative editing | Multi-leader with OT server or CRDTs | Presence, operation log | Concurrent edits are the point |
| Write-heavy, always-writable key-value (carts, sessions, IoT) | Leaderless | LOCAL_QUORUM, repair, idempotent writes | Tolerates node loss without failover |
| Multi-region with strong consistency | Consensus (Spanner, CockroachDB) | REGIONAL BY ROW, follower reads | Pay the quorum round trip, avoid conflicts |
| Cache | Redis single-leader async | Accept loss; min-replicas-to-write if it matters | A cache can be rebuilt |
| Event log | Kafka leader + ISR | RF=3, min.insync.replicas=2, acks=all | Survive one broker without losing acks |
| Independent customers or business lines | Federation into cells | Per-cell replication; CDC to a warehouse | Blast radius and independent operations |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One Laravel or Go app with one PostgreSQL primary and one standby. Replication is purely for availability: Patroni (or RDS Multi-AZ) promotes the standby, the app reconnects through a VIP, DNS name or HAProxy. The simplest correct setup: one synchronous or quorum standby in a different AZ, no reads from replicas yet, a monthly switchover drill. The only code change is retrying a transaction that failed with a connection error during the switch.
Modular monolith: several modules, read replicas
The app adds read replicas for reporting and catalogue pages. Now every module must declare its read freshness: the billing module reads fresh() from the primary; the catalog module reads stale() from replicas; the orders module uses PreventStaleDatabaseReads. A repository per module (like OrderRepository) keeps the rule in one place, and the reporting module gets its own replica so that a 20-minute report cannot delay replay for the others.
Microservices: each service picks its topology
orders (PostgreSQL, single-leader, sync standby), carts (Cassandra, LOCAL_QUORUM), sessions (Redis, async), events (Kafka, RF=3, acks=all). Across services there is no shared replication: data flows through events and the outbox, so every consumer is effectively an asynchronous replica of the producer's data, with lag, duplicates and out-of-order delivery. A consumer that keeps a copy (event-carried state transfer) must store the source version and ignore older events, which is LWW by version number rather than by clock:
1 orders: UPDATE order 1001 status=PAID, version 7; outbox row in the same transaction
2 relay -> Kafka orders.events (key 1001, acks=all)
3 shipping consumer: stored version 6 -> apply 7
4 redelivery of version 6 after a rebalance -> stored 7 > 6 -> ignoreDistributed data: replicas, caches, regions
Multi-region adds the hard parts of this page: cross-region lag in seconds, the choice between a global leader, home regions, multi-leader and consensus, and read-your-writes across regions. Caches are another replica layer: after a write, invalidate or version the cache and route the next read to a fresh source, or the cache re-fills from a stale replica (see Caching). Clocks matter whenever LWW is used; consistency theory is in CAP & PACELC and Eventual Consistency in Database Systems.
Scaling path: 1x, 10x, 100x
| Load | Shape | What changes |
|---|---|---|
| 1x | Primary + 1 standby | HA only; no replica reads |
| 10x reads | Primary + 3–5 async replicas, pooler, read routing | Freshness classes; lag alerts; reporting replica; cascading replication to protect the primary |
| 10x writes | Bigger primary, then shard | Replication does not scale writes: every replica replays every write |
| 100x, global | Federation into cells or home regions; or distributed SQL | Directory service, per-cell failover, CDC to analytics, cross-region DR drills |
Lab
The simulator lab is a single Go process and was run; the database experiments need containers and are expected, not run.
1. Run the tests and the chaos program (module declares go 1.24; output below is from an actual run):
cd docs/snippets/system-design/replication-topologies/go
go test ./...
go run ./cmd/chaos== 1. async single-leader: leader dies with an unshipped write
t=00 node 0 (epoch 1) commits balance:7=100
t=04 node 0 (epoch 1) commits balance:7=40
t=04 node 0 isolated
t=04 promotion loses acknowledged balance:7=40
t=04 node 1 promoted (epoch 2), fenced old leader: true
writes=2 rejected=0 stale=0 conflicts=0 lostLWW=0 lostFailover=1 splitBrain=0 hints=0/0 repairs=0
== 2. split brain: old leader partitioned, not fenced
t=00 node 0 isolated
t=00 node 1 promoted (epoch 2), fenced old leader: false
t=00 node 0 (epoch 1) commits seat:12A=alice
t=00 node 1 (epoch 2) commits seat:12A=bob
t=00 partition healed
t=01 node 1 refuses seat:12A=alice from epoch 1
t=01 node 0 (epoch 1) diverged, ignores epoch 2 until rewound
t=02 node 0 rewound and rejoined as follower, 1 divergent keys dropped
writes=2 rejected=0 stale=0 conflicts=0 lostLWW=0 lostFailover=1 splitBrain=1 hints=0/0 repairs=0
== 3. multi-leader: same key edited in two regions
t=00 leader 0 accepts profile:9=Ana locally
t=02 leader 0 accepts profile:9=Ana Silva locally
t=02 leader 1 accepts profile:9=Ana S. locally
t=04 node 1 detects conflict on profile:9: "Ana S." vs "Ana Silva", LWW keeps "Ana S."
writes=3 rejected=0 stale=0 conflicts=1 lostLWW=1 lostFailover=0 splitBrain=0 hints=0/0 repairs=0
== 4. leaderless N=3 W=2 R=2 sloppy: partition, hint, heal, read repair
t=00 node 0 isolated
t=00 coordinator 0 writes cart:5=v1 with 2 acks (W=2)
t=00 read via node 1 during the partition: "" fresh=false
t=00 partition healed
t=01 hint for cart:5 handed off to node 1
t=01 read via node 1 after hint delivery: "v1" fresh=true
writes=1 rejected=0 stale=1 conflicts=0 lostLWW=0 lostFailover=0 splitBrain=0 hints=1/1 repairs=1Change Lag, SyncCopies, W, R and Sloppy in cmd/chaos/main.go and predict the counters before running: SyncCopies: 1 in scenario 1 makes lostFailover=0; Sloppy: false in scenario 4 turns the write into quorum not reached: 1 of W=2 while leaving the value on node 0.
2. PostgreSQL replica lag and read-your-writes (expected, not run). With a primary and one streaming replica, on the primary: SELECT pg_current_wal_lsn(); → 0/3000148. Pause replay on the replica with SELECT pg_wal_replay_pause();, insert a row on the primary and run the replica query from postgresql-replication.sql step 3: received advances, replayed stays at 0/3000148, the row is missing, caught_up for the new LSN is f. SELECT pg_wal_replay_resume(); → caught_up = t, the row appears.
3. Synchronous commit blocks without a standby (expected, not run). Set synchronous_standby_names = 'replica_a', stop replica_a, run INSERT ...; COMMIT; on the primary: the session hangs; SELECT wait_event FROM pg_stat_activity shows SyncRep. Cancelling it prints WARNING: canceling wait for synchronous replication due to user request and DETAIL: The transaction has already committed locally, but might not have been replicated to the standby.
4. Cassandra consistency levels (expected, not run). Three nodes, RF=3. Stop one node: CONSISTENCY QUORUM; INSERT ... succeeds; stop a second: INSERT fails with Cannot achieve consistency level QUORUM; CONSISTENCY ONE; INSERT ... succeeds and the coordinator stores hints (nodetool listpendinghints shows them). Start the nodes; hints are replayed; nodetool repair -pr shop reports the ranges it synchronised.
5. Kafka min.insync.replicas (expected, not run). Topic orders with RF=3 and min.insync.replicas=2; stop two brokers; a producer with acks=all logs NOT_ENOUGH_REPLICAS and retries; a producer with acks=1 succeeds (and would lose the records if the last broker failed). kafka-topics.sh --describe --under-min-isr-partitions lists the partition.
Common misconceptions
| Belief | Reality |
|---|---|
| Replicas are backups | Mistakes replicate instantly; keep backups and PITR |
| Synchronous replication means replicas are readable fresh | PostgreSQL on waits for flush, not replay; use remote_apply |
| Semi-sync never loses data | It falls back to async after rpl_semi_sync_source_timeout without failing writes |
| The old primary is down, so it cannot write | It may be partitioned or paused; fence it |
| Multi-leader gives strong consistency across regions | It gives local writes and conflicts |
| LWW keeps the latest write | It keeps the highest timestamp and silently drops concurrent writes |
| R + W > N means linearizable | Sloppy quorums, partial writes, LWW and failures break it |
| W=2 writes to two nodes | It writes to all N and waits for two |
| Hinted handoff replaces repair | Hints expire (3 h in Cassandra); run anti-entropy |
acks=all means every replica | Every in-sync replica, possibly only the leader without min.insync.replicas |
Redis WAIT makes Redis consistent | It narrows, not closes, the loss window |
| Read replicas scale writes | Every replica replays every write; shard or federate to scale writes |
| Federation is the same as sharding | Federation runs independent systems; cross-unit queries are an app concern |
Cheat sheet
| Topic | Remember |
|---|---|
| Topologies | Single-leader: no conflicts. Multi-leader: local writes + conflicts. Leaderless: quorums + repair |
| Default modes | PostgreSQL, MySQL, Redis replicate asynchronously by default |
| Durability | Wait for one more copy (sync, semi-sync, quorum commit, acks=all + min.insync.replicas=2) |
| Read-your-writes | Primary for a few seconds, or position (LSN/GTID) routing |
| Monotonic reads | Pin a session to a replica or carry a minimum position |
| Failover | Detect via consensus lease, promote the most advanced replica, fence the old one, rewind it |
| Split brain | Prevented only by fencing: STONITH, watchdog, epochs, fencing tokens |
| Quorum | R + W > N for overlap; LOCAL_QUORUM in multi-DC Cassandra |
| Sloppy quorum | Keeps writes available; breaks freshness until hints are delivered |
| Repair | Read repair for read keys; Merkle-tree anti-entropy for the rest; within gc_grace_seconds |
| Concurrency | Version vectors (DVVs in Riak) detect it; timestamps do not |
| Resolution | Avoid > CRDT > merge/siblings > LWW (only where loss is harmless) |
| Geo | Home region per tenant, read local, write global, 307 for misplaced writes |
| Kafka | RF=3, min.insync.replicas=2, acks=all, no unclean election |
| Federation | Independent cells per tenant/region; directory in front; CDC for analytics |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A user gets "order not found" after checkout. The app has 'sticky' => true. Why does it still happen, and what fixes it? Must-know
Answer
Answer: sticky only applies within the same request; the redirect is a new request that reads a replica. Fix with PreventStaleDatabaseReads (session-level primary reads for a few seconds), position-based routing (store the commit LSN and read only from a replica past it), or render the confirmation from the POST's result.
2 — PostgreSQL has one synchronous standby with synchronous_commit = on. Can a read on that standby miss a committed row? Important
Answer
Answer: Yes. on waits for the standby to flush the WAL to disk, not to replay it. Only remote_apply makes the commit wait until the standby has replayed the transaction and it is visible to queries.
3 — Patroni promotes a replica after the primary's leader key expires. What stops the old primary from accepting writes if it is only partitioned? Important
Answer
Answer: Patroni on the old primary demotes PostgreSQL when it cannot renew the leader key; the Linux watchdog (with mode: required) reboots the node if Patroni itself hangs. Without that fencing both could accept writes (split brain), and the old primary's writes would be discarded by pg_rewind.
4 — N=3, W=1, R=1. Is a read after a write guaranteed to see it? What about W=2, R=2? Must-know
Answer
Answer: With W=1, R=1 no: R + W = 2 is not greater than 3, the read may hit a replica that missed the write. With W=2, R=2 the sets overlap in at least one node, so a strict-quorum read normally sees it, but sloppy quorums, concurrent writes and LWW can still return older data.
5 — Why does a sloppy quorum make the system more available but less consistent? Must-know
Answer
Answer: It counts acknowledgements from substitute nodes outside the key's home replicas, so writes succeed during outages. A later read from the home replicas may not include any node that has the write until hinted handoff delivers it.
6 — Two regions edit the same profile name concurrently in DynamoDB global tables (MREC). What happens to the two edits? Important
Answer
Answer: DynamoDB resolves by "last writer wins" on its internal timestamp per item: both regions converge on one value and the other edit is discarded without an error.
7 — In the version-vector cart, why must the client send back the context from its last read? Good to know
Answer
Answer: The context tells the server which versions the new write has seen; those are replaced. A write without context (a blind write) is concurrent with everything stored, so it becomes a sibling instead of an overwrite.
8 — Dynamo's union merge of carts never loses an "add to cart". What is the price? Important
Answer
Answer: Removals can be undone: if one sibling removed an item and a concurrent sibling still has it, the union brings it back ("deleted items can resurface"). An OR-Set CRDT with remove tags avoids that.
9 — A Kafka topic has RF=3 and min.insync.replicas=1, producers use acks=all. Two brokers fall out of the ISR. Are writes still accepted and are they safe? Important
Answer
Answer: Yes, they are accepted, because the ISR (just the leader) still meets min.insync.replicas=1, and acks=all then means "the leader alone". If that broker fails, the records are lost. Set min.insync.replicas=2 to refuse writes instead.
10 — A SaaS company wants EU customers' data to stay in the EU and low write latency for everyone. Which pattern, and how are writes from an EU customer travelling in the US handled? Important
Answer
Answer: Home region per tenant (region pinning) with read-local, write-global: the tenant's writes go to the EU primary (redirect with 307 or forward from the US edge), reads in the US use a local replica only if residency rules allow a copy, otherwise they go to the EU too; read-your-writes routing covers the writer's next reads.
11 — What is the difference between database federation and Mastodon-style federation? Good to know
Answer
Answer: Database federation splits one organisation's data into independent clusters (by function, tenant or region) behind a directory. Mastodon (ActivityPub) and Matrix federate servers run by different organisations, each owning its users' data and pushing activities to the others across trust boundaries.
Glossary
| Term | Meaning |
|---|---|
| Replication | Keeping copies of the same data on several nodes |
| Single-leader / leader-follower / primary-replica | One node accepts writes and streams changes to read-only followers |
| Synchronous replication | Commit waits for named replicas to confirm |
| Asynchronous replication | Commit returns after the leader's local commit; replicas catch up later |
| Semi-synchronous | Commit waits for at least one replica to receive the change, falling back to async on timeout (MySQL) |
| Quorum commit | Commit waits for any k of n standbys (ANY k (...) in PostgreSQL) |
remote_apply | PostgreSQL commit level that waits for replay on synchronous standbys |
| Replica lag | Distance between the leader's position and a replica's replayed position |
| Read-your-writes | A user always sees their own writes |
| Monotonic reads | A user never sees older data after newer data |
| Consistent prefix | Writes are seen in an order that respects causality |
| Failover | Replacing a failed leader with a follower |
| Switchover | A planned, clean change of leader |
| Promotion | Turning a follower into the leader (pg_promote()) |
| Split brain | Two nodes accepting writes for the same data at once |
| Fencing | Preventing a deposed leader from doing harm |
| STONITH | "Shoot the other node in the head": power off the old leader |
| Epoch / term / fencing token | A monotonically increasing leadership number checked on every write |
| Watchdog | Hardware or kernel timer that reboots a node that stops renewing it (Patroni) |
pg_rewind | Re-synchronises a former PostgreSQL primary with the new timeline |
| Multi-leader / active-active | Several nodes accept writes and replicate to each other |
| Write conflict | Two concurrent writes to the same key on different leaders |
| Conflict detection | Recognising that two versions are concurrent (version vectors, base versions) |
| Circular topology | Leaders forward changes around a ring |
| Star topology | A hub relays changes between spokes |
| All-to-all topology | Every leader sends to every other |
| Leaderless | Any replica accepts writes; clients use quorums |
| Dynamo | Amazon's 2007 leaderless key-value store paper |
| Quorum, N R W | N replicas; W acknowledgements per write; R answers per read; R + W > N overlaps |
LOCAL_QUORUM | Cassandra level: majority of replicas in the coordinator's data centre |
| Sloppy quorum | Quorum counted on the first N healthy nodes, not necessarily the home replicas |
| Hinted handoff | Substitute node stores a write for an unreachable replica and delivers it later |
| Read repair | Fixing stale replicas found during a read |
| Anti-entropy | Background comparison and repair of replicas |
| Merkle tree | Tree of hashes used to find differing ranges cheaply |
| Version vector | Per-replica counters attached to a value to detect concurrency |
| Dotted version vector (DVV) | Version vector plus the exact dot of each write; fewer false siblings (Riak) |
| Last-writer-wins (LWW) | Keep the version with the highest timestamp; drops concurrent writes |
| Siblings | Concurrent versions stored together and returned on read (Riak allow_mult) |
| CRDT | Data type whose replicas converge under any merge order |
| Operational transformation (OT) | Server transforms concurrent edits against each other (collaborative text) |
| Bounded staleness | Reads may lag by at most a stated time or version bound |
| Geo-replication | Replicas in several regions |
| Home region / region pinning | Each tenant or row has one region that owns its writes |
| Read-local write-global | Reads from the nearest replica, writes to the home region |
| Follow-the-sun | Moving a dataset's home or leaseholder with working hours |
| Redis replication | Asynchronous master-replica replication with replication ID and offset; WAIT for acks |
| ISR | Kafka in-sync replicas: followers caught up within replica.lag.time.max.ms |
acks | Kafka producer durability: 0, 1 or all |
min.insync.replicas | Minimum ISR size for acks=all writes to succeed |
| Unclean leader election | Kafka electing a non-ISR replica, trading durability for availability |
| Federation | Independent clusters per function, tenant or region behind a directory |
| Sharding by tenant | Placing each tenant's data in one shard or cell |
| Cell | A self-contained copy of the stack serving a subset of tenants |
| Patroni | PostgreSQL HA manager using a distributed configuration store |
| Orchestrator | MySQL replication topology manager and failover tool |
| Vitess | MySQL sharding and clustering system |
| ProxySQL | MySQL proxy with read/write split and writer tracking |
| Chaos | Deliberately injecting failures (partitions, kills, lag) to verify behaviour; see Chaos Engineering |
References
- DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store (SOSP 2007), HTML edition: https://www.allthingsdistributed.com/2007/10/amazons_dynamo.html
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 5 Replication (book site): https://dataintensive.net/
- PostgreSQL, High Availability, Load Balancing, and Replication: https://www.postgresql.org/docs/current/high-availability.html
- PostgreSQL, Log-Shipping Standby Servers (synchronous replication): https://www.postgresql.org/docs/current/warm-standby.html
- PostgreSQL, Failover (STONITH): https://www.postgresql.org/docs/current/warm-standby-failover.html
- PostgreSQL, Replication configuration: https://www.postgresql.org/docs/current/runtime-config-replication.html
- PostgreSQL, Comparison of Different Solutions: https://www.postgresql.org/docs/current/different-replication-solutions.html
- PostgreSQL, Monitoring statistics (
pg_stat_replication): https://www.postgresql.org/docs/current/monitoring-stats.html - Apache Cassandra, Dynamo architecture (tunable consistency, LWW): https://cassandra.apache.org/doc/latest/cassandra/architecture/dynamo.html
- Apache Cassandra, Hints: https://cassandra.apache.org/doc/latest/cassandra/managing/operating/hints.html
- Apache Cassandra, Read repair: https://cassandra.apache.org/doc/latest/cassandra/managing/operating/read_repair.html
- Apache Cassandra, Repair: https://cassandra.apache.org/doc/latest/cassandra/managing/operating/repair.html
- Riak KV, Conflict resolution: https://docs.riak.com/riak/kv/latest/developing/usage/conflict-resolution/index.html
- Riak KV, Causal context (vector clocks, DVVs, siblings): https://docs.riak.com/riak/kv/latest/learn/concepts/causal-context/index.html
- Riak KV, Active anti-entropy: https://docs.riak.com/riak/kv/latest/learn/concepts/active-anti-entropy/index.html
- Redis, Replication: https://redis.io/docs/latest/operate/oss_and_stack/management/replication/
- Apache Kafka 4.1, Design (replication, ISR, unclean election): https://kafka.apache.org/41/design/design/
- Apache Kafka 4.1, Producer configs (
acks): https://kafka.apache.org/41/configuration/producer-configs/ - Apache Kafka 4.1, Broker configs: https://kafka.apache.org/41/configuration/broker-configs/
- Amazon DynamoDB, How global tables work (MREC/MRSC, last writer wins): https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/V2globaltables_HowItWorks.html
- CockroachDB, Multi-region overview: https://www.cockroachlabs.com/docs/stable/multiregion-overview
- CockroachDB, Follower reads (
with_max_staleness): https://www.cockroachlabs.com/docs/stable/follower-reads - Patroni documentation: https://patroni.readthedocs.io/en/latest/
- Patroni, Replication modes: https://patroni.readthedocs.io/en/latest/replication_modes.html
- Patroni, Watchdog support: https://patroni.readthedocs.io/en/latest/watchdog.html
- Orchestrator: https://github.com/openark/orchestrator
- Vitess, What is Vitess: https://vitess.io/docs/overview/whatisvitess/
- ProxySQL documentation: https://proxysql.com/documentation/
- Laravel 13, Database: Getting Started (read/write connections, sticky, stale reads): https://laravel.com/docs/13.x/database
- W3C ActivityPub: https://www.w3.org/TR/activitypub/
- Matrix specification: https://spec.matrix.org/latest/
- Martin Kleppmann, How to do distributed locking (fencing tokens): https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html