Shard rebalancing and hotspots: moving data without downtime and taming hot keys

Shards never stay balanced. Data grows unevenly, one celebrity floods a single shard, a machine dies. Learn how to move data between live shards without downtime or lost writes, how to find and cool down hotspots, and why chasing perfect balance makes things worse.

Four storage bins standing in a row. Three are calm and half full. The third bin glows red, with a star-shaped celebrity box on top and a crowd of request arrows pouring into it. A small crane lifts boxes out of the hot bin toward an empty new bin on the right, while a conveyor keeps delivering new boxes. A sign above says 'Move it without stopping the line.'
Fig. 1 — Shards drift out of balance, and one hot key can overload a shard on its own. Rebalancing moves data while traffic keeps flowing.

A restaurant has four waiters, ten tables each. It works well, until it doesn’t. The owner adds twenty tables. A big party fills one section. A waiter calls in sick. The tables have to be reassigned, and dinner can’t stop while that happens.

Shards live the same life. We picked a sharding strategy, and on day one everything was even. Then:

  • Growth: four shards that were fine at 1 million users are drowning at 10 million.
  • Uneven data: one shard has 500 GB while the others have 150 GB.
  • Hot traffic: one shard serves 100,000 requests a second while the others serve 10,000, because a celebrity lives there.
  • Failure or cost: a machine dies, or you want to move to cheaper hardware.

Each of these means moving data between live shards: rebalancing. It’s one of the riskiest jobs in a sharded system. There may be terabytes to move, the system can’t stop, and a mistake can lose or corrupt data.

Even data is not even load

The first lesson: two shards can hold exactly the same number of users and have completely different workloads.

Two bar charts for four shards. Left, data stored: every shard holds 250,000 users, perfectly even. Right, requests per second: shards 1, 2 and 4 handle about 10,000 each, but shard 3 handles 100,000, ten times more, because one celebrity user lives there. A label says shard 3 is the bottleneck even though the data is balanced.
Balancing data doesn't balance traffic. One very popular key can make one shard ten times busier than the rest.

So watch both per shard: storage (GB) and traffic (requests per second, CPU, latency). Storage imbalance needs data moved. Traffic imbalance usually needs the hot keys found and handled, which is a different job. We’ll do both.

Moving data without downtime

The simplest approach is stop the world: take the system offline, copy the data, switch the routing, come back up. It’s safe and simple, and fine for small datasets in a maintenance window. For anything big and always-on, you need to move data while reads and writes keep flowing.

The standard recipe has six phases:

A timeline of six phases moving data from an old shard to a new shard, showing where writes and reads go in each phase. Phase 1, dual write: writes go to both old and new, reads come from old. Phase 2, backfill: existing rows are copied in throttled batches to new, while dual writes continue. Phase 3, verify: compare row counts and checksums between old and new, and re-copy anything that differs. Phase 4, switch reads: reads move to new gradually, 1 percent, then 10, then 100, while writes still go to both. Phase 5, switch writes: writes go only to new. Phase 6, clean up: after a safety period, old data is deleted. Up to phase 5, rollback is easy because old still has everything.
Start copying new writes first, then backfill the old ones. Old keeps everything until the very end, so you can always go back.

1. Start dual writes. Every new write for the moving data goes to both the old and the new shard. Reads still come from the old shard, so users notice nothing.

2. Backfill. Copy the existing rows to the new shard in small batches, throttled so you don’t slow down real traffic. Order matters: start dual writes before the backfill, or writes that happen during the copy get lost. The backfill must also never overwrite a newer value from a dual write, so copy with “insert if missing” or compare a version number.

3. Verify. Compare row counts and checksums between old and new. Re-copy anything that differs. Don’t switch until they match.

4. Switch reads, gradually. Send 1% of reads to the new shard, watch errors and latency, then 10%, 50%, 100%. Writes still go to both, so you can still turn back.

5. Switch writes. Point writes only at the new shard and update the routing. From here, the new shard is the source of truth.

