Skip to the page

Scaling and changing databases · senior

Shard keys, hot shards and unique ids

A shard key decides where data lives. A good key spreads load evenly and keeps common queries on one shard. A bad key makes one hot shard. Ids must be unique across shards.

The notes

What you must know

  • A key that only grows (such as a timestamp) sends every new insert to the same shard. The balancer moves old chunks later, but new writes still go to one place.
  • A good shard key has many distinct values, spreads writes evenly, has no single value that is too frequent, and matches the common queries so they go to one shard.
  • Hashed keys spread writes but turn range queries into scatter-gather. Ranged keys keep ranges local but can create hotspots. For one device in a time range, use { deviceId: 1, createdAt: 1 } or a hashed deviceId.
  • Changing a shard key later is possible in MongoDB with reshardCollection, but it needs spare disk and time.
  • Multi-tenant SaaS: shard by tenant_id, so a tenant's data and transactions stay together. Use many logical shards on fewer physical databases, and a directory that maps tenant to shard.
  • Moving a tenant: copy with logical replication or a backfill plus change capture, check counts and checksums, pause that tenant's writes briefly, switch the directory entry, then clean up.
  • Unique ids across shards: a Snowflake-style 64-bit id (41-bit time, 10-bit machine id, 12-bit sequence), or a time-ordered UUID. Handle a clock moving backwards. JavaScript numbers are exact only up to 2^53, so send 64-bit ids as strings in JSON.

The red pen

Common traps: mistake → fix

  • Mistake: Add more shards to fix a hot shard

    Fix: the write key is still the problem.

  • Mistake: Shard by date

    Fix: it makes one hot shard.

  • Mistake: Random 64-bit ids are fine, collisions are unlikely

    Fix: use a designed scheme.

  • Mistake: Send 64-bit ids as numbers to browsers

    Fix: they lose precision above 2^53.

Easy to hard

Questions interviewers ask, easy to hard

  1. We sharded a MongoDB collection on createdAt and one shard is at 100% CPU. Why?
  2. Which shard key for a multi-tenant invoicing app?
  3. How do you move one big tenant to its own shard?
  4. Design a 64-bit id that is unique across shards.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview