Database Sharding and Replication

When a single database reaches its limits in CPU, disk I/O, storage, or availability, distributed systems rely on two complementary techniques: replication (copying the same data onto multiple nodes to scale reads and survive crashes) and sharding (splitting different subsets of rows across multiple nodes to scale writes and total storage).

Replication vs. Sharding at a Glance

Although both add more database machines, they solve different bottlenecks — and large production databases almost always combine them (every shard has its own replicas for high availability).

Comparison of database replication vs sharding: Replication copies all rows from Primary DB to Replica 1 and Replica 2 to scale reads and availability; Sharding uses a Shard Router to split Users A-M onto Shard 1 and Users N-Z onto Shard 2 to scale writes and storage Comparison of database replication vs sharding: Replication copies all rows from Primary DB to Replica 1 and Replica 2 to scale reads and availability; Sharding uses a Shard Router to split Users A-M onto Shard 1 and Users N-Z onto Shard 2 to scale writes and storage
Replication copies the full dataset across nodes; sharding splits rows across independent shards · Made with Akriti
Dimension Database Replication Database Sharding (Horizontal Partitioning)
What each node holds A complete copy of the dataset A disjoint subset of the dataset
Primary goal Scale reads, high availability, regional failover Scale writes and total storage past one machine
Main trade-off Replication lag (stale reads) or sync write latency Cross-shard joins, distributed transactions, resharding
Typical trigger Read-heavy workload or zero-downtime failover needs Single primary saturates write IOPS or disk capacity

How Database Replication Works

  1. Primary-Replica (Single-Leader) Replication: All writes go to one primary node, which streams its write-ahead log (WAL / binlog) to one or more read replicas. Applications route read queries across replicas (often behind a load balancer).
    • Asynchronous replication: Primary acknowledges writes immediately (fast, AP-leaning), but replicas may briefly lag behind and recent writes can be lost if the primary dies mid-flight.
    • Synchronous replication: Primary waits for at least one replica to confirm the write before acknowledging (stronger consistency, CP-leaning in CAP theorem terms, higher write latency).
  2. Multi-Primary (Multi-Leader) Replication: Multiple nodes accept writes (for example, one primary per geographic region), synchronizing asynchronously. Low local write latency, but requires conflict resolution when two regions update the same row simultaneously.
  3. Leaderless Replication: Clients write directly to multiple nodes in parallel using quorum reads and writes (W + R > N), used in Amazon DynamoDB and Apache Cassandra.

How Database Sharding Works

Sharding picks a shard key (such as userId, tenantId, or orderId) to route every row to a specific shard (for deeper trade-offs on key selection, salting, and rebalancing, see Partitioning Strategies):

  • Range-Based Sharding: Splits keys into contiguous ranges (e.g., A–M on Shard 1, N–Z on Shard 2, or by date). Range queries (WHERE created_at BETWEEN ...) hit a single shard, but sequential keys (like timestamps or auto-increment IDs) create a hot shard where all new writes land on the latest partition.
  • Hash-Based Sharding: Applies a hash function to the shard key (usually via consistent hashing) to spread writes evenly across shards. Prevents write hotspots, at the cost of making range scans scatter across every shard.
  • Directory-Based Sharding: A lookup service maps each key or tenant to its shard explicitly. Flexible for moving large tenants to dedicated shards, but the lookup table itself must be heavily cached and highly available.

Common Challenges (and How Teams Handle Them)

  • Hot partitions (celebrity keys): Even with hash sharding, one giant tenant or viral account can overload a single shard. Mitigate with composite shard keys (key salting), dedicated shards for huge tenants, and front-end caching.
  • Cross-shard joins and transactions: SQL JOINs and ACID transactions across shards are slow or unsupported. Pick a shard key that keeps related entities co-located (for example, sharding orders and order_items by customerId), and use asynchronous messaging or Saga distributed transactions for cross-shard workflows.
  • Resharding pain: Moving data from 4 shards to 8 shards without downtime is complex. Plan ahead using logical shards (many virtual shards mapped onto fewer physical machines) or consistent hashing so splits move minimal data.
  • Read-after-write consistency under replication lag: After a user updates their profile on the primary, immediately reading from an async replica might show the old profile. Route a user’s own reads to the primary for a few seconds after a write (or track replication LSNs).

When to Shard (and When Not To)

Sharding adds serious operational complexity — treat it as a last resort, not a day-one default. Before sharding, exhaust simpler steps in order:

  1. Tune SQL queries and database indexes.
  2. Add Redis caching and a CDN to offload read traffic.
  3. Add read replicas to scale read throughput.
  4. Scale the primary vertically (faster NVMe, more RAM/CPU) or archive cold historical rows.
  5. Split by service boundary (database-per-service — avoiding common coupling).

Only shard a table when a single domain’s write throughput or dataset size genuinely outgrows one machine.

FAQs

Is database partitioning the same as network partitioning in the CAP theorem? No — they are completely different concepts. Database partitioning (sharding) intentionally splits data across multiple machines for scale. A network partition in the CAP theorem is an unplanned network failure that breaks communication between nodes.
Can you use sharding and replication together? Yes, and almost every production sharded database does. Sharding splits the dataset across nodes so writes and storage scale horizontally, while each shard maintains 2–3 replicas so losing a single machine never takes that shard’s users offline.
How do I choose a good shard key? Pick a high-cardinality, immutable column that appears in your most frequent queries (like tenantId or userId) and distributes writes evenly. Avoid monotonically increasing timestamps or low-cardinality fields like country or status, which create severe hot shards.
Why do people avoid sharding until necessary? Once a table is sharded, you lose cheap cross-shard JOINs, global UNIQUE constraints, and simple single-node ACID transactions, while gaining operational complexity around backups, schema migrations, and rebalancing hot shards.