Difficulty: Advanced
What is data skew in a sharded database, what causes it, and how do you fix it?
Data skew is when data or traffic is distributed unevenly across shards, so one shard holds far more rows or receives far more requests than the others. That shard becomes a hot spot: it runs out of CPU, I/O or storage first, and because the system is only as fast as its busiest shard, the whole cluster underperforms even though other shards sit idle. The root cause is almost always the choice of shard key.
country and most users are in India.restaurant_id, then a popular chain gets a flood of orders during an IPL final.Both lead to the same symptoms: one shard with high latency, timeouts, replication lag or throttling, while the cluster average looks healthy.
status, city or plan_type have only a few distinct values, so a few shards get everything.| Technique | How it helps | Cost |
|---|---|---|
| High-cardinality shard key | Spreads data across many values | Must still match query patterns |
| Hash sharding | Randomizes placement of sequential keys | Range queries hit every shard |
| Compound key (tenant_id, user_id) | Splits big tenants across shards | Tenant-wide queries fan out |
| Key salting | Appends a suffix like merchant_id#3 to split a hot key | Reads must query all suffixes and merge |
| Split or move hot shards | Rebalance large ranges to new nodes | Data movement during rebalancing |
| Dedicated shard for whales | Isolate one huge tenant | Operational special case |
| Caching hot reads | Absorbs read-heavy hot keys | Staleness, invalidation |
Managed systems help partly: DynamoDB has adaptive capacity that shifts throughput toward hot partitions and splits them, MongoDB's balancer moves chunks between shards, and Citus lets you choose a distribution column and rebalance shards. None of these fully fixes a single extremely hot key; that needs a design change like salting.
const SALT_BUCKETS = 10;
// Spread writes for one hot merchant across 10 partitions
function saltedKey(merchantId) {
const bucket = Math.floor(Math.random() * SALT_BUCKETS);
return merchantId + "#" + bucket; // e.g. "M-77#4"
}
// Reads must gather from every bucket and merge
async function getRecentPayments(db, merchantId) {
const queries = [];
for (let b = 0; b < SALT_BUCKETS; b++) {
queries.push(db.queryByPartition(merchantId + "#" + b, { limit: 50 }));
}
const parts = await Promise.all(queries);
return parts.flat().sort((a, b) => b.createdAt - a.createdAt).slice(0, 50);
}
Salting trades read fan-out for evenly spread writes. Apply it only to keys known to be hot.
-- Choose a high-cardinality distribution column
SELECT create_distributed_table('payments', 'merchant_id');
-- Inspect shard sizes to spot storage skew
SELECT nodename, count(*) AS shards,
pg_size_pretty(sum(shard_size)) AS total_size
FROM citus_shards
WHERE table_name = 'payments'::regclass
GROUP BY nodename;
Uneven total sizes across nodes reveal storage skew; Citus can then rebalance shards between workers.
Data Skew, Hot Partition, Shard Key, Key Salting, Consistent Hashing