Scaling Databases: Replication, Partitioning and Sharding

Scale reads with replicas, scale writes with sharding, choose shard keys, use consistent hashing, and understand the costs of distributed data.

Advanced · about 6 hours · difficulty 4/5

Learn first: Caching and CDNs, Transactions, ACID and Concurrency Control

The database is usually the first real bottleneck. Scaling it well is a core system design skill and builds directly on the DBMS section.

Replication

  • Leader-follower (master-slave): writes go to the leader, reads can go to followers. Scales reads and adds failover.
  • Synchronous vs asynchronous replication: sync is safer but slower; async risks losing recent writes and causes replication lag, so a user may not see their own update ("read your own writes" problem).
  • Multi-leader and leaderless (quorum-based, like Cassandra and DynamoDB) replication for multi-region writes, at the cost of conflict resolution.
  • Failover: promoting a follower when the leader dies, and the danger of split brain.

Partitioning and sharding

  • Vertical partitioning: split tables or columns by feature (users DB, orders DB).
  • Horizontal sharding: split rows of one table across machines.
  • Shard key choice is everything: range-based (easy range queries, risk of hot spots) vs hash-based (even spread, no efficient ranges) vs directory-based (a lookup service).
  • Consistent hashing places nodes and keys on a ring so adding or removing a node moves only a small fraction of keys. Virtual nodes smooth the distribution.

Costs of sharding

  • Cross-shard joins and transactions become hard or impossible.
  • Rebalancing when shards grow unevenly.
  • Hot partitions from celebrity users or trending items.
  • Global unique IDs: use UUIDs, Snowflake-style IDs, or ticket servers instead of auto-increment.

Order of operations in practice

Optimise queries and add indexes, then cache, then read replicas, and only then shard. Sharding is a big operational commitment.

Good enough to move on: you can choose a shard key for a given access pattern, explain consistent hashing on a whiteboard, and describe the replication lag problem and one fix.

Key concepts

  • Leader-follower replication
  • Sync vs async replication and lag
  • Multi-leader and leaderless replication
  • Vertical partitioning
  • Horizontal sharding and shard keys
  • Consistent hashing
  • Hot partitions and rebalancing
  • Distributed ID generation

Mini project

Implement consistent hashing with virtual nodes in your DSA language, simulate distributing 1 million keys over 5 nodes, then add and remove a node and measure how many keys move compared with simple modulo hashing.

Check yourself

Why does hash(key) mod N perform badly when you add a new database server, and how does consistent hashing fix it?

Free resources