Mirexa

Wiki Cluster

Moving partitions and rebalancing

How a partition moves to another node without losing an acknowledged write — migration intents, the cutover sequence, pacing, and the rebalancer that decides what should move.

Moving a partition means making another node its primary. Mirexa does it in two layers: a migration intent recorded in the control plane says what should move, and a cutover run by the receiving node does the move — catching up, freezing the old primary briefly, and flipping the directory — so that no acknowledged write is lost by a graceful move. A rebalancer decides which partitions are worth moving; by default it only recommends.

Migration intents

An intent is a goal, not a step counter: move partition P from node S to node T, plus a kind:[1]

Kind What moves How
PRIMARY The primary role T is added as a copy, catches up, cuts over, and S is dropped
SECONDARY One copy T is added and catches up from the primary, then S is dropped. Nothing is frozen and the copy count never drops below where it started
SWAP Primary and an in-sync copy exchange roles T (already in sync) cuts over; the old primary stays on as a copy. Nothing is copied

The intent's step is derived from the directory on every read, never stored, so each step of the orchestration is idempotent and survives a leader change:[2]

Step Meaning Who acts next
NEEDS_REPLICA T holds nothing yet Leader proposes ADD_SECONDARY (starts a seed)
CATCHING_UP T is a copy, not yet in sync T itself, by proposing JOIN_IN_SYNC once level
READY_TO_CUT T is in sync T runs the cutover
DRAINING_SOURCE The flip landed; S still holds the partition Leader proposes REMOVE_SECONDARY
DONE T is primary and S no longer holds the partition Leader completes the intent
UNSATISFIABLE The directory went somewhere the intent cannot reach (partition lost its entry, a third node became primary, or T began leaving before the flip) The leader abandons the intent

Two steps belong to the target and the leader never takes them: only the target knows its own durable position (so only it can say it is caught up), and only the target can verify that its final seed covers the frozen primary. A move is complete only once the source has let go — completing earlier would erase the record of why the partition is moving and strand the source.

An operator starts a primary move with MigratePartition(partition_id, target_node_id); it returns at once with the intent, and progress is a read (ListMigrations). A drain and the rebalancer record intents of their own through the same path, so a planned move is indistinguishable from an operator's. See Operating a cluster.

Abort (AbortMigration, naming the partition and the target) stops future steps and undoes nothing: a seeded copy stays a copy, and a flip past its commit point still lands. Naming the target means an abort cannot kill a different move of the same partition started meanwhile.

MigratePartition always records a primary move. If the target already holds a copy, that copy is consumed: it becomes the primary and the source is dropped, so the partition ends with one copy fewer. The rebalancer avoids this by using a swap instead.

The cutover

When a primary-move or swap target reads READY_TO_CUT, its replica supervisor runs the cutover sequence:[3]

  1. Drain the old primary (Drain RPC, 60 s budget). The old primary shuts the partition's write tap, waits until every write it already admitted has finished dispatching (a barrier, not a pause), and flushes the partition's streams to chunks. It answers with the final per-stream floors and its final durable WAL position. Writes arriving meanwhile are shed with the retryable Overloaded code, so a client re-sends them; nothing was stored for them.
  2. Final seed round — the flushed chunks come across.
  3. Tail until covered (30 s budget) — until the copy's cursor covers the frozen durable position.
  4. Verify coverage — the copy's floors must cover the primary's final floors.
  5. Propose the flip — one ASSIGN_PARTITION making this node primary, carrying the old primary forward as a copy. The new epoch is that entry's log index.
  6. Await the flip in this node's own applied view (15 s budget).

Only the target may drain, and only an in-sync copy: a drain is the first step of a takeover, and only the node that drained may resume.

The proposal is the commit point

Everything before step 5 rolls back cleanly: the target reopens the old primary's tap (Resume) and the directory never changed. From the moment the flip is proposed, rollback is off the table until the outcome is known:

  • A definite refusal (the cluster answered no) rolls back and thaws the old primary.
  • Anything else — a timeout, a lost leader — is ambiguous: the flip may have committed. The partition stays drained and is resolved from the directory, never by blind rollback. Reopening the tap under a flip that did commit would let the old primary acknowledge writes the directory has already moved away from.
  • A flip that committed never reopens the old primary's tap either. The old primary applies the flip whenever its own copy of the directory catches up, and until then it would still accept writes at the old epoch. The tap is bound to the epoch it froze, so it is void if the partition ever comes back to that node at a newer epoch.

Promotion

Replaying the replica log on the new primary is not part of the sequence. The replica supervisor does it whenever it observes "the directory names me primary and a replica log exists", so a crash between flip and replay, or a sequencer that never learned its proposal committed, still promotes on the next pass (every 2 s). A cutover that lands promotes before it returns, so a graceful move is not held for a pass. Until the replay is done the new primary sheds the partition's requests with a 250 ms retry hint.

After a successful move, the old primary's files for the partition are moved aside under quarantine/partition_<id>-epoch_<e>-released, not deleted. A completed migration therefore does not free disk on the source. See Reconciliation.

Pacing

At most cluster.max_concurrent_migrations (default 2) migrations may be seeding at once, cluster-wide. Extra intents wait recorded and visible rather than being refused. The count is taken from the replicated intents, so a new leader inherits it instead of starting a second wave. It is a flat number rather than per-node because the resource protected is the network between nodes. Drains and the replication loop keep at most twice this many of their own moves queued.

cluster.migration_interval (1 s) is how often the leader advances intents.

The rebalancer

The rebalancer decides which partitions should move to even out load. A leader-local loop evaluates every cluster.rebalance_interval (1 m) and keeps the latest plan; the GetRebalancePlan RPC and the mirexa_cluster_rebalance_moves_recommended / ..._bytes_recommended gauges read that plan and its evaluation time. It executes moves only if cluster.rebalance_auto is true (default false) — otherwise the plan is advice an operator acts on with MigratePartition. Turning it on logs a warning at startup.[4]

What it measures

  • Bytes a node can move: the flushed bytes of the partitions it is primary of, from the load reports nodes attach to their heartbeats, intersected with the directory. Copies and leftover files are not counted — a migration moves a primary, so counting load nothing can move would make the planner chase it forever.
  • Write rate, beside bytes: each load report carries a live-write counter, and the leader turns it into records per second over cluster.rebalance_rate_window (5 m; 0 turns rates off). Bytes alone read a stream made large by its history as busy and a small live one as idle.
  • Partition count only breaks ties.

What it refuses

Hazard Guard
Moving data to correct noise cluster.rebalance_threshold (0.20): nothing moves until a node is that far over the ideal, in bytes or in write rate
Oscillation A move is taken only if it strictly evens the cluster out (lowers the sum of each node's squared share of bytes and of write rate). For one load that means a partition smaller than the gap between the two nodes — at the gap they only trade places, past it the hotspot moves
Re-deciding a move still in flight An unlanded migration is counted at its target
Acting on a transient cluster.partition_cooldown (1 h): a partition this leader moved is left alone; leader-local, forgotten on a leadership change
Queuing the whole keyspace cluster.rebalance_max_moves (4) per plan; max_concurrent_migrations bounds what is in flight
Consuming a copy Never a primary move onto a node holding a copy. To reach a node that holds an in-sync copy it plans a swap: the copy becomes primary and the old primary stays a copy, so nothing is consumed or copied

It weighs every move of every source's movable partitions onto every other node and takes the one that evens the cluster out most, so it can still find a move when the lightest node already holds a copy of everything the heaviest could hand it. When a swap and a migration help equally, the swap wins. When no single move helps it stops, even with a node still over the threshold.

"Cannot tell" is not "nothing to do"

The plan refuses to exist while any ONLINE node has not reported its load, or (with rates on) before the leader has watched every node for half the rate window — after every election, join or restart. The RPC answers FailedPrecondition, the auto loop logs a warning, and the recommendation gauges read NaN, never zero, because zero would look like a balanced cluster.

Known limitation: a cutover under heavy load freezes its partition

The cutover freezes first and catches the copy up afterwards. A copy counts as in sync while within its staleness bound even if it is seconds of data behind, so under heavy write load the partition takes no writes for as long as that lag takes to close. Nothing is lost — shed writes are retried and land on the new primary — but the partition is unavailable for writes for the whole freeze.

Measured 2026-10-10 in the shipped binary on one development laptop (TestServerBinary_APartitionTakingAHundredThousandWritesASecondMovesAndLosesNoAckedWrite, three runs):

Acknowledged write rate before the move Longest wait for an acknowledgement
133,000 candles/s 17.3 s
~290,000 candles/s 31.5 – 32.4 s

One run's breakdown: 1.1 s drain, 11.1 s final seed, 18.2 s final tail. The standard remedy — iterative pre-copy, converging while the primary still serves and freezing only for the last delta — is not built; this is a known, accepted limitation. Moves of lightly loaded partitions freeze for well under a second.

References

Source

Tests

  • TestMigrationIntent_TriggersTheCutoverWithNobodyCallingIt, TestCutover_UnderConcurrentWritesNoAckedWriteIsLost, TestCutover_TheOldPrimaryAcksNoWriteBeforeItHasAppliedTheFlip, TestCutover_RollbackRestoresTheOriginalPrimary, TestMigrationAPI_AbortStopsFurtherStepsAndKeepsWhatWasDone, TestDrainer_FlushesOnlyThePartitionItFreezes, TestStartRebalance_TheConfiguredConstraintsReachThePlanner — /cmd/server/cutover_test.go
  • TestDrainTap_IsVoidOnceThePartitionComesBackAtANewerEpoch — /internal/network/fencing_test.go
  • TestReplicaMove_KeepsTheCopyCountAtEveryStep — /internal/cluster/replica_move_test.go
  • TestPlanRebalance_CountsOnlyWhatItCanMOVE, TestPlanRebalance_EvensOutWriteRateBesideBytes, TestPlanRebalance_LooksPastALightestNodeThatCanTakeNothing — /internal/cluster/rebalance_test.go
  • TestRebalancePlan_WaitsForWriteRatesAndThenEvensThemOut, TestRebalanceSweep_IsPacedAndDoesNotPileOnItsOwnUnlandedMoves — /internal/control/migration_test.go
  • TestServerBinary_APartitionTakingAHundredThousandWritesASecondMovesAndLosesNoAckedWrite — /tests/server_binary_cluster_test.go

Further reading

External

  • Christopher Clark et al., "Live Migration of Virtual Machines", NSDI 2005 (iterative pre-copy) — https://www.usenix.org/legacy/event/nsdi05/tech/full_papers/clark/clark.pdf
  • R. L. Graham, "Bounds on Multiprocessing Timing Anomalies", SIAM J. Applied Math., 1969 (longest-processing-time greedy)

  1. MigrationKind in internal/cluster/migration.go. ↩︎

  2. MigrationStep, migrationStep, replicaMoveStep, swapStep in internal/cluster/migration.go. ↩︎

  3. internal/replication/cutover.go header and CutoverOptions. ↩︎

  4. internal/cluster/rebalance.go header; startRebalance in cmd/server/resolver.go; knob defaults in internal/config/config.go. ↩︎