09. Replication & Sharding
Where this fits: You picked a database and modeled your data. Now traffic grows โ reads slow down, disks fill up, writes pile up. This lesson covers the two classic answers: copy the data (replication) and split the data (sharding).
Learning goals
By the end of this lesson, you should be able to:
- Explain replication using a primary-replica (master-copy) analogy
- Describe replication lag, why it happens, and how apps cope with stale reads
- Outline failover steps when a primary database dies
- Explain sharding (horizontal partitioning) and when you need it
- Choose a shard key and predict hot shard problems
- Build intuition for consistent hashing without heavy math
- Use a decision tree to choose replicas vs cache vs sharding
- Sketch how replication + sharding combine in real systems
The scaling problem โ one database, many hungry apps
A single database server has limits:
- CPU โ query processing, index maintenance
- Memory โ buffer cache, connections
- Disk I/O โ reads and writes to SSD
- Disk size โ you cannot store infinite rows on one machine
- Network โ bandwidth to app servers
Two different problems need two different tools:
| Problem | Symptom | Tool |
|---|---|---|
| Too many reads | SELECT queries slow; CPU high on reads | Replication (+ caching) |
| Too many writes or too much data | INSERT/UPDATE bottleneck; disk full | Sharding (or different store) |
Everyday analogy โ a popular restaurant:
- Replication = printing extra copies of the menu and hiring more waiters to read orders to customers โ the kitchen (primary) still cooks every dish.
- Sharding = opening multiple kitchens, each handling a subset of dishes โ now you can cook more meals in parallel.
Part 1: Replication (read scaling + availability)
Replication copies data from a primary (leader, master) to one or more replicas (followers, read replicas).
Primary-replica analogy โ the teacher and photocopies
Imagine a teacher ( primary ) who writes the official grade book. Every hour, the school makes photocopies ( replicas ) for tutors who help students look up grades.
- Writes (new grades) go only to the teacher's master book.
- Reads (students asking "what's my score?") can use photocopies โ faster, spread across many tutors.
- If a tutor's copy is from this morning but a grade was entered five minutes ago, the student might see stale info โ that's replication lag.
Benefits of replication
| Benefit | Explanation |
|---|---|
| Read throughput | Spread SELECT queries across N replicas |
| High availability | If primary dies, promote a replica (failover) |
| Geographic proximity | Replicas in EU and US โ reads closer to users |
| Backup / reporting | Run heavy analytics on replica without hurting primary |
Costs and caveats
| Cost | Explanation |
|---|---|
| Replication lag | Replicas are often milliseconds to seconds behind |
| Write bottleneck unchanged | All writes still hit primary (in classic setup) |
| Complexity | Monitoring lag, failover drills, split-brain risk |
| Storage multiplied | Each replica stores a full copy |
Sync vs async replication (intuition)
| Mode | Behavior | Trade-off |
|---|---|---|
| Synchronous | Primary waits for replica to confirm before ACKing write | Stronger durability; higher write latency |
| Asynchronous | Primary ACKs immediately; replica catches up later | Faster writes; replica may be stale |
Most web apps use async replication for read replicas and accept small lag.
Replication lag โ what it looks like in products
Timeline:
T0: User updates profile name to "Alice" on PRIMARY โ success
T1: User refreshes page โ read from REPLICA (still says "Alicia")
T2: Replication catches up โ replica now says "Alice"
Mitigations:
| Strategy | How it works |
|---|---|
| Read-your-writes | After a write, route that user's reads to primary for a few seconds |
| Session stickiness | Same user โ same replica (imperfect) |
| Client versioning | Return version: 7 with write; client sends If-None-Match |
| Accept staleness | OK for public profiles, not OK for bank balance |
Failover โ when the primary dies
Failover = automatically or manually promoting a replica to become the new primary.
Failover steps (simplified)
- Detect failure โ health checks, heartbeat timeout, operator alert
- Choose new primary โ usually the most caught-up replica
- Promote replica โ elevate to read-write role
- Reconfigure apps / DNS / load balancer โ point writes to new primary
- Rebuild old primary โ when it returns, make it a replica
Everyday analogy: The head chef calls in sick. The sous chef (replica) takes over the kitchen (promotion). Waiters (apps) are told to give orders to the sous chef now. When the head chef returns, they might work as line cook (replica) until next rotation.
Failover risks beginners should know
| Risk | What happens |
|---|---|
| Split-brain | Two nodes both think they're primary โ conflicting writes |
| Data loss | Async replication: writes not yet replicated are lost |
| Flapping | Unstable network triggers repeated failovers |
| App misconfiguration | Apps still sending writes to dead primary |
Managed databases (AWS RDS, Google Cloud SQL, PlanetScale) automate much of this. Self-hosted Postgres/MySQL requires tools like Patroni, Orchestrator, or operator runbooks.
Part 2: Sharding (write + storage scaling)
When one primary cannot handle write volume or data size, shard (partition) data across multiple independent databases.
Each shard holds a subset of rows โ typically the same schema on each shard.
Everyday analogy โ apartment mailboxes:
Instead of one giant inbox for an entire city (one DB), each building has its own bank of mailboxes (shards). Mail sorted by address (shard key) goes to the right building. You never search every building to find one letter โ if you know the address.
Replication vs sharding โ side by side
| Replication | Sharding | |
|---|---|---|
| Copies | Same full dataset on each node | Different subset on each shard |
| Fixes | Read capacity, failover | Write capacity, storage size |
| Writes | Still one primary (classic) | Spread across shards |
| Complexity | Lower | Much higher |
| Cross-row queries | Easy (same DB) | Hard (cross-shard) |
Production systems often combine both: each shard has its own primary + replicas.
Choosing a shard key
The shard key determines which shard owns a row.
# Simple hash sharding (conceptual)
def shard_for(user_id: int, num_shards: int) -> int:
return hash(user_id) % num_shards
Shard key options
| Shard key | Example use | Pros | Cons |
|---|---|---|---|
user_id | Social apps, SaaS | Most queries scoped to one user | Celebrity / power user โ hot shard |
tenant_id | B2B multi-tenant | Keeps one customer's data together | Huge enterprise tenant dominates a shard |
hash(id) | URL shortener, sessions | Even spread | Range queries across all shards |
geo_region | Compliance (EU data in EU) | Legal residency | Uneven population density |
time (month) | Logs, events | Easy archival | Recent month = hot shard |
Goal: Even distribution + queries usually hit one shard.
Hot shards โ when one mailbox is overflowing
A hot shard receives disproportionate traffic or data compared to siblings.
Shard 0: 10 million users (normal)
Shard 1: 10 million users (normal)
Shard 2: 1 user (celebrity) + 50 million followers' fanout โ HOT
Symptoms: One shard's CPU/disk maxes while others are idle; p99 latency spikes for unlucky users.
Mitigations:
- Split hot shard further (sub-shard by secondary key)
- Separate hot tenants to dedicated shard
- Cache aggressively on hot keys
- Rate-limit abusive keys
Cross-shard queries โ the hard part
Operations that need all shards are expensive:
| Operation | Difficulty |
|---|---|
GET user 42's profile (shard by user_id) | โ Single shard |
GET all users named 'Alice' (no shard key in query) | โ Scatter-gather all shards |
JOIN orders ร users on different shard keys | โ Very painful |
Global ORDER BY created_at LIMIT 10 | โ Merge from all shards |
Design rule: Structure data so 99% of queries are single-shard.
Consistent hashing โ intuition without the math exam
When you add or remove shards, naive hash(key) % N remaps most keys to new shards โ cache stampedes, mass data migration.
Consistent hashing maps keys and shards onto a ring. When a shard is added/removed, only neighboring keys move.
Everyday analogy โ clock faces:
Imagine keys placed around a clock. Each shard "owns" the arc from the previous shard to itself. Add a new shard at 3 o'clock โ only keys between 12 and 3 move to the new shard. Keys at 6 and 9 stay put.
Where you'll see it:
- Distributed caches (Memcached clients, Redis Cluster)
- Dynamo-style databases (DynamoDB, Cassandra)
- Load balancers (sticky routing)
You don't need to implement it โ know why it exists: minimal remapping when cluster size changes.
Resharding โ growing from 4 to 8 shards
Phase 1: 4 shards, data grows
Phase 2: Add 4 more shards (8 total)
Phase 3: Background job copies/migrates key ranges
Phase 4: Dual-write or read-from-new during migration
Phase 5: Decommission old mapping
Resharding is a planned project, not a button click. This is why some teams use managed sharding (Vitess, Citus, DynamoDB) or design for growth early.
Beginner decision tree
START: Database feels slow or full
โโ Is it mostly READ slowness?
โ โโ Yes โ Add caching (lesson 10)
โ โ + read replicas (replication)
โ โโ No โ continue โ
โ
โโ Is WRITE rate or total DATA too big for one machine?
โ โโ Yes โ Consider sharding OR different store (Cassandra, etc.)
โ โโ No โ Optimize queries, indexes, hardware, connection pooling
โ
โโ Need multi-region disaster recovery?
โ โโ Cross-region replicas + failover plan
โ
โโ Need legal data residency (EU only)?
โโ Geo-sharding by region
Worked example: URL shortener
Data: short_code โ long_url
Access pattern: Redirect by short_code only โ perfect single-key lookup.
Shard = hash(short_code) % N
Redirect flow:
1. hash("aZ9kQ2") % 8 โ shard 3
2. SELECT long_url FROM urls WHERE short_code = 'aZ9kQ2' (on shard 3)
3. 302 redirect
Why sharding works cleanly: No cross-shard joins. Each redirect is independent.
Add replication: Each shard has primary + replica; redirects read from replica; new URL creation writes to primary.
Worked example: Social app (harder)
Access patterns:
- User timeline:
user_idscoped โ shard byuser_idโ - Global trending topics: needs data from all shards โ
- Friends of friends: graph traversal across users on different shards โโ
Lesson: Sharding fits key-scoped workloads. Graph-like queries often need a graph DB, denormalization, or separate search/social graph service.
Comparison table โ scaling tactics
| Tactic | Scales reads | Scales writes | Scales storage | Complexity |
|---|---|---|---|---|
| Better indexes | โ | โ | โ | Low |
| Read replicas | โ โ | โ | โ | Medium |
| Cache (Redis) | โ โ | โ | โ | Medium |
| Sharding | โ (via parallelism) | โ โ | โ โ | High |
| Read/write split DB | โ | Partial | โ | Medium |
Common mistakes
| Mistake | Reality |
|---|---|
| "We'll add replicas to fix write slowness" | Replicas don't split write load on primary |
| Ignoring replication lag in UX | Users see stale data after their own edits |
| Sharding too early | Operational nightmare for 10k users โ vertical scale + cache first |
Bad shard key (e.g., created_at only) | All new data hits one shard |
| Cross-shard JOINs in hot path | Latency explosion |
| No failover drill | Promotion works in theory, fails in production |
| Forgetting connection limits per shard | 8 shards ร 500 connections = 4000 connections to manage |
Interview phrases that sound solid
- "Reads go to read replicas; writes go to the primary. We route post-write reads to primary for read-your-writes."
- "We shard by
hash(user_id)to spread load; celebrity users get a dedicated sub-shard to avoid hot spots." - "Global leaderboards are not sharded queries โ we maintain a separate Redis sorted set updated async."
- "Failover is automated via RDS Multi-AZ / Patroni with a 30-second RTO target."
Check your understanding
Questions
- Does adding read replicas increase the primary's write capacity?
- What is replication lag, and name one way to mitigate it for a user who just updated their profile?
- Explain sharding in one sentence using the mailbox analogy.
- What is a hot shard? Give one cause and one mitigation.
- Why are cross-shard JOINs problematic?
- Why is
hash(short_code) % Na good shard strategy for a URL shortener? - What is consistent hashing useful for?
- Walk through the first three steps of failover when a primary dies.
Answers
Click to reveal answers
-
No. In classic primary-replica setup, all writes still go to the primary. Replicas only help read throughput and availability.
-
Replication lag is the delay before changes on the primary appear on replicas. Mitigation: read-your-writes โ after updating profile, route that user's reads to the primary (or wait until lag < threshold).
-
Sharding splits data across multiple databases like separate banks of mailboxes โ each piece of mail (row) goes to one building (shard) based on address (shard key), so no single inbox holds everything.
-
A hot shard gets far more traffic/data than others. Cause: sharding by
user_idwhen one celebrity has massive fanout. Mitigation: sub-shard the hot user, dedicated shard, or heavy caching. -
Each shard only holds part of the data. A JOIN needs rows from multiple shards โ scatter-gather across the network, slow merge, no single-query optimizer.
-
Every redirect looks up only
short_codeโ hash distributes codes evenly, each lookup hits exactly one shard, no cross-shard queries needed. -
Consistent hashing minimizes how many keys move when nodes are added or removed from a cluster โ used in distributed caches and Dynamo-style stores.
-
(1) Detect primary failure via health checks. (2) Choose the best replica (most up-to-date). (3) Promote it to primary and repoint applications/load balancers to send writes to it.
Quick reference card
Replication โ copy full dataset; scale READS; failover
Lag โ replicas behind primary; use read-your-writes
Sharding โ split rows across DBs; scale WRITES + storage
Shard key โ even spread + single-shard queries
Hot shard โ uneven load; fix key choice or split/cache
Consistent hashing โ minimal key movement when nodes change
Decision โ reads slow? replicas + cache | writes big? shard
Next: 10. Caching โ the fast layer in front of your database.