6. Clean up, later. Keep the old copy for a safety period (days, not minutes) in case you need to roll back. Then delete it in throttled batches.

// Java · the router decides per key, based on the migration phase
public void write(Key key, Row row) {
    Migration m = migrations.find(key);
    if (m == null)                         { shardFor(key).upsert(row); return; }
    switch (m.phase()) {
        case DUAL_WRITE, BACKFILL, VERIFY, READS_ON_NEW
                         -> { m.oldShard().upsert(row); m.newShard().upsert(row); }
        case WRITES_ON_NEW, DONE -> m.newShard().upsert(row);
    }
}

public Row read(Key key) {
    Migration m = migrations.find(key);
    if (m == null) return shardFor(key).get(key);
    return m.readsFromNew(key) ? m.newShard().get(key) : m.oldShard().get(key);   // % rollout
}

Two practical notes:

  • App-level dual writes have a weak spot: one write can succeed and the other fail. Make writes idempotent with a version or request ID, so retries are safe, and let the verify phase catch any gaps. Many teams avoid the problem by using change data capture (CDC): the database’s own change log is streamed to the new shard, so the app doesn’t write twice at all.
  • Move in big units. If you used logical shards, you move whole logical shards between servers, and the routing change is one row in a small map. That’s far easier than tracking millions of individual keys.

Hotspots: when one key is the problem

A hotspot is a shard getting much more traffic than the others. There are three kinds:

  • A hot key: one celebrity, one viral post, one product on flash sale. Moving the data around doesn’t help much: wherever that key goes, its traffic follows.
  • A hot range: with range sharding on an increasing key (timestamps, auto-increment IDs), all new writes land on the last shard.
  • A hot tenant: in a multi-tenant app, one giant customer outgrows its shared shard.
Four fixes for a hot key, as cards. Cache it: put the celebrity's profile and posts in Redis or a CDN, so most reads never reach the shard. Add read replicas: spread reads for the hot shard over several copies. Split the key: instead of one counter row for likes on a viral post, write to ten sub-keys, likes:post9:0 to likes:post9:9, chosen at random, and add them up when reading, which spreads writes over ten places. Isolate it: move the hot user or tenant to a dedicated shard with its own replicas, so it can't hurt its neighbours.
Read-heavy hot keys: cache and replicate. Write-heavy hot keys: split them. Huge tenants: give them their own shard.

Act in layers, from fastest to most lasting:

Minutes: buy time.

  • Cache the hot data (Redis, or a CDN for public content). Most hotspots are reads, and a cache absorbs them before they reach the shard.
  • Add read replicas to the hot shard, or scale it up.

Hours: fix the shard.

  • Find the hot keys. Keep per-key request counts (even a sample of the top 100 keys per shard is enough). You can’t fix what you can’t name.
  • Isolate them. Move the hot user or tenant to a dedicated shard with its own replicas. A directory or logical-shard map makes this one routing change.

Days: fix the design.

  • Split write-heavy keys. A viral post’s like counter is one row taking every write. Spread it over N sub-keys (likes:post9:0 … likes:post9:9), write to a random one, and sum them on read. This is called key salting or write sharding.
  • Change the access pattern. If celebrity posts are pushed into millions of feeds, switch celebrities to a pull model: followers fetch their posts at read time (see fan-out in data modeling).
  • Change the key. For a hot range, put a hash in front of the timestamp so new writes spread out.
// Java · split a hot counter over 10 sub-keys
private static final int SPLITS = 10;

public void like(long postId) {
    int part = ThreadLocalRandom.current().nextInt(SPLITS);
    redis.opsForValue().increment("likes:" + postId + ":" + part);   // writes spread over 10 keys
}

public long likes(long postId) {
    return IntStream.range(0, SPLITS)
        .mapToObj(i -> redis.opsForValue().get("likes:" + postId + ":" + i))
        .filter(Objects::nonNull).mapToLong(Long::parseLong).sum();  // reads add them up
}

