Data Skew

Difficulty: Advanced

Question

What is data skew in a sharded database, what causes it, and how do you fix it?

Answer

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.

Two kinds of skew

  • Storage skew: one shard holds much more data than others, such as when sharding by country and most users are in India.
  • Access (load) skew: data is spread evenly, but requests are not. Example: sharding a food delivery platform's orders by 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.

Common causes

  • Low-cardinality shard key: status, city or plan_type have only a few distinct values, so a few shards get everything.
  • Celebrity or whale keys: one tenant, merchant or user is much bigger than the rest. A large enterprise customer in a SaaS product, or a viral influencer in a social app.
  • Monotonic keys with range sharding: if you range-shard on a timestamp or auto-increment id, every new write lands on the last shard.
  • Time-based bursts: flash sales and festival traffic like Big Billion Days concentrate on a few products.

How to fix or prevent it

TechniqueHow it helpsCost
High-cardinality shard keySpreads data across many valuesMust still match query patterns
Hash shardingRandomizes placement of sequential keysRange queries hit every shard
Compound key (tenant_id, user_id)Splits big tenants across shardsTenant-wide queries fan out
Key saltingAppends a suffix like merchant_id#3 to split a hot keyReads must query all suffixes and merge
Split or move hot shardsRebalance large ranges to new nodesData movement during rebalancing
Dedicated shard for whalesIsolate one huge tenantOperational special case
Caching hot readsAbsorbs read-heavy hot keysStaleness, 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.

How to detect it

  • Compare per-shard metrics (rows, CPU, p99 latency, throttled requests), not just cluster averages.
  • Track the top N keys by request count; a few keys taking a large share is the signature of access skew.
  • DynamoDB's CloudWatch Contributor Insights shows the most accessed partition keys.
How one hot key slows the whole cluster. Requests for a single popular key all route to the same shard.
  1. Flash sale traffic: Most requests target one product id.
  2. Router hashes shard key: Same key always maps to the same shard.
  3. Shard 3 overloaded: CPU and I/O maxed, queues grow.
  4. Other shards idle: Spare capacity cannot be used.
  5. Timeouts for users: p99 latency spikes across the app.

Code examples

Write sharding (salting) a hot key

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.

Checking shard size distribution in Citus

-- 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.

Key points

  • Data skew = uneven distribution of data or load across shards, creating hot spots.
  • Usually caused by a low-cardinality, monotonic or celebrity-dominated shard key.
  • Hash sharding fixes monotonic keys; salting fixes individual hot keys.
  • Monitor per-shard metrics, not cluster averages.
  • Managed rebalancing helps, but a single extremely hot key needs a design change.

Common follow-up questions

  • How would you choose a shard key for a multi-tenant SaaS product?
  • What are the trade-offs of hash vs range sharding?
  • How does consistent hashing reduce data movement when adding shards?
  • How would you handle a single tenant that outgrows one shard?

Interview tips

  • Distinguish storage skew from access skew; many candidates only describe one.
  • Tie the cause to the shard key choice and give a concrete bad key, like city or a timestamp.
  • Explain the read cost of salting so it does not sound like a free fix.

Concepts covered

Data Skew, Hot Partition, Shard Key, Key Salting, Consistent Hashing

More Database Design questions