Component Architecture · Phase 2: Core Infrastructure
Database Scaling: Sharding, Partitioning & Replication
Master horizontal database scaling: Single-Leader vs Leaderless replication, replication lag anomalies, sharding strategies, and Consistent Hashing with virtual nodes.
Primary specification: Consistent Hashing and Random Trees (Karger et al.)
Lesson 15 of 33
1d streakThe Architectural Question
A single database reaches write throughput and storage capacity limits. Naive modulo sharding (`hash(id) % N`) forces rebalancing the entire database when adding a node.
Core Engineering Objectives
- Replication topologies: Single-Leader, Multi-Leader, and Leaderless (Dynamo quorum: R + W > N)
- Replication lag anomalies: Read-your-own-writes consistency, monotonic reads, and consistent prefix reads
- Consistent Hashing ring with virtual nodes (vnodes) for uniform partition distribution without reshuffling
Interactive system trace
Watch the architecture make its key decision
Switch scenarios, predict the next active component, and step through the request or failure path.
Healthy routing
Database Sharding
Read customer M-204 using the first letter as the shard key.
Shard key
customer M-204
First letter is the routing key
Partition map
A–H | I–P | Q–Z
Apply deterministic range rule
Partition load
34%
Partition load
33%
Partition load
33%
A stable routing rule identifies one owner; it does not guarantee balanced traffic when one key is disproportionately popular.
The API includes customer key M-204 with the request.
Why it matters: Without the shard key, the router may need an expensive scatter-gather.
1. What is it & Why it Matters
A single monolithic database server hits physical ceilings: NVMe throughput caps at ~7–14 GB/s, memory buses saturate, and replication threads lag behind master writes. Once your dataset exceeds 5–10 Terabytes or write volume surpasses 20,000 writes/sec, you must partition your database horizontally across independent nodes. This is Database Sharding.
Sharding is a One-Way Architectural Door
2. Sharding Strategies: Range vs. Hash vs. Directory
Range-Based Sharding
Data is partitioned based on discrete key ranges (e.g. User IDs 1–1,000,000 -> Shard 1). Excellent for range scans, but creates catastrophic write hotspots on auto-incrementing timestamps or sequential IDs.
Hash-Based Sharding
Applies a hash function to the shard key: `shard_id = hash(key) % N`. Disperses writes uniformly across all nodes, but turns range scans into multi-shard scatter-gather queries.
Directory-Based Lookup Sharding
Maintains a centralized lookup mapping table that tracks which shard owns each entity. Highly flexible for moving individual enterprise tenants, but introduces an extra network hop and a critical SPOF.
| Strategy | Write Distribution | Range Query Efficiency | Resharding Complexity | Hotspot Risk |
|---|---|---|---|---|
| Range-Based | Skewed (creates hot intervals) | Exceptional (local to 1 shard) | Easy (split boundary ranges) | High (sequential writes hit newest shard) |
Modulo Hash (key % N) | Uniform | Abysmal (scatter-gather all N shards) | Catastrophic (adding 1 node relocates ~N/(N+1) keys) | Low (except on celebrity keys) |
| Consistent Hashing | Uniform with Virtual Nodes | Abysmal (scatter-gather required) | Minimal (only K/N keys relocated on node add) | Low |
| Directory-Based Lookup | Customizable per tenant | Moderate (lookup routes queries) | Simple (update pointer in directory) | Low (can move hot tenant to dedicated shard) |
3. Modulo Collapse & Scatter-Gather Tail Amplification
- 01The Modulo Re-Sharding Catastrophe: Under naive
shard = hash(key) % N, changing node count from $N$ to $N+1$ alters the remainder calculation for nearly all keys. Approximately $N/(N+1)$ of the entire database (~80% when scaling from 4 to 5 nodes) must be rehashed and transferred across the network, saturating storage and causing multi-hour outages. - 02The Scatter-Gather Tail Latency Trap: When a query omits the shard key (e.g.
SELECT * FROM orders WHERE status = "PENDING"), the query coordinator must broadcast requests to ALL 100 shards simultaneously and merge the results. If each shard has a P99 latency of 50ms, the mathematical probability of a 100-shard scatter-gather query taking $\ge 50\text{ms}$ is $1 - (0.99)^{100} = 63.4\%$! The client’s median response time becomes governed by the slowest, most degraded node in the entire cluster.
DIRECT QUERY ROUTING (O(1) Single-Shard Hop):
[Client Query: WHERE user_id = 42]
|
v
[Query Router (Vitess / Proxy)] --(hash(user_id) % N)--> [Shard 2 Only] (Fast, < 2ms)
SCATTER-GATHER FANOUT (Omitting Shard Key):
[Client Query: WHERE status = 'PENDING']
|
v
[Query Router (Coordinator)]
+----(Broadcast)----> [Shard 1] (12ms)
+----(Broadcast)----> [Shard 2] (15ms)
+----(Broadcast)----> [Shard 3] (480ms - GC stall / lock wait!)
|
v
* Client latency = 480ms (Bound to the slowest tail node in the cluster!)4. Production Invariants: Co-Location, Sagas & Resharding
- 011. Table Co-Location by Entity: Store related tables (
users,orders,order_items) on the SAME physical shard using a shareduser_idrouting key. This allows 99% of customer transactions and relational joins to execute locally on a single machine with full ACID integrity. - 022. Cross-Shard Transactions (Saga > 2PC): When mutations span multiple shards (e.g., deducting inventory on Shard 1 and charging balance on Shard 2), avoid Two-Phase Commit (2PC) because coordinator crashes cause shards to hold row locks indefinitely. Instead, use an asynchronous Saga pattern with local ACID transactions and compensating actions.
- 033. The Celebrity Shard Pattern: Route normal users by
user_id. For designated celebrity accounts (e.g. 50M followers), route their posts bypost_idacross all shards and use Fan-out on Read (merging dynamically at query time) to avoid single-shard write bottlenecks. - 044. Zero-Downtime Resharding Pipeline: 1) Enable dual-writing at the routing proxy. 2) Backfill historical records via Change Data Capture (CDC) replication. 3) Run shadow validation checks to verify parity. 4) Atomically switch read routing to the new shard topology.
Use it when
Use composite shard keys (tenant_id:entity_id) for multi-tenant B2B SaaS platforms to keep most tenant-scoped access local and reduce cross-shard joins.
Reconsider when
Avoid sharding prematurely: vertical scaling on a single read-replica cluster or table-level partitioning (PostgreSQL declarative partitioning) easily handles up to 5TB and 15,000 QPS with vastly lower operational complexity.
5. Shard Key Selection Cheatsheet & War Stories
| Candidate Shard Key | Distribution Uniformity | Data Co-Location | Query Performance | Primary Failure Mode |
|---|---|---|---|---|
User ID (user_id) | High (millions of users spread evenly) | High (all user orders on 1 shard) | O(1) direct single-shard lookup | Cross-user queries require scatter-gather |
Timestamp (created_at) | Catastrophic (100% writes hit latest shard) | High for time-window scans | Fast historical analytics | Active time shard crashes under write saturation |
Country (country_code) | Abysmal (US/EU have 100x load of others) | High for compliance (GDPR) | Low in-region latency | Severe load skew on major regional shards |
Composite (tenant_id:id) | Exceptional for B2B SaaS | 100% co-located per customer | Zero cross-shard joins for tenant | Mega-enterprise tenant outgrows single physical box |
Instagram & Pinterest Sharding Architectures
6. Active Recall Checkpoint
Active Recall Checkpoint
Why is sharding by an auto-incrementing timestamp (created_at) considered a disastrous anti-pattern for write-heavy systems?
Hint: Where do all current writes land if the key is the current time?
Show answer & explanation
Because current time moves forward monotonically, 100% of all incoming write requests in the current minute will hash to the exact same newest partition range. All other historical shards sit completely idle at 0% write CPU, while the active time shard crashes under write saturation. Sharding by timestamp completely destroys horizontal write distribution.
Active Recall Checkpoint
Why does Two-Phase Commit (2PC) degrade write availability in distributed sharded databases compared to the Saga pattern?
Hint: What happens when the coordinator fails after participants vote?
Show answer & explanation
2PC is a blocking protocol. During Phase 1, participants acquire exclusive row locks. If the coordinator crashes or is partitioned before sending Phase 2 COMMIT/ROLLBACK, participant shards must hold their locks indefinitely to preserve consistency. This blocks all subsequent reads and writes on those rows, causing cluster-wide throughput collapse. Sagas avoid this by using non-blocking local ACID transactions with asynchronous compensating rollbacks.
Topic sizing snapshot
The four numbers that materially affect this architecture. Use them as bounds, not as a generic calculator embedded in every lesson.
Peak QPS
45,000 Writes/sec across 8 shards
5-Yr Storage
18 TB replicated across 3 AZs
Bandwidth
8 Gbps intra-cluster replication
Working Set RAM
128 GB buffer pool per shard
Architectural Trade-Off Analysis
Compare latency, throughput, consistency, and operational complexity across core industry alternatives.
Architecture Decision Matrix
Multi-axis engineering evaluation and FAANG interview rules of thumb.
SQL (Postgres / MySQL)
Relational ACID Store
Structured schema, relational joins, ACID transactions, and strict foreign keys.
NoSQL (Cassandra / DynamoDB)
Distributed Non-Relational Store
Horizontal partition keys, denormalized documents/wide-columns, and tunable consistency.
| Evaluation Axis | SQL (Postgres / MySQL) | NoSQL (Cassandra / DynamoDB) | Details |
|---|---|---|---|
Latency | Moderate | Strong | |
Throughput | Moderate | Strong | |
Scalability | Moderate | Strong | |
Consistency | Strong | Moderate | |
Complexity | Strong | Moderate | |
Cost | Moderate | Strong |
When to Choose in an Architecture Interview
Choose SQL when ACID guarantees are non-negotiable (financial ledgers, payment processing, inventory checkout) or when query access patterns are unpredictable and require ad-hoc analytical joins.
Choose NoSQL when write volume exceeds single-node capacity (>20K writes/sec), data is unstructured/hierarchical (logs, telemetry, user feeds), or multi-region active-active replication is mandatory.
Never say "NoSQL is faster than SQL" without qualification. SQL with proper B-Tree indexes on indexed primary keys is lightning fast. NoSQL wins on horizontal write scaling, not inherent single-row read speed.
Production Postmortem & Verification
Production Incident Postmortem
- Trigger / Setup: A company adds a 4th database node to a modulo-sharded cluster (`id % 3` becomes `id % 4`).
- Production Symptom: 75% of existing data must be migrated across the network, taking the cluster offline for 18 hours.
- Root Cause & Fix: Consistent Hashing ensures that adding a node only migrates 1/(N+1) fraction of keys, keeping the cluster available.
Acceptance Criteria & Outcomes
- Demonstrate replication lag anomalies and engineer read-after-write consistency solutions (routing dirty reads to leader).
- Implement a consistent hashing ring with virtual nodes and prove balanced key distribution.
- Analyze cross-shard query performance penalties and avoid distributed multi-shard transactions.
End-of-Chapter Synthesis & Key Takeaway
Database Scaling: Sharding, Partitioning & Replication is built around one fundamental rule: A shard key is a routing address. The router applies one deterministic rule so each record belongs to exactly one horizontal partition.. Before adding components, establish explicit quantitative SLAs for latency, throughput, and consistency. Does the request contain a shard key that maps evenly and deterministically?
Architectural & Technical Interview Review
Core FAANG Interview Questions
Q01How do you justify introducing Database Scaling: Sharding, Partitioning & Replication into a high-scale production architecture?Click to reveal model answer →Hide answer ↑Requirements & Design Brief
Introduce Database Scaling: Sharding, Partitioning & Replication only when measured scale, data size, or failure boundaries exceed single-node capacity. State the exact bottleneck, evaluate operational overhead, and verify that the trade-offs justify the added moving parts.
Q02What is the primary trade-off and hidden operational cost of Database Scaling: Sharding, Partitioning & Replication?Click to reveal model answer →Hide answer ↑Architecture Trade-offs
It provides Storage and write throughput scale horizontally, but costs Cross-shard joins, transactions, and rebalancing become harder. Always name what the design spends immediately after what it buys.
Q03How do you handle catastrophic failure or dependency degradation in Database Scaling: Sharding, Partitioning & Replication?Click to reveal model answer →Hide answer ↑Failure Review & Recovery
Guard against One popular key creates a hot partition.. Mitigate through bounded queues, circuit breakers with graceful fallback, and load shedding under extreme traffic.
Production Pitfalls & Anti-Patterns
Critical Failure Anti-Patterns
One popular key creates a hot partition.
Scattering distributed components before identifying concrete write, read, or storage limits creates accidental points of failure and operational debt.
Production Mitigation: Start with the simplest modular design that satisfies requirements, evolving it only as measured constraints dictate.
A query without the shard key fans out to every shard.
When a dependency degrades, immediate synchronized retries multiply downstream traffic, turning a minor slowdown into a total fleet outage.
Production Mitigation: Enforce strict retry budgets, exponential backoff, and full randomized jitter on all client calls.
Neglecting Observability and Metrics
Deploying architecture without distributed tracing or p99 tail latency alerts leaves engineers blind when partial partitions occur.
Production Mitigation: Export metrics for request rate, error rate, p95/p99 duration, and saturation at every service boundary.