Repository navigation
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.
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.
POST /rebalance/plan(kingres_readonly) returns the plan that would be used, without moving anything (moveLimitcaps 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, andrebalance_plan()for the plan by bucket count). -
Start.
POST /rebalance(kingres_ops) starts one cluster-wide task of kindrebalance(202 with aTask). Options:databases(omitted or empty means all), the strategy, the threshold,maxMovesPerServer,maxConcurrentMovesandforce. What a request leaves out comes from the cluster settings (below). -
Follow. The task has the steps
Check that the cluster can rebalance,Compute the plan,Move bucketsandWrite 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 throughkingres.move_bucket(...)(or the schema move) on the map group primary. -
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 becomespaused(statestopping, thenstopped). -
Resume.
POST /rebalanceagain 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. -
Cancel.
POST /tasks/{id}/cancelon a paused rebalance ends the run as cancelled and raises notaskFailedalert.
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).
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.
-
Strategy.
byBucketCount(the default; every bucket costs 1) orbyDiskSize(the size of the bucket's partitions of every table of the colocation group, at leastkingres_shard.min_bucket_cost, 1 MiB by default). A group whose sizes cannot be read givesKS018and 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.
maxMovesPerServercaps the moves per server. -
Weights. A server has a weight (
PATCH /servers/{serverId}withweight, or the Servers page): a larger weight gets more. Nothing moves until the next rebalance. -
Settings.
rebalance.strategy,threshold,maxMovesPerServer,maxMoveAttempts,maxDiskUsedFractionandmaxStandbyLagBytesare cluster settings (PATCH /settings/cluster, the Settings page). All of this needskingres_shard0.8 or later; against an older extension anything but the plan by bucket count is refused with 422unsupported_operation.
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.
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.
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.
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;acceptFewerReplicasoverrides), 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: 409schema_pinnedfor a schema with a ledger table, 422unprocessablefor a table that is not logged or has neither a key nor a full replica identity (setREPLICA IDENTITY FULL, then try again). -
Draining the server that runs the map group. Once the buckets have moved, the step
Hand over the map grouppauses 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 staysdraining, 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.
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.
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.
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.
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.
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.
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.
KingresDB's own code is licensed under AGPL-3.0-only. PostgreSQL code keeps the PostgreSQL License. Copyright of the project's own code: RooyeKhat Media Co. KingresDB is derived from PostgreSQL and is not endorsed by the PostgreSQL project. Repository | Licence | COPYRIGHT
KingresDB
1. Product
- Product Overview and Features
- Status and Roadmap
- User Guide
- Administrator Guide
- REST API Reference
- Web Console
- Command Line Client
- Extensions
- Limitations and Known Issues
- Release Notes
Features in detail
- Sharding
- Sharding Query Pushdown
- Sharding Table Lifecycle
- High Availability
- Ledger
- Ledger Signing and Publication
- Ledger Anchoring
- The Verifier
- Analytics Extensions
Administration
- Cluster Setup
- Servers Databases and Roles
- Rebalancing
- Configuration
- Memory and Warm-up
- Control Plane and REST API
- Upgrades
2. Architecture (arc42)
- Architecture
- Architecture Introduction and Goals
- Architecture Constraints
- Architecture System Context
- Architecture Containers
- Architecture Components
- Architecture Runtime Views Sharding
- Architecture Runtime Views Availability and Ledger
- Architecture Deployment
- Architecture Crosscutting Concepts
- Security Model
- Architecture Decisions
- Architecture Quality Requirements
- Architecture Risks and Technical Debt
- Enterprise Architecture
3. Data architecture
- Data Architecture
- Data Model Sharding
- Data Model Ledger
- Data Model System Database
- Data Model Analytics
- Data Lifecycle
- Backup Restore and PITR
- Data Security
- Data Quality and Integrity
4. Development
- Building from Source
- Development and Testing
- Repository Layout
- Coding Standards
- Branching and Synchronisation
- Testing Strategy
- Review Process
- Release Process
- Contributing
5. Operations