Skip to the content

Lesson 235 of 296

Replication, read replicas and sharding

What you will learn

  • Replication and why it exists
  • Primary-replica replication and read replicas
  • Synchronous vs asynchronous replication, and replication lag
  • Failover
  • Partitioning and sharding
  • Choosing a shard key
  • Consistent hashing
On this page

Replication

Replication keeps copies of the same data on several machines. Reasons:

  • Availability: if one machine dies, another has the data.
  • Read scaling: spread reads across copies.
  • Latency: put copies near users in other regions.
  • Backups and analytics without loading the main database.

Primary and replicas

The most common setup: one primary (also called leader) accepts all writes; one or more replicas (followers) copy changes from it and serve reads.

writes → Primary ──replicates──> Replica 1 (reads)
                 └─replicates──> Replica 2 (reads)

PostgreSQL does this by streaming its write-ahead log (Lesson 223) to replicas. Managed services (AWS RDS and Aurora, Lesson 254) create read replicas with a click.

Synchronous vs asynchronous

SynchronousAsynchronous
Commit returns whenThe replica has also received the changeOnly the primary has it
Data loss on primary crashNone (for confirmed writes)Recent writes may be lost
Write latencyHigherLower
Typical useWithin a region, for critical dataMost read replicas, cross-region copies

Replication lag

With asynchronous replicas, a replica may be behind by milliseconds or, under load, seconds. Classic bug: a user updates their profile (write goes to the primary), the page reloads and reads from a replica that has not caught up, and the user sees their old profile. Solutions:

  • Read-your-writes: read the user's own recently changed data from the primary (for example for a few seconds after a write, or always for their own profile).
  • Route only lag-tolerant reads (reports, public listings) to replicas.
  • Monitor lag and stop using replicas that fall too far behind.

Failover

If the primary fails, a replica is promoted to primary. Managed databases do this automatically (Multi-AZ in AWS RDS, typically within a minute or two). Concerns: losing writes that had not replicated yet, and split brain (two nodes both thinking they are primary), which is prevented with consensus or fencing. Applications must reconnect and retry.

Multi-primary

Some systems accept writes on several nodes (multi-region active-active setups, Cassandra, DynamoDB global tables). They then need conflict resolution (last write wins, merging, CRDTs). Much more complex; use only when required.

Partitioning and sharding

When one machine cannot hold the data or handle the writes, split the data:

  • Partitioning within one database: PostgreSQL can split a big table into partitions (by month, by tenant) so queries and maintenance touch smaller pieces.
  • Sharding across machines: each shard is a separate database holding a subset of rows, chosen by a shard key.
StrategyHowProsCons
RangeShard by ranges of the key (A to F, G to M; or by date)Range queries stay on one shardHot spots (all new data hits the latest range)
Hashhash(key) mod NEven distributionRange queries hit every shard; changing N moves most keys
Directory / lookupA table maps each key (tenant) to a shardFlexible; move big tenants on their ownThe lookup service is extra infrastructure
Consistent hashingKeys and shards placed on a ringAdding a shard moves only a small share of keysMore complex

Choosing a shard key

A good shard key:

  • Spreads load evenly (high cardinality, no hot values).
  • Matches the main access pattern, so most queries hit one shard. For a SaaS app, tenant_id is usually ideal: each tenant's data lives together.
  • Rarely changes.

Costs of sharding: cross-shard queries and joins are hard, transactions across shards need special techniques, rebalancing is work, and every query must know the shard key. So shard last: first optimise queries and indexes, add caching, add read replicas, scale vertically, and partition tables. Many large companies run on a few large PostgreSQL instances for a long time; distributed SQL databases (CockroachDB, Spanner, Aurora DSQL, Citus) can hide some of the complexity.

Consistent hashing

With hash(key) mod N, changing N from 4 to 5 servers changes the result for most keys, so almost all cached data or stored rows would move. Consistent hashing places servers at points on a circle of hash values; each key belongs to the next server clockwise. Adding a server only takes keys from its neighbour. Virtual nodes (each server at many points) make the distribution even.

TypeScript
import { createHash } from "node:crypto";

function hash32(value: string): number {
  return createHash("md5").update(value).digest().readUInt32BE(0);
}

export class ConsistentHashRing {
  private ring: { point: number; node: string }[] = [];

  constructor(nodes: string[], private readonly virtualNodes = 100) {
    for (const node of nodes) this.add(node);
  }

  add(node: string): void {
    for (let i = 0; i < this.virtualNodes; i++) this.ring.push({ point: hash32(`${node}#${i}`), node });
    this.ring.sort((a, b) => a.point - b.point);
  }

  remove(node: string): void {
    this.ring = this.ring.filter((entry) => entry.node !== node);
  }

  nodeFor(key: string): string {
    if (this.ring.length === 0) throw new Error("No nodes in the ring");
    const h = hash32(key);
    let lo = 0;
    let hi = this.ring.length;
    while (lo < hi) {
      const mid = (lo + hi) >>> 1;
      if (this.ring[mid]!.point < h) lo = mid + 1;
      else hi = mid;
    }
    return this.ring[lo % this.ring.length]!.node;
  }
}

nodeFor uses binary search (Lesson 125) to find the first point at or after the key's hash, wrapping around to the start. Tested with 10,000 keys: going from 4 to 5 nodes moved 2,116 keys (about 21%) with consistent hashing, and every one of them moved to the new node, which is exactly the share it should take. With hash mod N, 7,975 keys (about 80%) changed server. Used by Redis Cluster-style systems, Cassandra, DynamoDB and CDNs.

How to say it in an interview

"Replication copies data for availability and read scaling: a primary takes writes and replicas serve reads, usually asynchronously, which brings replication lag, so I route a user's reads of their own recent writes to the primary. Failover promotes a replica, and applications must reconnect and retry. When one machine cannot handle the data or writes, I partition and then shard by a key that spreads load and matches the main access pattern, typically tenant ID in SaaS. Hash sharding spreads evenly but breaks range queries, and consistent hashing with virtual nodes means adding a shard only moves a small share of keys. I shard last, after indexes, caching, replicas and vertical scaling."

Key words

WordMeaning
ReplicationKeeping copies of data on several machines
Primary / replicaThe node that takes writes / nodes that copy it
Read replicaA replica used to serve reads
Replication lagHow far a replica is behind the primary
FailoverPromoting a replica when the primary fails
Split brainTwo nodes both acting as primary
PartitioningSplitting a table into pieces
ShardingSplitting data across separate databases
Shard keyThe value deciding which shard holds a row
Consistent hashingHashing that moves few keys when nodes change

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.