Skip to content

Rebalancing

Mohammad Rasoul Kazemi edited this page Nov 26, 2026 · 2 revisions

Rebalancing

Rebalancing moves hash buckets (and distributed schemas) between shard groups so that the placement matches the target: after a server is added, before a server is removed or drained, after the replica count or a server group changed, or when the placement is skewed. This page is the administrator's view. The extension functions are in Sharding; the control-plane implementation is in Control Plane and REST API.

State: built (phases 4, 10 and 11). A rebalance is one task run by the manager leader, one move at a time. Strategies by bucket count or by disk size, weights, a threshold, an automatic mode (off by default), draining a server (including the hand-over of the map group), splitting a bucket and distributed schemas as items of the plan are all built. Moves that run together are not: see "One move at a time". See Status and Roadmap and Limitations and Known Issues.

When a rebalance is needed

GET /rebalance (kingres_readonly) answers needed and the reasons: serverAdded, serverRemoved, replicaCountChanged, replicasMissing, skewed, serverGroupChanged. The state is idle, running, stopping, stopped (a paused run) or failed (the last run failed). The console shows the same on the Rebalance page.

Preview, start, stop, resume

  1. Preview. POST /rebalance/plan (kingres_readonly) returns the plan that would be used, without moving anything (moveLimit caps the list, default 200, up to 5000). The preview names the strategy and the threshold, the imbalance and the load of each server before and after. The plan comes from the extension (plan_rebalance, and rebalance_plan() for the plan by bucket count).
  2. Start. POST /rebalance (kingres_ops) starts one cluster-wide task of kind rebalance (202 with a Task). Options: databases (omitted or empty means all), the strategy, the threshold, maxMovesPerServer, maxConcurrentMoves and force. What a request leaves out comes from the cluster settings (below).
  3. Follow. The task has the steps Check that the cluster can rebalance, Compute the plan, Move buckets and Write the report. In the third step the plan is computed again before every move and the first move that is not backing off is made through kingres.move_bucket(...) (or the schema move) on the map group primary.
  4. Stop. POST /rebalance/stop (kingres_ops) sets a flag: the move in flight is cancelled through the extension (before its switch it is undone; a move already switching cannot be cancelled and is asked again until it ends, so the switch is never interrupted), no other move starts, and the task becomes paused (state stopping, then stopped).
  5. Resume. POST /rebalance again goes on with the same task. A start is a new decision of a person: the attempts and skips of the stopped round do not count, the request's options replace the old ones, and the plan is computed again.
  6. Cancel. POST /tasks/{id}/cancel on a paused rebalance ends the run as cancelled and raises no taskFailed alert.

A rebalance survives a restart of kingresd and a change of leader. A stopped rebalance does not block updateServer or removeServer; between a stop and a start an operator can change shouldHaveShards (Servers Databases and Roles).

One move at a time

A run makes one move at a time, whatever the value of maxConcurrentMoves. The option (1 to 64) is accepted and recorded; when a start leaves it out it is recorded as 1. The cluster setting rebalance.maxConcurrentMoves (default 4) is a default that is shown and changed in the settings; it is not what a start without the option records, and it does not make moves run together. The extension itself can run moves of different buckets together, and its README says what a move costs the nodes, but the control plane does not use that.

