CodeWithYash
DSA
Spring Boot
System Design
Series
Articles
Leaderboard
Sign In

Subscribe to Newsletter

Get the latest articles, DSA sheets, and system design challenges delivered to your inbox.

<CODEWITHYASH/>

The ultimate sanctuary for software engineers seeking deep mastery of core technical principles.

Library

  • Articles
  • DSA Sheets
  • Roadmaps

Connect

  • GitHub
  • LinkedIn
  • About
  • Contact

Legal

  • Privacy
  • Terms
  • Support

© 2026 CodeWithYash Global Systems.

Status: OperationalVersion: 4.2.0
System Design
OverviewTheory lessonsHLDLLD
All SeriesSeries
Distributed Systems

System Design Series

0%

0 of 33 topics completed

Progress
Load Balancers & Reverse ProxiesTheory
25 min
API Gateways & Edge RoutingTheory
35 min
Caching Architecture & Critical PathologiesTheory
30 min
Consistent Hashing & Virtual NodesTheory
25 min
Content Delivery Networks (CDNs) & Anycast RoutingTheory
35 min
Storage Engines: B-Trees vs. LSM-TreesTheory
30 min
SQL vs. NoSQL & Data Model SelectionTheory
35 min
Database Scaling: Sharding, Partitioning & ReplicationTheory
30 min
Message Brokers, Event Streaming & Task QueuesTheory
30 min
Rate Limiters & Traffic ShapingTheory
25 min
System DesignCore Infrastructure Building BlocksDatabase Scaling: Sharding, Partitioning & Replication

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.)

Written & reviewed by Yash Patel 30 minBaseline 2026.1 Curated Blueprint· Verified 2026-09-14

Lesson 15 of 33

1d streak

The 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

Shard AA–H

Partition load

34%

Shard BI–P

Partition load

33%

Shard CQ–Z

Partition load

33%

A stable routing rule identifies one owner; it does not guarantee balanced traffic when one key is disproportionately popular.

Receive keyed querykey = M

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 / 4
Step 1 of 4

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

Sharding completely shatters relational abstractions: distributed cross-shard joins become prohibitively slow, ACID transactions require heavy Two-Phase Commit (2PC) or Sagas, and selecting the wrong Shard Key creates permanent hot-spot partitions that collapse individual nodes while the rest of the cluster sits idle.

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.

StrategyWrite DistributionRange Query EfficiencyResharding ComplexityHotspot Risk
Range-BasedSkewed (creates hot intervals)Exceptional (local to 1 shard)Easy (split boundary ranges)High (sequential writes hit newest shard)
Modulo Hash (key % N)UniformAbysmal (scatter-gather all N shards)Catastrophic (adding 1 node relocates ~N/(N+1) keys)Low (except on celebrity keys)
Consistent HashingUniform with Virtual NodesAbysmal (scatter-gather required)Minimal (only K/N keys relocated on node add)Low
Directory-Based LookupCustomizable per tenantModerate (lookup routes queries)Simple (update pointer in directory)Low (can move hot tenant to dedicated shard)

3. Modulo Collapse & Scatter-Gather Tail Amplification

  1. 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.
  2. 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.
snippet.texttext
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

  1. 011. Table Co-Location by Entity: Store related tables (users, orders, order_items) on the SAME physical shard using a shared user_id routing key. This allows 99% of customer transactions and relational joins to execute locally on a single machine with full ACID integrity.
  2. 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.
  3. 033. The Celebrity Shard Pattern: Route normal users by user_id. For designated celebrity accounts (e.g. 50M followers), route their posts by post_id across all shards and use Fan-out on Read (merging dynamically at query time) to avoid single-shard write bottlenecks.
  4. 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 KeyDistribution UniformityData Co-LocationQuery PerformancePrimary Failure Mode
User ID (user_id)High (millions of users spread evenly)High (all user orders on 1 shard)O(1) direct single-shard lookupCross-user queries require scatter-gather
Timestamp (created_at)Catastrophic (100% writes hit latest shard)High for time-window scansFast historical analyticsActive time shard crashes under write saturation
Country (country_code)Abysmal (US/EU have 100x load of others)High for compliance (GDPR)Low in-region latencySevere load skew on major regional shards
Composite (tenant_id:id)Exceptional for B2B SaaS100% co-located per customerZero cross-shard joins for tenantMega-enterprise tenant outgrows single physical box

Instagram & Pinterest Sharding Architectures

Instagram solved shard routing without an external directory by designing a 64-bit ID generator: 41 bits for millisecond timestamp, 13 bits for logical shard ID (8,192 logical shards), and 10 bits for auto-incrementing sequence. Every primary key inherently tells the router where it lives. Pinterest redesigned MySQL around 4,096 immutable Virtual Shards mapped to physical instances: adding a physical machine simply required moving a pre-defined range of virtual shards via MySQL replication with zero downtime.

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.

Hardware Bounds & Sizing Math

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

Engineering Decision Matrix

Architectural Trade-Off Analysis

Compare latency, throughput, consistency, and operational complexity across core industry alternatives.

Architectural Trade-Off Matrix

Architecture Decision Matrix

Multi-axis engineering evaluation and FAANG interview rules of thumb.

Option A

SQL (Postgres / MySQL)

Relational ACID Store

Structured schema, relational joins, ACID transactions, and strict foreign keys.

Option B

NoSQL (Cassandra / DynamoDB)

Distributed Non-Relational Store

Horizontal partition keys, denormalized documents/wide-columns, and tunable consistency.

Evaluation AxisSQL (Postgres / MySQL)NoSQL (Cassandra / DynamoDB)Details
Latency
Moderate Strong
Throughput
Moderate Strong
Scalability
Moderate Strong
Consistency
Strong Moderate
Complexity
Strong Moderate
Cost
Moderate Strong
FAANG Interview Rule of Thumb

When to Choose in an Architecture Interview

Pick SQL (Postgres / MySQL) If:

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.

Pick NoSQL (Cassandra / DynamoDB) If:

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.

Examiner Trap to Avoid:

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

  1. Trigger / Setup: A company adds a 4th database node to a modulo-sharded cluster (`id % 3` becomes `id % 4`).
  2. Production Symptom: 75% of existing data must be migrated across the network, taking the cluster offline for 18 hours.
  3. 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

3 Questions
Q01
How 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.

Source section: Requirements & Design Brief
Q02
What 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.

Source section: Architecture Trade-offs
Q03
How 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.

Source section: Failure Review & Recovery

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.

Primary Documentation & Specifications

Consistent Hashing and Random Trees (Karger et al.)
Previous LessonSQL vs. NoSQL & Data Model SelectionCore InfrastructureNext LessonMessage Brokers, Event Streaming & Task QueuesCore Infrastructure

In this chapter

01Architectural Question02Interactive Model031. What is it & Why it Matters042. Sharding Strategies: Range vs. Hash vs. Directory053. Modulo Collapse & Scatter-Gather Tail Amplification064. Production Invariants: Co-Location, Sagas & Resharding075. Shard Key Selection Cheatsheet & War Stories086. Active Recall Checkpoint09Sizing Snapshot10Trade-Off Analysis11Production Verification12Synthesis & Review13Primary References

Chapter promise

Replication topologies: Single-Leader, Multi-Leader, and Leaderless (Dynamo quorum: R + W > N)