As your application grows from a weekend project to serving millions of users across India, your database will inevitably become the bottleneck. A single database server can only hold so much memory, process so many queries per second (QPS), and store so much data on its disk. When you hit a wall, you have two primary ways to scale your data layer horizontally: Replication and Sharding.
In system design interviews (especially for SDE-2 and Senior roles at companies like Swiggy, Flipkart, or Uber), interviewers expect you to know exactly when to use which technique, how they interact, and the painful trade-offs they introduce. This article will break down both concepts, compare their strategies, and arm you with the knowledge to tackle complex database scaling questions.
What It Is and Why It Matters
To understand why we need these techniques, let's look at the limitations of a single database server. If you are running a flash sale, your database might be hit with 100,000 read requests per second (users checking product details) and 10,000 write requests per second (users placing orders). A single machine will quickly exhaust its CPU, memory, or disk I/O.
Replication: Scaling Reads and Ensuring High Availability
Replication is the process of keeping multiple copies of your data across different servers.
- Why it matters: Most applications are read-heavy (typically a 10:1 to 100:1 read-to-write ratio). By creating copies (replicas) of your database, you can distribute the read traffic across multiple machines. Furthermore, if your main database server crashes, a replica can take over, ensuring your system remains highly available.
- The Catch: Replication does not help you scale writes (since every write must eventually be copied to all replicas), nor does it help you scale storage capacity (since every server holds a full copy of the data).
Sharding: Scaling Writes and Storage Capacity
Sharding (also known as horizontal partitioning) is the process of splitting a single large dataset into smaller, more manageable pieces called "shards." Each shard is held on a separate database server.
- Why it matters: If your database grows to 50 Terabytes, it won't fit on a single standard disk. By sharding, you might split this into 10 servers holding 5 TB each. Additionally, because each shard operates independently, you can distribute write traffic across all the shards, effectively multiplying your write throughput.
- The Catch: Sharding introduces immense complexity. Queries that span multiple shards become slow and difficult to execute, and rebalancing data when a shard gets full is a logistical nightmare.
How It Works
In a production system, replication and sharding are almost always used together. You shard your data to handle storage and write volume, and then you replicate each shard to handle read volume and ensure fault tolerance.
Here is a high-level architecture of a sharded and replicated database system:
When an application needs to read or write data, the request hits a Shard Router (this logic can also live inside the application code). The router determines which shard holds the relevant data. If it's a write request, it is routed to the Primary node of that shard. If it's a read request, it can be routed to the Primary or any of its Replicas.
Main Strategies and Variants
Let's break down the different ways to implement replication and sharding.
Replication Strategies
| Strategy | How it works | Best for | Trade-offs |
|---|---|---|---|
| Single-Leader (Primary-Replica) | One node accepts writes; multiple nodes accept reads. Writes are copied to replicas. | Most standard web applications (e.g., MySQL, PostgreSQL default). | If the leader dies, writes fail until a new leader is elected. Replication lag can cause stale reads. |
| Multi-Leader | Multiple nodes accept writes. They sync changes with each other. | Multi-datacenter setups, collaborative apps (e.g., Google Docs). | High complexity in resolving write conflicts (e.g., two users editing the same row simultaneously). |
| Leaderless | Any node can accept reads/writes. Uses quorums (W + R > N) to ensure consistency. | High-availability, write-heavy systems (e.g., Cassandra, DynamoDB). | Eventual consistency is the norm. Requires complex mechanisms like read-repair and anti-entropy. |
Sharding Strategies
| Strategy | How it works | Best for | Trade-offs |
|---|---|---|---|
| Range-based Sharding | Data is divided by contiguous ranges of the shard key (e.g., User IDs 1-10000 in Shard A, 10001-20000 in Shard B). | Queries that scan a range of data (e.g., fetching all events between two dates). | Highly susceptible to "hotspots." If you shard by date, all today's traffic hits a single shard. |
| Hash-based Sharding | A hash function is applied to the shard key, and the result determines the shard (e.g., hash(user_id) % num_shards). | Distributing data evenly across all shards. | Range queries are impossible without querying every single shard (scatter-gather). Resharding is painful. |
| Directory-based Sharding | A lookup service (like a separate database or cache) keeps a mapping of which key belongs to which shard. | Multi-tenant B2B applications where you want to pin specific large clients to dedicated shards. | The lookup service becomes a single point of failure and an extra network hop. |
Code Example: Hash-Based Shard Router
If you are asked to implement a basic hash-based routing mechanism in a coding or low-level design round, here is how you might write it. Note how we use a simple modulo operator, though in production, you would use Consistent Hashing to minimize data movement during resharding.
class ShardRouter:
def __init__(self, num_shards: int):
self.num_shards = num_shards
def get_shard(self, user_id: str) -> int:
# Use a stable hashing algorithm in production (e.g., MD5 or MurmurHash)
# Built-in hash() in Python is randomized per process in newer versions
import hashlib
hash_val = int(hashlib.md5(user_id.encode('utf-8')).hexdigest(), 16)
return hash_val % self.num_shardsTrade-offs and Failure Modes
Scaling databases is an exercise in choosing your pain. Here are the major failure modes you must discuss in an interview.
Replication Lag
In a Single-Leader setup, replication is usually asynchronous. This means the Primary acknowledges the write to the user before the Replicas have copied it.
- The Failure: A user updates their profile picture and immediately refreshes the page. The read request hits a Replica that hasn't received the update yet. The user sees their old picture and thinks the upload failed.
- The Fix: Implement "Read-Your-Own-Writes" consistency. For a short window (e.g., 5 seconds) after a user makes a write, route all their read requests directly to the Primary node.
Split-Brain
If the network between your Primary and Replicas fails, a Replica might assume the Primary is dead and promote itself to Primary. If the original Primary is actually still alive and accepting writes from a subset of users, you now have two Primaries (a "split-brain").
- The Failure: Data diverges. When the network heals, it is nearly impossible to merge the conflicting writes without data loss.
- The Fix: Use consensus algorithms (like Raft or Paxos) and require a strict quorum for leader election. A node can only become a leader if it gets votes from a majority of the nodes.
The Celebrity Problem (Hot Shards)
In hash-based sharding, data is distributed evenly by key. But what if one key is accessed millions of times more than others? Think of Virat Kohli's Instagram account versus a normal user's account.
- The Failure: The shard holding the celebrity's data gets overwhelmed with read/write traffic, bringing down that specific server while the other shards sit idle.
- The Fix: Caching is the first line of defense for read-heavy hot keys. For write-heavy hot keys, you may need to append a random number to the shard key (e.g.,
user_id_1,user_id_2) to force the data to split across multiple shards, though this makes reading the data much harder.
Cross-Shard Joins
Relational databases are loved for their JOIN capabilities. Once you shard, your users table might be on Shard A, but their orders might be on Shard B.
- The Failure: You cannot run a simple SQL
JOINacross two different physical servers efficiently. - The Fix: Denormalize your data (store the user's name directly in the orders table) or perform the join at the application level (fetch the user from Shard A, fetch the orders from Shard B, and combine them in your backend code).
How It Shows Up in Real Systems
- Cassandra: Uses a leaderless replication model combined with consistent hashing for sharding. It is designed for massive write throughput and high availability, making it a favorite for companies like Netflix and Apple.
- MongoDB: Uses "Replica Sets" for single-leader replication and supports both range-based and hash-based sharding out of the box.
- Vitess: A database clustering system used by YouTube and Slack. It sits on top of MySQL and handles sharding and routing transparently. The application talks to Vitess as if it were a single massive MySQL database, and Vitess handles the complex cross-shard routing.
Interview Questions
Here are the most common questions interviewers ask regarding sharding and replication, along with model answers.
1. "How do you choose a shard key for a multi-tenant SaaS application (like Slack or Jira)?"
Model Answer: For a B2B SaaS application, the best shard key is almost always the tenant_id (or workspace_id). This ensures that all data for a specific company lives on the same shard. This is crucial because users within a company frequently query data related to their own company, allowing us to perform local database joins and transactions without cross-shard network calls. If a single tenant becomes too large for one shard, we can use directory-based sharding to allocate them a dedicated cluster.
2. "We are using hash-based sharding with 4 shards. Our data has doubled, and we need to add 4 more shards. How do you handle this?"
Model Answer: If we use a simple modulo (hash(key) % 4), changing the divisor to 8 will remap almost every single key, requiring massive data movement. To avoid this, we should have used Consistent Hashing from the start, which minimizes data movement. If we are stuck with modulo, the safest approach is a double-write migration:
- Spin up the 8 new shards.
- Write new data to both the old and new shards.
- Run a background script to migrate historical data to the new shards.
- Verify data integrity.
- Flip the read path to the new shards.
3. "What happens if a primary node fails in a single-leader replication setup?"
Model Answer: The system must detect the failure, usually via missing heartbeats. Once detected, an automated failover process begins. The remaining replicas hold an election to choose a new primary (typically the one with the most up-to-date replication log). The shard router/load balancer is then updated to point write traffic to the new primary. During this election window (which can take a few seconds), the system will reject write requests, sacrificing availability temporarily for consistency.
4. "How does replication lag impact a system like Twitter?"
Model Answer: In Twitter, if I tweet and immediately reload my timeline, replication lag might cause my timeline read to hit a replica that hasn't processed my tweet yet. I would think my tweet vanished. To fix this, we can implement "read-your-own-writes" consistency by caching the user's recent tweets in Redis, or by routing the user's read requests to the primary node for a few seconds after they post a tweet. For viewing other people's tweets, eventual consistency (and replication lag) is perfectly acceptable.
5. "Why wouldn't you just shard your database from day one to be safe?"
Model Answer: Sharding introduces massive operational overhead. It breaks ACID transactions across shards, makes JOIN operations incredibly slow or impossible, complicates backups, and requires complex application-level routing. Modern single-node databases can handle terabytes of data and thousands of QPS. I would scale vertically (buy a bigger machine) and use read replicas first. Sharding is a last resort when vertical scaling and replication are no longer sufficient.
6. "Explain the difference between Synchronous and Asynchronous replication."
Model Answer: In Synchronous replication, the primary waits for replicas to acknowledge they have saved the data before telling the user "success." This guarantees zero data loss if the primary crashes, but it makes writes very slow and fragile (if a replica is down, the write fails). In Asynchronous replication, the primary saves the data and immediately tells the user "success," syncing to replicas in the background. This is fast and highly available, but if the primary crashes before syncing, data is lost. Most systems use Asynchronous replication, or a hybrid (sync to at least one replica, async to the rest).
Common Mistakes in System Design Interviews
- Sharding too early: As mentioned in the interview questions, throwing sharding at a system with 10,000 users is a red flag. It shows a lack of practical engineering experience. Always exhaust caching, indexing, vertical scaling, and read replicas first.
- Choosing a sequential ID for range sharding: If you shard by an auto-incrementing
user_idor atimestamp, all new writes will go to the very last shard. Your cluster will have 9 idle machines and 1 machine on fire. - Forgetting connection pool limits: When you shard a database, your application servers need to maintain connection pools to every shard. If you have 100 app servers and 50 shards, the number of open connections can easily overwhelm the database's connection limits. This is why intermediate proxies like PgBouncer or Vitess are used in production.
- Ignoring the CAP theorem: When discussing replication, you must acknowledge the trade-off between Consistency and Availability during a network partition. You cannot have both. (Check out our article on the CAP Theorem for a deeper dive).
Mastering sharding and replication is about understanding that there are no perfect solutions, only trade-offs. By knowing the exact failure modes of each strategy, you can demonstrate the maturity and foresight expected of a senior engineer.