Difficulty: Advanced
What is database sharding? How do you choose a shard key, and what problems does sharding introduce?
Sharding is splitting one large logical dataset across multiple independent database servers, called shards, where each shard holds a subset of the rows and handles reads and writes for that subset. A shard key (such as user_id or merchant_id) decides which shard owns each row. It lets you scale writes and storage beyond what a single machine can handle, at the cost of significant application and operational complexity.
| Strategy | How rows are placed | Pros | Cons |
|---|---|---|---|
| Hash | hash(key) mod N or consistent hashing | Even distribution | Range queries hit every shard |
| Range | Key ranges (A-F, G-M, ...) or date ranges | Efficient range scans | Hot spots on newest range |
| Directory / lookup | A mapping table says which shard owns a key | Flexible moves, tenant pinning | Lookup service is a dependency |
| Geo | By region or country | Data residency, low latency | Uneven load across regions |
Naive mod N forces moving most rows when N changes. Consistent hashing or a fixed large number of logical shards (say 1,024 virtual shards mapped onto 8 physical servers) keeps rebalancing incremental.
A good key has high cardinality, spreads load evenly, and appears in most queries so they can be routed to one shard. For a food delivery app, customer_id keeps a customer's orders together, but a restaurant dashboard listing all its orders would then fan out to every shard. Pick the key around the most frequent, latency-sensitive queries and serve the rest from a secondary store or an analytics copy.
Bad keys: created_at (all writes hit the newest shard), country (India dominates), booleans or low-cardinality enums.
Shard last. First try indexing, query tuning, caching, read replicas, vertical scaling and archiving old data. When you do need it, tools like Vitess (MySQL, used by YouTube and Slack), Citus (Postgres), MongoDB's built-in sharding, or distributed SQL databases such as CockroachDB and YugabyteDB handle much of the routing and rebalancing for you.
import hashlib
LOGICAL_SHARDS = 1024
# Mapping of logical shard ranges to physical servers (kept in config/etcd)
SHARD_MAP = {range(0, 256): "db-1", range(256, 512): "db-2",
range(512, 768): "db-3", range(768, 1024): "db-4"}
def logical_shard(user_id: int) -> int:
digest = hashlib.md5(str(user_id).encode()).hexdigest()
return int(digest, 16) % LOGICAL_SHARDS
def server_for(user_id: int) -> str:
ls = logical_shard(user_id)
for r, host in SHARD_MAP.items():
if ls in r:
return host
raise KeyError(ls)
print(server_for(8421))
# Resharding moves whole logical shards between servers;
# the hash function and LOGICAL_SHARDS never change.
A fixed number of logical shards decouples the hash from the number of servers, so scaling out means moving some logical shards rather than rehashing every row.
CREATE TABLE orders (
order_id BIGINT,
merchant_id BIGINT NOT NULL,
amount_paise BIGINT,
PRIMARY KEY (merchant_id, order_id) -- PK must include distribution column
);
SELECT create_distributed_table('orders', 'merchant_id');
Citus hash-distributes rows by merchant_id across worker nodes and routes single-merchant queries to one node.
Horizontal Scaling, Shard Key, Hash Sharding, Range Sharding, Hot Partition, Resharding