Database Sharding: How to Choose a Key and Know When You Need It
In this article
Database sharding is the practice of splitting a large database into smaller, faster, more manageable parts called shards, and you need it when a single database server can no longer handle your workload or data size. Choosing the right shard key—the column or field used to distribute rows—is the single most important decision in sharding, because it determines whether your system scales smoothly or becomes a maintenance nightmare. This article explains how sharding works, how to pick a good shard key, and how to recognize the signs that you actually need it.
What Is Sharding and Why Does It Exist?
Sharding is a horizontal partitioning strategy: you take one logical database and split its rows across multiple physical databases (shards), each with the same schema but a different subset of data. The goal is to distribute both storage and query load so that no single server becomes a bottleneck. It differs from vertical partitioning, which splits by column, and from replication, which copies the entire dataset to multiple servers. Sharding is typically used in large-scale web applications, SaaS platforms, and any system where data volume or query throughput exceeds what one machine can handle.
The concept is not new—it has been used in large distributed systems for decades—but it has become mainstream with the rise of cloud databases and microservices. Sharding is often implemented at the application layer (the app decides which shard to query), or via middleware, or natively by some databases like MongoDB and Citus (a PostgreSQL extension).
How Sharding Works: The Mechanics
At its core, sharding involves three components: the shard key, a sharding function, and a routing mechanism.
- Shard key: a column (or set of columns) that identifies which shard a row belongs to.
- Sharding function: a rule that maps the shard key to a specific shard. Common functions include range-based (e.g., user IDs 1-1000 on shard A, 1001-2000 on shard B), hash-based (e.g., hash(user_id) % number_of_shards), and directory-based (a lookup table maps keys to shards).
- Routing: when an application reads or writes a record, it computes the shard from the key and sends the query to the appropriate shard.
For example, in a multi-tenant SaaS app, you might shard by tenant_id using a hash. Each tenant’s data lives entirely on one shard, so queries for a single tenant only hit one server. In a social media app, you might shard by user_id so that each user’s posts and profile are colocated.
How to Choose a Shard Key
Choosing a shard key is a trade-off between even distribution, query efficiency, and operational simplicity. There is no universal best key; the right choice depends on your data access patterns.
Key Requirements
- High cardinality: the key should have many distinct values so that data spreads evenly. A boolean column (true/false) would put half the data on each shard, which is fine for two shards but useless for 100.
- Even distribution: each shard should hold roughly the same amount of data and receive roughly the same query load. A key with a few very popular values (like a country column where 80% of users are in the US) creates “hot spots.”
- Query locality: queries should ideally be scoped to a single shard. If most of your queries filter by
user_id, shard onuser_id. If they filter bytenant_id, shard on that. - Immutability: the key should never change. If a user changes their email and you shard on email, you must move the entire row to a new shard—a costly operation.
Common Shard Key Strategies
- Hash of a primary key: e.g.,
hash(user_id). This gives excellent distribution but makes range queries across shards expensive. - Range-based: e.g., date ranges (orders from 2020 on shard A, 2021 on shard B). Simple and supports range scans, but can create hot spots if activity is seasonal.
- Composite keys: e.g.,
(tenant_id, user_id). Useful when you need to colocate related data but also spread across many tenants. - Directory-based: a lookup table maps keys to shards. Flexible but adds a lookup hop and can become a bottleneck.
Real-World Example
Consider an e-commerce platform with orders. If you shard by customer_id, all of a customer’s orders are on one shard, so queries like “show my order history” are fast. But queries like “show all orders from the last hour” require scanning every shard. If you shard by order_date, the reverse is true. The best choice depends on which query is more frequent.
Signs You Actually Need Sharding
Sharding adds complexity: you must handle cross-shard joins, distributed transactions, and resharding. It should be a last resort after other scaling options have been exhausted. Here are concrete signs that you might need it:
- Storage limit: your database is approaching the maximum size of a single server (e.g., a few terabytes for many setups).
- Write throughput bottleneck: the primary server’s CPU or disk I/O is consistently near 100% during peak hours, and you cannot scale up further.
- Read replica limitations: you already use read replicas, but they cannot keep up with read-heavy workloads, or replication lag causes stale data.
- Backup/restore time: full backups take longer than your recovery time objective (RTO).
- Connection limits: the database hits its maximum number of concurrent connections.
Before sharding, consider simpler alternatives: optimize queries, add indexes, increase server resources (vertical scaling), use caching (Redis, Memcached), or move to a managed database that scales automatically. Sharding is a significant architectural change that affects every part of your application.
Common Problems and Pitfalls
Even with a good shard key, sharding introduces challenges that you must plan for:
- Cross-shard joins: joining data from two shards requires fetching from both and merging in the application, which is slow and complex. Design your schema to avoid them by denormalizing or colocating related data.
- Distributed transactions: ACID transactions that span shards are hard. Use eventual consistency or design operations to be single-shard.
- Resharding: when you add shards, you must redistribute data. This is a major operation that can cause downtime. Plan for it from the start.
- Hot spots: a poorly chosen key can cause one shard to receive a disproportionate load. Monitor shard metrics and be ready to rebalance.
- Backup and recovery: you now have multiple databases to back up, and restoring a single shard requires careful coordination.
Sharding vs. Alternatives
Sharding is not the only way to scale. Here’s how it compares to other strategies:
- Vertical scaling (scale-up): buy a bigger server. Simple but has hard limits and can be expensive.
- Replication (read replicas): copy data to multiple servers for read scalability. Does not help with write throughput or storage capacity.
- Partitioning (within a database): split a table into smaller physical segments on the same server. Helps with manageability but not with server load.
- Sharding: distributes data across independent servers, allowing both storage and compute to scale horizontally. The cost is complexity.
Many systems combine these: shard the database and also use read replicas per shard for high availability and read scaling.
Costs and Operational Considerations
Sharding has real costs beyond hardware:
- Engineering time: building sharding logic, updating queries, and handling edge cases.
- Infrastructure: more servers, more monitoring, more backup storage.
- Data migration: moving existing data into shards requires careful planning and downtime or a migration tool.
- Team expertise: your team must understand distributed systems concepts.
If you are considering sharding, first estimate the total cost of ownership. For many small-to-medium applications, a well-optimized single database with caching is sufficient and far simpler.
Frequently Asked Questions
Can I change my shard key later?
Yes, but it is extremely difficult. Changing a shard key requires redistributing all data, which can take days and cause downtime. That’s why choosing the right key upfront is critical. Some databases support online resharding, but it’s still a complex operation.
What happens if my shard key causes hot spots?
Hot spots occur when some shards receive more traffic or data than others. You can mitigate by choosing a key with high cardinality and even distribution, or by using a hash function. If hot spots appear, you may need to rebalance by moving data or adding more shards, which is disruptive.
Does sharding work with SQL databases?
Yes, but it requires more work. Traditional SQL databases like MySQL and PostgreSQL were not designed for sharding, so you need middleware (e.g., Vitess, ProxySQL) or an extension like Citus. NoSQL databases like MongoDB and Cassandra have built-in sharding support, making them easier to scale horizontally.
How do I handle cross-shard queries?
You can either accept the performance hit and merge results in the application, or redesign your schema to avoid them. For example, if you need to join orders and customers, shard both by the same key (customer_id) so that related data is on the same shard. If that’s impossible, consider denormalizing or using a separate analytics store.
Is sharding the same as partitioning?
No. Partitioning splits a table into smaller segments, usually on the same server, to improve manageability and query performance. Sharding distributes the data across multiple independent servers. Partitioning is a logical split; sharding is a physical distribution.
When should I avoid sharding?
Avoid sharding if your dataset fits on a single server, if your queries are mostly global (e.g., aggregate reports), or if your team lacks experience with distributed systems. Start with indexing, caching, and vertical scaling. Only shard when you have a clear, measurable need.