← Back to Home

🧩 Replication, Sharding and Consistent Hashing

Stale reads, synchronous commit and lost writes measured on a real PostgreSQL primary and replica, plus shard keys and hash schemes compared on a million keys, with an interactive hash ring.

One database server eventually isn't enough. It may not survive a hardware failure, it can't serve every read, or the data and writes simply outgrow one machine. There are two separate answers, often used together:

This article measures the trade-offs of both. A real PostgreSQL 16 primary with a streaming replica shows stale reads, the cost of synchronous replication, and committed data lost in a failover. A simulation of a million keys compares mod-N hashing, consistent hashing, rendezvous hashing and jump hashing for balance and for how much data moves when the cluster changes.

It builds on CAP and consistency models, which described the guarantees in the abstract, and Raft, which is how many systems decide who the leader is.

Leader-Follower Replication

The most common design: one leader (primary) accepts writes; followers (replicas, standbys) receive a stream of its changes and apply them in the same order. In PostgreSQL that stream is the write-ahead log described in How a Database Works Inside: every change is already written to the WAL before it's applied, so replication means shipping the WAL to another machine and replaying it.

Setting up a replica is two commands: copy the primary's data directory while it runs, then start the copy in standby mode. -R writes the connection settings the replica needs:

pg_basebackup -h /run/user/1000/labrepl -p 5501 -U postgres -D replica -R -X stream
pg_ctl -D replica -l replica.log -w start
replica1|streaming|async

That last line is from pg_stat_replication on the primary: one replica, streaming, asynchronous. Asynchronous is the default, and it's what most of the surprises below come from.

Replication Lag and Stale Reads

Replicas are always a little behind. A common pattern sends writes to the primary and reads to replicas, to spread the load. Then a user updates their profile, the page reloads, the read goes to a replica, and they see the old name.

To measure it, the test updated a row on the primary and immediately read it from the replica, 200 times. Then it did the same with the replica's replay delayed by 200 ms (recovery_min_apply_delay), a stand-in for a busy or distant replica:

replica apply delay none (async, same host): stale reads 200/200 | waiting for the write's LSN: median 4.8 ms, max 5.0 ms, then 20/20 fresh
replica apply delay '200ms': stale reads 200/200 | waiting for the write's LSN: median 199.8 ms, max 209.7 ms, then 20/20 fresh

Every read was stale, even with both servers on the same machine and no artificial delay. The replica was about 5 ms behind: enough to receive the WAL, write it, and replay it. A read issued immediately after the write always beat it. Across data centres, lag is tens of milliseconds; under heavy write load or a long-running query on the replica, it can be minutes.

