Skip to content
UniCircle
MediumDesignDatabases

Database replication vs sharding

Question SD-107

Your app's single database server is struggling. Explain replication and sharding: what problem each solves, how they work, and the new problems each introduces. How would you pick a shard key for a table of user orders?

Show hints

One copies the data; the other splits it.

Show the explanation

Model answer.

Replication — copying the same data to multiple servers

  • Typical setup: leader–follower (primary–replica). All writes go to the leader, which streams changes to followers; reads can be served by followers.
  • Solves: read scaling and high availability — if the leader fails, a follower can be promoted.
  • Synchronous replication waits for a follower to confirm each write (safer, slower); asynchronous does not (faster, but recent writes can be lost on failover).
  • New problems:
  • Replication lag: a user updates their profile, the next read hits a lagging replica, and the old data appears. Fix with read-your-writes routing (send that user's reads to the leader for a short time).
  • Failover complexity, e.g. avoiding two leaders ("split brain").
  • It does not scale writes — every replica still applies every write.

Sharding (horizontal partitioning) — splitting data across servers

  • Each shard holds a subset of rows, e.g. users 1–1M on shard A and 1M–2M on shard B.
  • Solves: write throughput and storage beyond one machine.
  • Strategies:
  • Range-based: by ID or date ranges; simple, supports range scans, but can create hot spots (all new orders land on the latest shard).
  • Hash-based: shard = hash(key) mod N; spreads load evenly, but range queries span all shards and changing N moves most data — consistent hashing reduces data movement when shards are added.
  • Directory-based: a lookup table maps keys to shards; flexible but adds a lookup service.
  • New problems: cross-shard joins and transactions are hard, resharding is painful, and uneven keys create hot shards.

Shard key for orders

  • Use user_id (hashed): a user's orders live together, so "show my orders" hits one shard, and users spread load evenly.
  • Avoid order date alone (all current writes go to one shard) and low-cardinality keys like country.

In practice the two are combined: each shard is itself replicated for availability.

Follow-up: "What would you try before sharding?" Indexes and query tuning, caching, read replicas, vertical scaling and archiving old data.

Original UniCircle question. Last reviewed 28 Oct 2026.