Quick revision
The short answer
The rebalancer measures each bucket's data size, read and write rates and CPU, and defines imbalance as the hottest shard's load divided by the mean on the most constrained resource. It plans greedily, moving the buckets that remove the most imbalance per byte copied from the most loaded shard to the least loaded one that stays under target, executes every move with the standard copy, catch-up, fence, switch and verify protocol under concurrency caps, and uses hysteresis, cooldowns and automatic pauses so it never chases noise or makes an incident worse. It starts in recommend-only mode.
What to remember
In this answer, we designed an automatic rebalancer for 4,096 buckets on 40 shards. It measures size, read and write rates and attributed CPU per bucket over weeks, defines imbalance as the max-to-mean ratio on the most constrained resource at peak, and plans greedily by imbalance removed per byte copied, avoiding buckets at their peak. Every move runs the standard copy, catch-up, fence, switch and verify protocol under per-shard and global caps. Hysteresis, cooldowns and automatic pauses keep it from oscillating or acting during incidents, and it starts in recommend-only mode before acting within a daily budget with a kill switch and an audit log.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The rebalancer measures each bucket's data size, read and write rates and CPU, and defines imbalance as the hottest shard's load divided by the mean on the most constrained resource. It plans greedily, moving the buckets that remove the most imbalance per byte copied from the most loaded shard to the least loaded one that stays under target, executes every move with the standard copy, catch-up, fence, switch and verify protocol under concurrency caps, and uses hysteresis, cooldowns and automatic pauses so it never chases noise or makes an incident worse. It starts in recommend-only mode.
Why this question is asked
Moving buckets by hand works for a while, but with 40 shards and 4,096 buckets the imbalance grows faster than people can fix it, and every manual move carries the risk of a step skipped in the runbook. An automatic rebalancer is the natural next step, and also a dangerous one: a system that moves data on its own can turn a small problem into a big one. Interviewers ask this design question to see whether we can build the measurement, the planning and the safety around the moves, not only the moves themselves. In this answer, we will define what to measure, decide what imbalance means, plan moves, execute them safely, add damping, and roll the rebalancer out gradually.
1What We Are Building and Why
The platform maps 4,096 logical buckets to 40 PostgreSQL shards, about 100 buckets per shard on average. Because buckets differ in size and activity, some shards now carry twice the data and traffic of others. The rebalancer's job is to keep every shard within a target band, for example no shard above 120 percent of the mean on any resource, with as little data movement and risk as possible. It has four parts: a metrics collector, a planner, an executor and a set of safety controls around all of them.
- Metrics collectorsize, reads, writes and CPU per bucket and per shard
- Plannercomputes imbalance and proposes moves within a budget
- Safety controlshysteresis, cooldowns, pause on incidents, kill switch
- Executorruns the move protocol with concurrency caps
- Audit logevery decision, its inputs and its result
5 layers, from the top down. Step through them one at a time.
2Measuring Load per Bucket and per Shard
Moves are made of buckets, so we need costs per bucket, not just per shard. Data size is easy: each bucket's rows live in identifiable partitions or carry a bucket column, so we can sum table and index sizes. Read and write rates per bucket come from the routing layer, which knows the bucket of every request it sends. CPU is the hardest: PostgreSQL does not report CPU per bucket, so we attribute each shard's CPU to its buckets in proportion to their share of query time, which pg_stat_statements or per-request timing at the router can provide.
We store these as time series, at least hourly over several weeks, so the planner sees daily and weekly patterns rather than a single snapshot. A bucket that is hot every Monday morning and idle otherwise is a different case from one that is constantly heavy.
3Defining Imbalance
For each resource, disk, CPU, read IOPS and write IOPS, we compute each shard's load and the mean across shards. Imbalance for that resource is the hottest shard's load divided by the mean: 1.0 is perfect, 2.0 means the hottest shard carries twice the average. The overall imbalance is taken on the most constrained resource, the one closest to its limit, because that is what will hurt first. If disks are at 40 percent everywhere but one shard's CPU is at 85 percent, CPU is the resource to balance. We also look at the peak, for example the p95 of hourly CPU, rather than the daily average, since shards fail at their peaks.
4Planning Moves Greedily
Finding the perfect assignment of 4,096 buckets to 40 shards is a hard optimisation problem, and a perfect plan that moves 1,000 buckets is worse than a good plan that moves 20. So the planner is greedy and incremental. It takes the most loaded shard, considers its buckets, and for each candidate computes how much imbalance moving it would remove, divided by the bytes it would copy. It picks the best ratio, chooses as destination the least loaded shard that would still be under target afterwards on every resource, and records the move. Then it updates its model of both shards and repeats, until imbalance is within the target band or the move budget for the day is used.
Preferring imbalance removed per byte copied favours small, busy buckets, which are cheap to move and do the most good. The filters matter too: a bucket in its cooldown period, or one that is at its daily peak right now, is skipped, since moving a bucket at its busiest moment puts the most risk on the most users.
5Executing Moves With the Standard Protocol
The planner only proposes; the executor carries out each move with the same protocol a careful operator would follow: bulk copy the bucket to the destination, catch up with change data capture, fence writes for the bucket at the router and on the source, apply the final changes up to the recorded log position, switch the directory with a new epoch, verify with row counts and per-chunk checksums, and delete the source copy later, after a safety period. Each step is idempotent and its state is persisted, so a crashed executor can resume.
Concurrency is capped at two levels: at most one or two moves in progress per shard, since each move adds copy load on both sides, and a global cap, such as four at a time, so the fleet as a whole is never busy moving data. Copy speed is throttled to protect foreground latency.
6Damping So It Never Makes Things Worse
Automatic controllers can oscillate, chasing noise or moving the same bucket back and forth. We prevent that in three ways. Hysteresis: the rebalancer starts acting only when imbalance exceeds an upper threshold, for example 1.3, and stops when it falls below a lower one, such as 1.15, so small differences produce no moves at all. Cooldowns: a bucket that moved cannot move again for, say, seven days. And automatic pauses: if any shard is degraded, replication lag is high, an incident is open, or p99 latency on any shard is above its target, the rebalancer stops starting new moves, because moving data during trouble adds load at the worst time.
- Collect metrics for all bucketslast 14 days, peak-aware
- Incident open or any shard degraded?YesPause and alertNoContinue
- Imbalance above the upper threshold?YesPlan moves within the daily budgetNoDo nothing
- Mode is recommend-only?YesPublish the plan for operatorsNoExecute with concurrency caps
- Verify and record every moveaudit log and metrics
5 steps in order. Play them, or step through them one at a time.
7Rolling the Rebalancer Out
We earn trust before granting autonomy. The first phase is recommend-only: the rebalancer publishes its plans every day, operators keep moving buckets by hand, and we compare its suggestions with the operators' choices and with the outcomes. Once its plans are consistently sensible, it may act alone within a small daily budget, for example 200 GB or 20 buckets, with a kill switch that stops new moves instantly and an audit log that records every decision with its inputs. The budget grows as confidence grows. Operators keep the ability to pin a bucket to a shard, for example a tenant with a contractual placement, and the planner respects those pins.
8Follow-up questions
Which metric would prove the rebalancer improves the fleet?
The max-to-mean ratio of the most constrained resource at peak, tracked over weeks, should fall and stay within the target band, together with p99 latency on the hottest shard. We would also track the cost side: bytes moved per week and any latency impact during moves. A rebalancer that keeps imbalance low while moving little data and causing no latency spikes is working; one that moves a lot without lowering the ratio is chasing noise.
Why not rebalance continuously in real time?
Load changes faster than data can move. A bucket that is hot for ten minutes cannot be moved in ten minutes without risk, and by the time it arrives the spike is over. Rebalancing works on sustained patterns; short spikes are handled by capacity headroom, caching and rate limiting.
9Conclusion
In this answer, we designed an automatic rebalancer for 4,096 buckets on 40 shards. It measures size, read and write rates and attributed CPU per bucket over weeks, defines imbalance as the max-to-mean ratio on the most constrained resource at peak, and plans greedily by imbalance removed per byte copied, avoiding buckets at their peak. Every move runs the standard copy, catch-up, fence, switch and verify protocol under per-shard and global caps. Hysteresis, cooldowns and automatic pauses keep it from oscillating or acting during incidents, and it starts in recommend-only mode before acting within a daily budget with a kill switch and an audit log.
Open with
I would build it in four parts: measurement, planning, execution and safety. For measurement, I need costs per bucket, not just per shard: data size, read and write rates from the router, and CPU attributed to each bucket by its share of query time, kept over a few weeks so I see peaks.
Then, if they want more
Imbalance is the hottest shard's load divided by the mean, on whichever resource is most constrained, at peak rather than average.
Planning is greedy: take the most loaded shard, pick the bucket that removes the most imbalance per byte copied, send it to the least loaded shard that stays under target on every resource afterwards, update the model and repeat until we are in the target band or hit the daily budget, and skip buckets that are at their peak or recently moved.
Execution uses the standard protocol for every move: copy, catch up with change capture, fence writes, final catch-up to the recorded LSN, switch the directory with a new epoch, verify with checksums, delete the source later. I cap concurrent moves per shard and globally and throttle copy speed.
For safety, hysteresis thresholds so small differences do nothing, a cooldown per bucket, and an automatic pause when any shard is degraded or an incident is open. And I would run it in recommend-only mode first, then let it act within a small daily budget with a kill switch and an audit log.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Design an automatic rebalancer: how it measures imbalance, chooses which buckets move...": https://scrivio-interview-library.netlify.app/architecture/partitioning-and-replication/42953aa229/