This breaks read-your-writes consistency (#0029). Ways to restore it:

  1. Read your own recent writes from the primary. For example, route a user's reads to the primary for a few seconds after they write anything. Simple and common.
  2. Wait for the replica to catch up to your write. After committing, get the primary's WAL position (pg_current_wal_lsn()); before reading from a replica, wait until it has replayed at least that far:
pc.execute("UPDATE profile SET name = %s WHERE id = 1", (f"v{i}",))
pc.execute("SELECT pg_current_wal_lsn()"); lsn = pc.fetchone()[0]
t = time.perf_counter()
while True:
    rc.execute("SELECT pg_last_wal_replay_lsn() >= %s::pg_lsn", (lsn,))
    if rc.fetchone()[0]: break
    time.sleep(0.002)

That turned 0/20 fresh reads into 20/20, waiting a median of 4.8 ms without delay and about 200 ms with the delay, exactly the lag. The LSN can travel with the user's session (a cookie or a token) so any later request can wait for it. This is a causal consistency token; MongoDB's causal consistency sessions and several other systems work the same way.

  1. Keep each user on one replica (sticky sessions). That doesn't give read-your-writes, but it does give monotonic reads: a user never sees data go backwards, as can happen when consecutive reads hit replicas with different lag.

And monitor lag on every replica (pg_stat_replication.replay_lag on the primary, or now() - pg_last_xact_replay_timestamp() on a replica). Take a replica out of the read pool when it falls too far behind.

Synchronous Replication

With asynchronous replication, the primary confirms a commit as soon as it has written the WAL. With synchronous replication, it waits until a replica confirms too. PostgreSQL offers several levels through synchronous_commit:

Setting Commit returns when Survives primary loss? Replica reads see it immediately?
local (or async) Primary has flushed WAL No: recent commits can be lost No
remote_write Replica has received WAL (written, not flushed to disk) Yes, unless both machines crash No
on Replica has flushed WAL to disk Yes No
remote_apply Replica has replayed it Yes Yes

Measured with 300 single-row inserts each (both servers on one machine, so the network adds almost nothing; most of the ~4.5 ms is the disk flush):

asynchronous replication           : median 4.49 ms, p99 5.56 ms
synchronous, synchronous_commit=remote_write: median 5.06 ms, p99 5.97 ms
synchronous, synchronous_commit=on          : median 5.35 ms, p99 7.21 ms
synchronous, synchronous_commit=remote_apply: median 5.40 ms, p99 8.67 ms

On one machine, synchronous replication cost under a millisecond. Across availability zones it adds a round-trip of 1 to 2 ms to every commit; across regions, 50 to 150 ms. That's the latency price. The availability price shows up when the replica goes away:

stopping the replica, then inserting one row on the primary (sync replication still required)...
  INSERT blocked for 3.0 s; after the cancel it returned SUCCESS
  server said: WARNING:  canceling wait for synchronous replication due to user request
DETAIL:  The transaction has already committed locally, but might not have been replicated to the standby.
  rows visible on the primary afterwards: 1

With the only synchronous replica down, every commit on the primary blocks, indefinitely; the test cancelled it after 3 seconds. Note what the cancellation did: the INSERT returned success, with a warning, and the row is visible. The transaction had already committed locally; only the wait for the replica was cancelled. An application that treats a cancelled or timed-out commit as "didn't happen" can be wrong in both directions, which is the "unknown outcome" from #0038 again, inside the database.

The standard way out is quorum commit: several replicas, and the primary waits for any one (or any k) of them. synchronous_standby_names = 'ANY 1 (replica1, replica2)' keeps durability when one replica is lost, without blocking.

Failover, and the Writes It Loses

When the primary dies, a replica is promoted to become the new primary. With asynchronous replication, anything the replica hadn't received yet is gone. To show it, the test stopped the replica (as if partitioned from the primary), committed 50 more payments on the primary, then killed the primary and promoted the replica:

replica has 1000 payments (caught up)
primary acknowledged 50 more commits: 1050 payments
primary crashes (kill -9); replica is promoted
new primary (former replica): 1000 payments, in recovery: False -> 50 acknowledged commits lost

Fifty payments that the application was told had committed no longer exist. In normal operation the window is smaller (whatever the replica was behind at the moment of the crash, typically milliseconds of writes), but it's never zero with async replication, and it's largest exactly when things are already going wrong: under load, or during a network problem.

Two numbers frame every failover design:

And failover has its own famous failure: split brain. If the old primary isn't really dead, just partitioned, and a replica is promoted, there are now two primaries accepting writes that conflict. Automated failover tools prevent this by fencing (cutting the old primary off: revoking its storage, shutting down its network, or stopping it with a lease it must renew) and by deciding who's primary through consensus. Patroni stores the leader lock in etcd or Consul, which use Raft; managed databases do the equivalent. Never build failover on "the replica couldn't reach the primary, so it promoted itself".

Other Replication Topologies

Multi-leader replication accepts writes at several leaders (often one per region) and replicates between them asynchronously. Writes are fast locally, but two leaders can accept conflicting writes to the same row. Something must resolve them: last-writer-wins by timestamp (which silently discards one write, and depends on clocks, the subject of the next article), merge functions, or CRDTs like the counters in #0029.

Leaderless replication (Dynamo, Cassandra, Riak) writes to and reads from several replicas directly, using quorums: with N replicas, a write waits for W acknowledgements and a read asks R replicas, and when W + R > N, every read overlaps the latest write. Replicas repair each other in the background (read repair, anti-entropy). The quorum simulation in #0029 shows how this behaves under failures.

Sharding: Splitting the Data

Replication copies all the data everywhere, so it doesn't help when the data or the write rate is too big for one machine. Sharding splits it: each shard (partition) owns a subset of the keys, and each shard is usually replicated for availability.

Everything depends on the shard key: the value that decides which shard a row lives on. A good one:

Then there are two ways to map keys to shards:

Range partitioning Hash partitioning
How Shard 1: keys A–F, shard 2: G–M, … shard = f(hash(key))
Range scans (WHERE created_at BETWEEN …) Efficient: one or a few shards Must ask every shard
Sequential keys (timestamps, auto-increment IDs) Hotspot: all new writes hit the last shard Spread evenly
Rebalancing Split a busy range, move half Depends on the hash scheme (below)
Used by HBase, Bigtable, Spanner, CockroachDB, MongoDB (ranged) Cassandra, DynamoDB, Redis Cluster, MongoDB (hashed)

Range-partitioned systems avoid the hotspot by splitting busy ranges automatically and by choosing keys that don't increase monotonically. Hash-partitioned systems give up range scans. Many designs use a compound key: hash on the first part (user_id) to choose the shard, then sort by the second part (created_at) within it, which gives even spreading and efficient "this user's recent items" queries. Cassandra's partition key plus clustering key is exactly this.

Hash Schemes Compared

Hashing a key spreads it pseudo-randomly. The question is how to turn the hash into a node, and what happens when the number of nodes changes. One million keys over 10 nodes, then an 11th node added, or node 3 removed:

scheme (10 nodes)                  | balance                      | rebalancing (ideal: 9.1% on add, 10.0% on remove)
hash mod N                         | busiest node 1.00× average | spread ± 0.3% | add a node:  90.9% moved | remove node3:  90.0% moved
consistent hashing, 1 point/node   | busiest node 2.32× average | spread ±53.1% | add a node:  13.5% moved | remove node3:   2.9% moved
consistent hashing, 10 vnodes      | busiest node 1.20× average | spread ±14.2% | add a node:  11.9% moved | remove node3:  10.7% moved
consistent hashing, 100 vnodes     | busiest node 1.13× average | spread ± 8.3% | add a node:   9.4% moved | remove node3:  11.0% moved
consistent hashing, 1000 vnodes    | busiest node 1.07× average | spread ± 3.2% | add a node:   8.6% moved | remove node3:  10.0% moved
rendezvous (HRW) hashing           | busiest node 1.01× average | spread ± 0.9% | add a node:   9.1% moved | remove node3:   9.8% moved
jump consistent hash               | busiest node 1.01× average | spread ± 0.5% | add a node:   9.1% moved | remove node3:  68.9% moved

(Rendezvous and jump hashing were measured on 200,000 keys to keep the run short.)

Try the ring. Dots are keys, coloured by the node that owns them; a dark outline marks keys that moved in the last change:

Things to try: add a node with 1 vnode and watch only one neighbour lose keys; switch to 50 vnodes and add again; then switch to mod N and add a node.

Rebalancing in Practice

Most production systems don't hash keys straight onto nodes. They add a level of indirection: a fixed, large number of partitions, much larger than the number of nodes, and a map from partitions to nodes.

Adding a node then means moving whole partitions to it, not rehashing keys. The key-to-partition mapping never changes, so routing stays simple, and moves can be throttled and done one partition at a time while the system serves traffic. The cost is choosing the partition count up front: too few and you can't spread across more nodes later; too many and each one carries overhead. Systems that split partitions dynamically (Bigtable, CockroachDB, MongoDB's chunks, DynamoDB) avoid that choice.

Two problems no hash scheme fixes:

Life with Shards

Sharding solves capacity and creates new problems for the application:

Because of all this, shard late. A single modern PostgreSQL server with read replicas handles more than most applications will ever need. Before sharding, try: better indexes (#0036), caching, moving reads to replicas, archiving old data, and splitting unrelated data into separate databases. When you do need to shard, consider a database that does it for you (Citus for PostgreSQL, Vitess for MySQL, or CockroachDB, YugabyteDB, Spanner, Cassandra or DynamoDB) rather than building it into your application.

Key Takeaways

Copied to clipboard!