Sharding is one of the most important concepts in system design interviews. When your interviewer asks "How do you handle billions of rows?" or "What happens when data exceeds a single server's capacity?", sharding is the answer.
Yet many candidates struggle with the details: How do you choose a shard key? What happens when you need to add more shards? How do you handle queries that span multiple shards? These are the questions that separate strong candidates from average ones.
This article provides a deep understanding of sharding for system design interviews. We will explore why sharding is necessary, different sharding strategies, consistent hashing, shard key selection, rebalancing, cross-shard operations, and how major databases implement sharding.
Here is what we will cover:
If you're enjoying this newsletter and want to get even more value, consider becoming a [paid subscriber](https://blog.algomaster.io/subscribe).
As a paid subscriber, you'll unlock all premium articles and gain full access to all [premium courses](https://algomaster.io/newsletter/paid/resources) on [algomaster.io](https://algomaster.io).
Before diving into implementation details, let us understand why sharding is fundamental to scaling databases.
Every server has limits: CPU, memory, disk space, and I/O bandwidth. When your data grows beyond these limits, you have two options.
Vertical scaling hits a ceiling. The most powerful server money can buy still has limits. Horizontal scaling through sharding is the path to virtually unlimited capacity.
Sharding is horizontal partitioning of data across multiple database instances. Each shard holds a subset of the total data.
Sharding is not free. It adds significant complexity. Only shard when you must.
Interview insight: "We shard when a single database cannot handle the load, typically when data exceeds a few hundred gigabytes or query throughput exceeds tens of thousands per second. Before sharding, we exhaust other options: read replicas, caching, query optimization, and vertical scaling."
Understanding the difference between horizontal and vertical partitioning is essential.
Split tables by columns. Different columns go to different databases.
Use cases:
Split tables by rows. Different rows go to different databases.
Use cases:
How do you decide which shard holds which data? There are several strategies.
Assign ranges of the shard key to each shard.
How it works:
Advantages:
Disadvantages:
Apply a hash function to the shard key and use modulo to determine shard.
How it works:
Advantages:
Disadvantages:
Maintain a lookup service that maps keys to shards.
How it works:
Advantages:
Disadvantages:
Shard based on geographic location.
Use cases:
Interview tip: "For our user table with random access patterns, we use hash-based sharding on user_id for even distribution. For our time-series data with range queries, we use range-based sharding on timestamp. The choice depends on query patterns."
Consistent hashing solves the resharding problem of simple hash-based sharding.
Impact: Adding one shard moves ~80% of keys. This is unacceptable at scale.
Imagine a ring from 0 to 2^32-1. Both keys and shards are placed on this ring using hash functions.
Rules:
When adding a shard, only keys between the new shard and its predecessor move.
Result: Only ~1/N of keys move (where N is the number of shards).
Problem: With few shards, distribution may be uneven.
Solution: Each physical shard has multiple virtual nodes on the ring.
Benefits of virtual nodes:
Interview insight: "We use consistent hashing with 256 virtual nodes per shard. When adding a new shard, we only move about 1/N of the data. The virtual nodes ensure even distribution even with heterogeneous hardware, we just assign more vnodes to more powerful servers."
The shard key is the most critical decision in sharding. A bad choice leads to hotspots, inefficient queries, and painful migrations.
User ID as shard key:
Tenant ID for multi-tenant SaaS:
Problem: Large tenants cause hotspots.
Solution: Compound shard key: tenant_id + user_id
Time-based sharding:
Good for: Time-series data, logs, events Problem: Latest shard is always hot
Combine multiple fields for better distribution and query routing.
Interview tip: "For our e-commerce orders table, we shard by customer_id because 90% of queries are customer-specific (order history, cart). For cross-customer queries like analytics, we use a separate read-optimized replica with different sharding or no sharding at all."
As data grows, you need to add shards. This is one of the hardest operational challenges.
Triggers:
Strategy 1: Fixed Number of Shards (Pre-splitting)
Create more shards than needed initially.
Pros: Simple, no data splitting Cons: Must guess correctly upfront, fixed maximum capacity
Strategy 2: Dynamic Splitting
Split shards when they get too large.
Pros: Automatic, adapts to growth Cons: Complex, splits cause temporary slowdown
Strategy 3: Dynamic Merging
Merge small shards to reduce overhead.
Moving data without downtime is complex.
Phases:
Design to minimize resharding frequency:
Interview insight: "We use consistent hashing with 256 virtual nodes per physical shard. When adding a new shard, we use a background migration process that copies data in batches during off-peak hours. During migration, we dual-write to both old and new locations, then atomically switch the routing once migration is complete."
Some operations inherently span multiple shards. These are challenging.
Example: Find all orders over $1000
Performance implications:
The most expensive cross-shard operation.
Strategies for cross-shard JOINs:
Transactions spanning multiple shards require coordination.
Two-Phase Commit (2PC):
Problems with 2PC:
For long-running transactions, use compensating transactions instead of distributed locks.
Each step has a compensating action:
Maintain indexes that span all shards for cross-shard queries.
Trade-offs:
Interview tip: "We avoid cross-shard transactions by co-locating related data. Orders and order_items are sharded by customer_id, so a complete order transaction stays within one shard. For truly cross-shard operations like transferring money between users, we use the saga pattern with compensating transactions."
Different architectural patterns for implementing sharding.
Application code decides which shard to query.
Pros: Full control, no middleware Cons: Logic in every application, harder to change
A proxy layer handles routing transparently.
Popular proxies:
Pros: Transparent to application, centralized logic Cons: Extra hop, potential bottleneck
Database handles sharding internally.
Databases with native sharding:
Pros: Integrated, automatic rebalancing Cons: Vendor lock-in, less control
Combine multiple patterns.
How major databases implement sharding.
Components:
Shard key selection:
Partition key:
Virtual nodes (vnodes):
VSchema (sharding configuration):
Automatic features:
Q: How would you shard a social media posts database?
Q: Design sharding for a multi-tenant SaaS application.
Q: One shard is significantly hotter than others. How do you debug and fix?
Q: How do you handle a cross-shard transaction failure?
Sharding is essential for scaling beyond the limits of a single database server. Here are the key takeaways:
When discussing sharding in interviews, be specific about your choices. Do not just say "we shard the data." Explain the shard key, the sharding strategy, how you handle cross-shard queries, what happens when you need to add shards, and how you monitor shard health. This depth demonstrates genuine understanding of distributed database design.
Thank you for reading!
If you found it valuable, hit a like and consider subscribing for more such content every week.
If you have any questions or suggestions, leave a comment.
This post is public so feel free to share it.
P.S. If you're enjoying this newsletter and want to get even more value, consider becoming a [paid subscriber](https://blog.algomaster.io/subscribe).
As a paid subscriber, you'll unlock all premium articles and gain full access to all [premium courses](https://algomaster.io/newsletter/paid/resources) on [algomaster.io](https://algomaster.io).
There are [group discounts](https://blog.algomaster.io/subscribe?group=true), [gift options](https://blog.algomaster.io/subscribe?gift=true), and [referral bonuses](https://blog.algomaster.io/leaderboard) available.
Checkout my [Youtube channel](https://www.youtube.com/@ashishps_1/videos) for more in-depth content.
Follow me on [LinkedIn](https://www.linkedin.com/in/ashishps1/) and [X](https://twitter.com/ashishps_1) to stay updated.
Checkout my [GitHub repositories](https://github.com/ashishps1) for free interview preparation resources.
I hope you have a lovely day!
See you soon,
Ashish