Ramp up slowly

Moving a hot user to a fresh shard can backfire. The new shard has empty caches and cold disks. Send it 100% of a celebrity’s traffic at once and it falls over. Traffic falls back to the old shard, which is now even more loaded, and it falls over too. One move has become a cascading failure.

The fix is the same as phase 4 above: warm the new shard first (pre-load its caches), then shift traffic in steps (1%, 10%, 50%, 100%) and watch latency and errors at each step before going further.

Trade-offs between approaches

Approach Downtime Complexity Risk Good for
Stop the world Yes Low High (no easy rollback) Small data, maintenance windows, staging
Dual write + backfill None High Medium Most production moves
Change data capture None High (extra tooling) Lower Large, busy datasets
Consistent hashing / logical shards None Medium, built in Low Ongoing growth, with minimal data moved

What breaks, and how to fix it

What breaks Why The fix
Writes lost during the move Backfill started before dual writes, or a backfill overwrote newer data Dual-write first; backfill with insert-if-missing or version checks
Migration stalls halfway A crash, or the copy is too slow Checkpoint progress and resume; old shard still serves everything
New shard crashes after cutover Cold caches, or not enough capacity Warm it up, ramp traffic in steps, keep the old copy to fall back to
One write succeeds, the other fails Network trouble during dual writes Idempotent writes with versions, retries, and a verify pass
Rebalancing slows production Copying competes with real traffic Throttle batches, run in quiet hours, read from replicas

Puzzle 1: the hotspot that follows you

You’re moving data, but the problem is traffic. Shard 3 had a million users, and one of them (a celebrity) was producing most of the load. Every time you move half the users, the celebrity goes with one half, and so does the hotspot.

Measure per-key traffic, not just per-shard. Find the top keys, then deal with them directly: cache their data, give them a dedicated shard with replicas, or split their hottest counters. And check that each rebalance actually worked: if the source shard’s traffic didn’t drop by roughly the share you moved, you moved the wrong data.

Puzzle 2: zombie data

Something is still reading from the old location:

  • A stale route in a cache. Some app servers or caches still think the data lives on the old shard and serve whatever they find there, or what they cached before the move.
  • A lagging replica of the old shard that hasn’t applied the deletes yet.
  • A cleanup job that died halfway, leaving part of the old data behind.

Prevent it in order: invalidate routing caches first, wait for their TTLs to expire, then soft-delete the old copy and watch for any reads hitting it. Only after a quiet safety period with zero reads to the old location do you hard-delete. Deleting is the one step you can’t undo, so it goes last and slowest.

Puzzle 3: the perfectly balanced disaster

Rebalancing isn’t free. Every move uses disk, network and CPU, adds dual-write overhead, and brings risk. New signups always land somewhere, so some shard is always “slightly above average”. The system ends up constantly moving data, and the moving costs more than the imbalance ever did.

Allow some imbalance. Rebalance only past a clear threshold, say a shard at 1.5× the average load or above 70% of its capacity. Add a cool-down period between moves. A 20% difference between shards is normal and harmless. A shard running out of disk is not.

Key takeaways

  1. Shards drift. Growth, uneven data, hot users and failures all force rebalancing sooner or later.
  2. Even data isn’t even load. Watch storage and traffic per shard, and per key.
  3. Zero-downtime moves follow one recipe: dual write, backfill, verify, switch reads gradually, switch writes, clean up much later.
  4. Hot keys follow you. Cache and replicate hot reads, split hot writes, and give giant users or tenants their own shard.
  5. Ramp traffic onto new shards slowly, or one move can turn into a cascading failure.
  6. Don’t chase perfect balance. Rebalance past a threshold, not on every small difference.

That completes the Partitioning, sharding & distribution thread: when to scale out, how to split data, and how to keep it balanced. Next comes the other side of distributed data: keeping copies of it in sync, starting with replication.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.