Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • About
  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

👥10,068visitors

Built for engineers who want to go deep.


← System Design Fundamentals

Scalability Fundamentals

  • Horizontal vs Vertical Scaling
  • Load Balancing
  • Caching Strategies

Databases at Scale

  • CAP Theorem
  • Database Sharding
  • Replication & Consistency
  • Consistent Hashing
Chaturmind
← System Design Fundamentals

Scalability Fundamentals

  • Horizontal vs Vertical Scaling
  • Load Balancing
  • Caching Strategies

Databases at Scale

  • CAP Theorem
  • Database Sharding
  • Replication & Consistency
  • Consistent Hashing
HomeLearnSystem DesignSystem Design FundamentalsDatabases at Scale
✓ FreeIntermediate· 6 min read

Database Sharding

Horizontal partitioning — range vs hash sharding, hot spots, and cross-shard queries.

Published September 21, 2026


Database Sharding

Sharding (horizontal partitioning) splits one logical dataset across several independent database servers, called shards. Each shard holds a subset of the rows, for example the users whose IDs hash to it. Together, the shards hold everything.

It's how systems grow beyond what one machine can handle: more data than one server can store or keep in memory, or more writes per second than one leader can absorb. Read replicas can't solve that, because every replica still has to apply every write.

Sharding is powerful, but it's also one of the most expensive architectural decisions to make, and to undo. Consider it after cheaper options are exhausted:

  1. Optimize queries and indexes.
  2. Scale the database server up.
  3. Add caching, and read replicas for read-heavy load.
  4. Archive or move cold data.
  5. Split by function: separate databases for separate services.
  6. Then shard.

Advertisement

Choosing the shard key

Every sharding design is really a shard key decision. The key determines which shard stores each row, and therefore:

  • Load distribution: does data and traffic spread evenly?
  • Query routing: can common queries be answered by one shard?
  • Transactions: can data that must change atomically live together?

A good key has high cardinality, even access frequency, and matches the dominant query pattern. For a SaaS product, tenant_id keeps each customer's data on one shard, so almost every query and transaction is single-shard. For a social app, user_id keeps a user's posts together.

Partitioning strategies

Hash partitioning

shard = hash(key) mod N, or more flexibly, hash into many fixed buckets (virtual partitions) that are then assigned to shards.

  • ✅ Spreads keys evenly, even when the keys themselves are sequential.
  • ❌ Range queries on the key (user_id BETWEEN …) must hit every shard.
  • ❌ With plain mod N, changing N remaps almost every key. Changing from 4 to 5 shards moves about 80% of the data.

The fix is to decouple keys from physical servers:

  • Fixed virtual partitions: create, say, 1,024 partitions up front, and assign several to each server. Adding a server moves whole partitions, and keys never change partition. Cassandra, DynamoDB, Elasticsearch and Kafka all use variants of this.
  • Consistent hashing: servers and keys are placed on a hash ring, and adding a server takes over only a slice of neighbouring keys (about 1/N of the data). See Consistent Hashing.

Range partitioning

Contiguous key ranges go to each shard: A–F, G–M, or date ranges.

  • ✅ Efficient range scans and ordered reads within a shard.
  • ❌ Hot spots: with monotonically increasing keys (timestamps, auto-increment IDs), every new write goes to the last shard.
  • Systems like HBase, Bigtable and CockroachDB split ranges automatically as they grow.

Directory (lookup) partitioning

A mapping service records which shard holds each key or tenant.

  • ✅ Maximum flexibility: move one large tenant to its own shard without rehashing anyone else.
  • ❌ The directory must be highly available and fast (cache it aggressively), and it's one more component to operate.

Hot spots and skew

Even distribution by key count isn't the same as even load:

  • Celebrity keys: one user or product receiving a huge share of the traffic.
  • Large tenants: one customer with 1,000× the data of the average.
  • Time-based keys: "today" is always the hottest partition.

Mitigations:

  • Put hot entities on dedicated shards, via a directory mapping.
  • Cache hot read-heavy data in front of the shard.
  • Split a hot key with a suffix (post_123#0 … post_123#9) to spread its writes. Reads must then gather and merge all the sub-keys.
  • Compound keys such as (sensor_id, day) spread time-series writes.

Cross-shard operations

What was simple on one database becomes hard:

  • Queries without the shard key (WHERE email = ? when sharded by user_id) must scatter-gather across all shards: send the query to every shard in parallel and merge the results. Latency is set by the slowest shard, and the load multiplies.
    • Fix: a global secondary index, a separate table mapping email → user_id, itself sharded by email.
  • Joins across shards are generally avoided. Denormalize, co-locate related tables with the same shard key (orders sharded by user_id alongside users), or join in the application.
  • Transactions across shards need two-phase commit (slow, and blocking on coordinator failure) or sagas with compensating actions. Design so that most transactions touch a single shard.
  • Globally unique IDs: per-shard auto-increment collides. Use UUIDs, Snowflake-style IDs, or a central ID service that hands out ranges.
  • Aggregations and reporting are usually offloaded to an analytics store fed by change data capture.

Resharding

Eventually shards fill up, and data must move while the system stays online. The usual approach:

  1. Copy the moving partitions to their new servers (a snapshot plus streaming changes).
  2. Briefly pause, or dual-write, until the copy catches up.
  3. Switch routing to the new location.
  4. Clean up the old copy.

Systems with virtual partitions and automatic balancing (MongoDB's balancer, Cassandra, DynamoDB, Vitess, Citus, CockroachDB) do most of this for you. That's a strong reason to prefer them over hand-rolled application-level sharding.

Sharding in practice

  • MongoDB: built-in sharded clusters with range or hashed shard keys, and a balancer that migrates chunks.
  • PostgreSQL: Citus distributes tables by a distribution column, and co-locates related tables.
  • MySQL: Vitess (originally built for YouTube) handles routing and resharding.
  • Cassandra / DynamoDB: the partition key is the sharding scheme.

Follow-up questions this topic invites — and their answers

Q: How would you shard a multi-tenant SaaS database? A: Shard by tenant_id, so each tenant's data and transactions stay on one shard, and use a directory so that very large tenants can be moved to dedicated shards. Cross-tenant analytics go to a separate warehouse.

Q: Why is hash(key) % N a poor choice, and what replaces it? A: Changing N remaps nearly every key, forcing a massive data migration. Use many fixed virtual partitions assigned to servers, or consistent hashing, so adding a server moves only a small fraction of the data.

Q: How do you look up a user by email when sharding by user ID? A: Maintain a global secondary index (a lookup table from email to user ID, sharded by email). Query it first, then go to the right user shard. The alternative, scatter-gather across all shards, doesn't scale for frequent queries.

Q: What's a hot partition, and how do you fix it? A: One shard receiving disproportionate traffic, because of a popular key or a sequential key pattern. Fixes include caching, isolating hot keys on dedicated shards, adding random suffixes to split writes, and choosing keys that don't concentrate new writes in one place.

Q: When should you not shard? A: When the data fits on one well-provisioned server and the write rate is manageable. Sharding adds permanent complexity to queries, transactions, operations and schema changes, so use every simpler option first.

Advertisement

Previous

CAP Theorem

Next

Replication & Consistency

AI Tutor

Lesson: Database Sharding

Quick actions

AI responses can be inaccurate. Verify critical information.