Sharding & Partitioning

Splitting data across tables and machines — vertical vs horizontal partitioning, range, hash and directory-based sharding, choosing a shard key, hot spots, rebalancing, and cross-shard queries.

Advanced 5 min readLesson 14 of 14 Interview Q&A

When data or write traffic outgrows a single machine, you split it. Partitioning divides data into pieces; sharding usually means putting those pieces on different servers. Replication copies data; sharding divides it. Large systems do both: each shard is itself replicated.

Kinds of partitioning

KindSplit byExample
VerticalColumns or tablesMove large profile_photo blobs or rarely used columns to another table or store; put different services' tables in different databases
HorizontalRowsUsers A–M on shard 1, N–Z on shard 2
FunctionalFeature / serviceOrders DB, users DB, analytics warehouse

Within one server, table partitioning (PostgreSQL declarative partitioning, MySQL partitions) splits a big table into child tables by range or hash. It's great for time-series data: dropping last year's partition is instant compared with deleting billions of rows.

Sharding strategies

Range-based

Assign contiguous key ranges to shards: user IDs 1–1M → shard 1, 1M–2M → shard 2; or by date.

  • ✓ Range queries on the key are efficient (they hit one or few shards).
  • ✗ Hot spots: sequential keys (timestamps, auto-increment IDs) send all new writes to the last shard.

Hash-based

Shard = hash(key) mod N.

keyhashsharduser_17hash → 0x9c…shard 0user_42hash → 0x3a…shard 2user_99hash → 0x71…shard 1
  • ✓ Spreads keys and load evenly.
  • ✗ Range queries must hit every shard.
  • ✗ With plain mod N, changing N remaps almost every key. Consistent hashing fixes this: adding a node moves only about 1/N of the keys (Consistent hashing).

Directory-based

A lookup service maps each key (or key range, or tenant) to a shard.

  • ✓ Total flexibility: move a big tenant to its own shard.
  • ✗ The directory is an extra hop, and must be highly available and consistent.

Choosing a shard key

The most important decision, and expensive to change later. A good shard key:

  1. Has high cardinality — many distinct values to spread across shards.
  2. Spreads load evenly — not just data, but reads and writes.
  3. Matches the main access pattern, so most queries hit a single shard.
  4. Keeps data that's used together on the same shard, so transactions and joins stay local.
AppGood shard keyWhy
Multi-tenant SaaStenant_idAlmost every query is within one tenant
Social networkuser_idProfile, posts and settings live together
Chatconversation_idMessages are read per conversation
Orderscustomer_id"My orders" pages hit one shard
Bad: created_at—All current writes hit one shard
Bad: country—Low cardinality and very uneven

Cross-shard operations

Sharding takes away things a single database gives you for free:

NeedWhat it costs once sharded
Query without the shard keyScatter-gather to all shards, then merge — latency is set by the slowest shard
Joins across shardsDone in the application, or by denormalising data onto each shard
Transactions across shardsTwo-phase commit or sagas (Distributed transactions)
Unique constraints (e.g. email)Need a global index or a separate lookup table
Auto-increment IDsUse globally unique IDs: UUIDv7, Snowflake-style IDs (timestamp + machine + sequence)

Rebalancing

Shards grow unevenly, and you add machines. Approaches:

  • Fixed number of partitions — create many more partitions than nodes (e.g. 1024 logical partitions on 8 nodes) and move whole partitions when nodes are added. Used by Elasticsearch, Couchbase, Riak and Kafka.
  • Dynamic splitting — split a range when it grows too big and merge small ones (HBase, MongoDB, CockroachDB, Spanner, TiDB).
  • Consistent hashing with virtual nodes (Cassandra, DynamoDB).

Moving data must happen online, without downtime, while the shard keeps serving: copy, catch up from the change log, then switch routing.

Who routes requests?

AppRouter / proxyknows key → shard mapShard 1Shard 2Shard 3

Routing can live in the client library (Cassandra drivers), a proxy (Vitess for MySQL, Citus coordinator for PostgreSQL, mongos for MongoDB), or any node that forwards requests. Distributed SQL databases (CockroachDB, Spanner, TiDB, YugabyteDB) shard automatically and hide most of this — at the price of distributed transaction latency.

Key takeaways
  • Partitioning splits data; sharding puts the pieces on different machines; each shard is usually replicated.
  • Range sharding supports range queries but creates hot spots; hash sharding balances load but scatters ranges.
  • Choose a high-cardinality shard key that matches the main access pattern and keeps related data together.
  • Cross-shard queries, joins, transactions and unique constraints become expensive.
  • Rebalance with many fixed partitions, dynamic splitting or consistent hashing — and shard only when you must.
Interview questions
QHow would you shard a multi-tenant SaaS database?medium

Shard by tenant_id so each tenant's data and queries stay on one shard, with a directory mapping tenants to shards. That allows moving large tenants to dedicated shards and rebalancing. Global data (plans, feature flags) lives in a small separate database, replicated or cached everywhere.