Strategies, threshold and weights

  • Strategy. byBucketCount (the default; every bucket costs 1) or byDiskSize (the size of the bucket's partitions of every table of the colocation group, at least kingres_shard.min_bucket_cost, 1 MiB by default). A group whose sizes cannot be read gives KS018 and the control plane answers 503 with a retry hint: a plan by disk size does not guess.
  • Threshold. How far a server may be from the ideal before a move is planned: 0 by bucket count and 0.1 by disk size by default. maxMovesPerServer caps the moves per server.
  • Weights. A server has a weight (PATCH /servers/{serverId} with weight, or the Servers page): a larger weight gets more. Nothing moves until the next rebalance.
  • Settings. rebalance.strategy, threshold, maxMovesPerServer, maxMoveAttempts, maxDiskUsedFraction and maxStandbyLagBytes are cluster settings (PATCH /settings/cluster, the Settings page). All of this needs kingres_shard 0.8 or later; against an older extension anything but the plan by bucket count is refused with 422 unsupported_operation.

Distributed schemas in the plan

The plan and the run include the distributed schemas of the database (Sharding): a schema is one item that moves whole, shown in the plan, the progress and the report with kind schema and its schemaName (contract 0.31.0). A schema counts as one bucket by byBucketCount and as its size (at least 1 MiB) by byDiskSize. A schema that holds a ledger table is pinned and is not planned; its size stays on its group as load. A move of a schema is a failure of the run, like a move of a bucket, when it is given up.

Automatic mode

Off by default (rebalance.automatic.enabled). When on, the leader looks at the cluster at an interval and starts a rebalance only when the imbalance has held for a settle time, the servers have not changed lately, enough time has passed since the last automatic run, and no safety rule holds it back (a failover, a primary that changed lately, a group without a primary or without the standbys the replica count asks for, a dead or suspect server, a failed earlier move nobody acknowledged, a failing cluster check). A run pauses when a rule fails and resumes when the rules have held again. A failed automatic run raises the alert rebalanceFailed and suspends the mode until an operator starts a rebalance. The Rebalance page shows the last evaluation. A run of the automatic mode also makes one move at a time.

Standby lag

A rebalance is held back while a group has a standby that is behind its primary by more than maxStandbyLagBytes (default 64 MiB), or whose lag cannot be read. A manual start is refused with 409 group_degraded; force: true lifts that refusal, and only that one, for that start. The automatic mode treats such a group like a group without a healthy standby and pauses.

Drain

POST /servers/{serverId}/drain (preview: .../drain-preview) empties a server so that it can be removed. It stops new buckets from landing on it, moves its buckets and its distributed schemas away, relocates the standbys it hosts to other servers, writes a report and, if you asked, removes the server. A drain is a task of kind rebalance, so it excludes failover and other server tasks, and its progress is on the Rebalance page.

  • Refusals before a task exists: an unknown server, the last server, no server that can receive buckets, a server that has the map group when no other server runs a standby of it (409 server_hosts_map_group), too few servers to keep the replicas (replicas_cannot_be_kept; acceptFewerReplicas overrides), a degraded group, a dead server, and a server that holds ordinary tables that would leave with it (acknowledgeLocalData). A schema that cannot move refuses the drain, naming it: 409 schema_pinned for a schema with a ledger table, 422 unprocessable for a table that is not logged or has neither a key nor a full replica identity (set REPLICA IDENTITY FULL, then try again).
  • Draining the server that runs the map group. Once the buckets have moved, the step Hand over the map group pauses the drain and asks for a planned switchover of the map group (High Availability) to a standby on another server. The drain goes on under the new manager leader and keeps its task id. While it waits, the Rebalance page shows the drain as stopped by a safety rule. A switchover that is refused or rolled back fails the task with its own code, the server stays draining, and the drain can be started again.
  • The drain ends only when no bucket and no schema is left on the server; a schema whose old copy is not yet emptied still counts.

Split a bucket

POST /databases/{db}/colocation-groups/{colocationId}/buckets/{bucket}/split (preview: .../split-preview) splits a bucket into several, so that a hot or large bucket can be spread. It is the task bucket.split and it cannot be undone. A cancel works until the backfill ends, and the console says truthfully when it came too late and the split completed. A table without a primary key is refused when the split starts, and so is a colocation group with a columnar table.

Refusals before a start

A start is refused with 409 and a code, before any task exists: rebalance_in_progress, operation_in_progress (another task adds, removes or leaves a server, or a database import runs), failover_in_progress, group_degraded, version_mismatch (servers differ in extension version or PostgreSQL major), cluster_inconsistent (kingres.check_cluster() reports something that makes moving unsafe), no_receiving_server, nothing_to_rebalance. 503 map_group_unavailable while the map group is failing over. The same conditions are checked again before each move; one that stops holding stops the run (outcome stopped, stoppedBy safetyRule) instead of failing it. A run also stops when it has made more than three times the first plan plus ten moves, because something else keeps changing the placement.

A rebalance and a server operation (server.add, server.remove, server.leave, server.failover) exclude each other; the database enforces it. A failover first stops a running rebalance, and nothing resumes it afterwards: a person starts it again.

Failures and retries

A failed move is tried again after 30 s times its failure count, up to three tries (maxMoveAttempts), while other buckets go on. A bucket that fails three times is given up and the run ends failed (the report is written first and the alert taskFailed carries the task). Skipped moves are in the report and are not failures: a group lost its lease, a group needs a synchronous standby that is not in sync, or the target disk is low (the disk check was not verified on real servers: no server reports its disk yet).

After a restart of kingresd or a change of the manager leader the new leader claims the task under a new epoch and settles a move left running through the extension (resume_bucket_moves()), never with its own SQL. A holder that lost the task's lease writes nothing. A call to move_bucket that has a record is not cancelled; the next holder waits for the live move.

A move or split does not drop an old copy that objects of its owner depend on (a view, a foreign key, a function on its row type): the copy stays, check_cluster() reports orphan_blocked, and the next cleanup after the owner dropped the dependents finishes the move.

What a move does to standbys

A move changes who owns data, not where standbys are. The replication slot and subscription of a move are on the source and target primaries. A failover during a move fails and undoes it. kingresd writes wal_level = logical into the instances it creates; an instance created earlier needs a restart, and the start check says so. While a database import runs, a drain, a rebalance and a change of a weight or of shouldHaveShards are refused with 409 operation_in_progress.

Reports

GET /rebalance/reports and /rebalance/reports/{reportId} (the id is the task id) list every run with placement before and after and the result of each move, schema items included.

Not verified on real servers

From the control-plane README: the free-disk check (no server reports its disk yet), the lease check for groups whose primary runs on another server (the leader knows only its own leases) and a leader change in the middle of a move (the tests restart the leader's kingresd but cannot move the map group). Two failures at once, and a failure during a rebalance, are not tested on a cluster. One narrow window remains by design: a process frozen between the guard's liveness check and its write on the socket longer than the idle timeout can issue a late call; the data stays correct and the report may miss that move.

Sources

Clone this wiki locally