Skip to main content

Replication and Recovery

Use this page when you diagnose lagging followers or retries during failover, or replica moves. It explains how a persistent write becomes committed and how a restarted node rebuilds its state. It also explains how requests reach the right node, and what happens when leadership or placement changes.

Kahuna uses Raft replication to make persistent mutations durable and ordered. The server wires Raft events to Kahuna through ReplicationService.

Startup Wiring​

On startup, ReplicationService subscribes Kahuna to these Raft events.

  • OnLogRestored
  • OnReplicationReceived
  • OnReplicationError

Then it joins the Raft cluster. Embedded nodes perform equivalent wiring in EmbeddedKahunaNode.

Commit Path​

A persistent mutation follows these steps.

  1. The leader actor validates the request.
  2. A proposal is created for the mutation.
  3. The proposal is serialized as a Raft log entry.
  4. Raft replicates the entry to the partition group.
  5. Once committed, Raft raises OnReplicationReceived.
  6. Kahuna's replicator applies the committed entry to the in-memory state.
  7. The materialized state is queued for background persistence.

Request Flow shows this path as a sequence diagram, from the receiving node through quorum commit to background persistence.

Acceptance by the leader actor alone does not make a mutation durable. The committed Raft log is the source of truth for ordering and durability.

Log Types​

Kahuna categorizes replicated logs with simple type names.

TypeMeaning
lockLock state mutation.
kvKey/value state mutation.
rangemapKey-range descriptor map, replicated on partition 0 (the system partition).
snapshotfloorSnapshot-hold floor registry, replicated on partition 0.
coorddecisionLegacy coordinator-decision delta.
txnrecordCanonical transaction-record delta on the anchor partition.
preparedintentParticipant prepared-intent and settlement delta.
receiptCompletion receipt handoff for range split/merge movement. In steady state, receipts ride key/value commits.

ReplicationSerializer serializes these messages with protobuf. Larger values use recyclable memory streams to reduce allocation pressure.

Restore Path​

During recovery, Raft replays committed logs that are newer than the latest checkpoint. Kahuna receives those logs through OnLogRestored.

The restore path has these steps.

  1. Raft loads logs from its write-ahead log (WAL).
  2. Kahuna routes each log by replication type.
  3. The handler for each log type rebuilds its state.
  4. Materialized persistence provides checkpointed baseline data.
  5. New committed logs continue through the normal replication path.

Inter-Node Forwarding​

Clients may contact any node. If the receiving node is not the leader for a resource's partition, Kahuna forwards the operation through IInterNodeCommunication.

The production implementation uses gRPC and shared batchers. This lets Kahuna combine related inter-node requests and reduce per-operation network overhead.

The gRPC batchers can coalesce independent server-to-server envelopes onto one stream message. Each inner request retains its ID and type, and its hop count and response. Order-sensitive maintenance and placement operations are serialized per stream. This means that a later maintenance request can't overtake an earlier one from the same peer.

Forwarded durable transaction operations start on arrival, for example bundles and decisions. They don't wait on that ordered lane. They can reach the partition write aggregator together, and its admission controls backpressure. Their order is governed by the transaction protocol, for example transaction identities and term fences. Placement operations use the lane as before. kahuna.internode.ordered_lane_wait_ms measures the remaining ordered placement work, and it doesn't have durable-request tags.

Forwarded key/value and lock requests include a hop count. If leadership or placement metadata is briefly inconsistent, the hop budget turns a potential forwarding loop into MustRetry, letting the client retry after the cluster view converges.

After a shared inter-node stream fails, reopening backs off per peer from 100 ms, doubling to a maximum of 2 seconds. Requests arriving during backoff receive their operation's retryable unavailable response; the batcher does not open a stream for each request. A successful write resets backoff. Logs show the failure episode at Warning, summarize ongoing failures at most every 10 seconds, and report recovery at Information. The Kahuna meter exposes these counters, tagged by peer: kahuna.internode.stream_opens_total, kahuna.internode.stream_failures_total, kahuna.internode.requests_refused_by_backoff_total.

Grouped commit probes also tolerate a stale leader hint: a follower resolves the actual leaders for keys it cannot answer and forwards one grouped probe per leader. This avoids repeatedly probing the same follower; it does not remove retryable outcomes while leadership is unavailable.

With replica placement, the receiving node may also be a non-host for the target partition. It takes the client request as usual and resolves the partition's hosting replicas. It then forwards the request to a node that can serve the partition. Hosting changes can race with requests. This means that callers can see retryable responses while a partition is moving.

Replica Placement​

Kahuna's default placement is full replication: all voters host all partitions. A positive replication factor stores each data partition on an explicit replica set.

The partition map records these items.

  • The partition lifecycle state
  • The partition generation
  • The effective replication factor
  • Replica endpoints
  • Replica roles, for example Voter and Learner

Replica changes are committed through partition 0 before data movement proceeds. A new replica starts as a learner, which receives data but does not vote. It catches up from the log or a partition snapshot, and is promoted only after it is close enough to the leader for the configured stable window. Removals are staged. This means that a partition has a safe voter set while the old host is drained and purged.

Catch-up is bounded on both the streaming and buffering paths. Leaders cap outbound bytes per peer, cap backfill (resending missed log entries to a lagging follower) by entry count and bytes, and retry lagging followers through heartbeat/backfill. Snapshot rescue has a convergence breaker. Repeated rescue cycles can leave a follower below the compaction floor (the oldest log entry that the leader has retained). In this case, the leader pauses aggressive rescue for that peer, but it sends periodic probes. A recovered follower can then be seeded later. Small snapshot exports can be cached for retry so a failed transfer does not immediately rebuild the same snapshot.

Compaction also accounts for peers that go silent. A live follower that recently needed snapshot rescue can hold the compaction floor within a configured lag budget so normal compaction does not immediately put it below the floor again. A peer that stops answering limits compaction only for the silent-peer retention window; after that, it no longer prevents compaction and must restart from a snapshot when it comes back.

The placement controller executes on the partition 0 leader. It repairs under-replicated partitions before it removes extra replicas. After that, it balances replica counts across nodes. Per-partition overrides change the target; the controller performs the actual movement on later passes.

These placement metrics are useful.

MetricMeaning
kahuna.placement.replicas_gainedReplica records added to the local node.
kahuna.placement.replicas_lostReplica records removed from the local node.
kahuna.placement.forwards_resolvedRequests forwarded successfully using placement information.
kahuna.placement.forwards_unresolvedForwarding attempts that could not resolve a valid host.
kahuna.placement.leader_hint_hitsForwarding used a known partition leader hint.
kahuna.placement.leader_hint_missesForwarding had to proceed, and a usable leader hint wasn't available.

Replica Placement Internals​

These details explain how the placement controller converges. The operator procedure is in Replication Factor and Replica Placement.

Legacy Full-Replication Conversion​

Kahuna, pinned to Kommander 1.13.3, can convert legacy full-replication partitions when a positive effective replication factor and the placement rebalancer are enabled. Each eligible active partition with an empty replica set first receives an explicit set of all committed roster voters. This preserves its existing quorum; it does not immediately replace that quorum with an arbitrary factor-sized subset. Normal placement trims then remove surplus replicas one step at a time toward the target. Conversion is bounded by MaxReplicaMovesPerPass (--raft-max-replica-moves-per-pass), and a failed map commit is retried on a later pass.

With rebalancing disabled the partitions stay fully replicated and a warning explains why conversion has not begun. Full replication with an effective factor of zero remains an intentional mode. It isn't a pending migration.

The leader of partition 0 exposes raft.placement.ranges_awaiting_initial and the counter raft.placement.initial_assignments_total on the Kommander meter. Embedded hosts can inspect node.Raft.GetPartitionsAwaitingPlacement(). A zero pending count means that assignment finished. It doesn't mean that all later trimming and movement finished.

Leader Removal and Rebalancing​

Removing a partition's leader replica requires a confirmed handoff to another replica before marking it Removing. If the requesting node is not that partition's leader, it sends a transfer suggestion and polls the confirmed leader within a bound. An unconfirmed handoff returns LeadershipNotConfirmed, leaving removal for a later placement pass. A replica excluded by the committed map is also treated as a vacated leader for election gating, even if its process remains alive.

Trim selection prioritizes replica load and zone placement; leadership only breaks ties among equally loaded candidates. A balancing add is planned only if its predicted follow-up trim improves load distribution. This prevents the repeated addition and removal of the same replica. These are convergence safeguards. They aren't an exact balancing deadline.

Learner Promotion Diagnostics​

Placement uses the fresh load-report incarnations of restarted nodes, even when their report version counters reset. If the gossiped leader hint is absent or dead, learner-lag checks can resolve a quorum-confirmed leader before deciding promotion readiness. These are recovery paths. They don't permit the promotion of an unconfirmed learner.

--raft-learner-promotion-stall-warning-after (30,000 ms) logs the last failed check when a placement-added learner can't be promoted. It is diagnostic only; it does not relax the lag or stability requirements. A non-member range leader is reported as a stall condition. After a failed drain is confirmed rolled back to Voter, the node's departure latch is released so a later eviction can trigger automatic rejoin. A removal that can commit later retains the latch.

Leave Requests and Elections​

Requesting leave does not immediately stop the node from participating in elections: it remains eligible while membership removal is being committed. This means that it can help elect the partition 0 leader needed to finish that removal. A refused or failed API leave leaves the node campaigning while it remains a member. After removal commits, candidacy is suppressed.

An eviction during a leave request returns Evicted. It isn't a confirmed decommission. The node admits itself again, and the caller must retry after rejoin. The committed roster records whether a departure was an eviction or a requested removal. This means that an eviction doesn't suppress rejoin permanently. See Replica Placement for the operational response.

Automatic rejoin is suppressed while departure remains in force. A refusal that didn't commit a change releases that suppression, and so does a confirmed rollback of a decommission drain to Voter. A newer committed roster naming the node Voter also confirms rollback when its acknowledgement was lost. A timed-out removal that doesn't have such proof can commit later. For this reason, suppression remains. Verify committed membership after an uncertain response and finish decommissioning explicitly. Process shutdown follows a separate teardown path and suppresses candidacy after its removal attempt ends; disposal alone is not evidence that membership removal committed.

Leader Changes​

Raft handles leader election for each partition. A leader change has these effects.

  • Only the current leader can commit new writes for that partition
  • Followers catch up from the leader's log
  • Committed entries remain ordered
  • Uncommitted proposals may need to be retried
  • The node that lost leadership discards the belief-only state from the old leadership term. This state includes staged transactional writes and unprepared write intents, and transactional locks in all modes

Clients can see retry or abort responses when leadership changes race with an operation.

For durable transaction decisions, the node that becomes leader for the anchor partition is responsible for continuing recovery of any outstanding decision records it now owns.

Leadership Transfer​

A leadership transfer, such as one suggested by the leader balancer, is best-effort. Winning an election is not enough for the target to serve: it must drain committed log entries and pass the leadership barrier, and a contained or incomplete target can relinquish immediately. Kommander (since 1.9.7; Kahuna pins 1.13.3) reads the WAL on each promotion-drain attempt. This means that a readable entry isn't delayed only because its completion callback is queued behind promotion. Entries that remain unreadable prevent promotion as before.

Apply Fingerprints​

Each node maintains a small apply fingerprint for each partition.

FieldMeaning
Applied key/value log idHighest key/value Raft log id applied on this node for the partition.
Committed-head ledger entriesNumber of committed key heads tracked for transactional read validation on this partition.
Live intentsPrepared intents currently held by the node.

At leadership changes, Kahuna logs the local fingerprint. It also exposes gauges tagged by partition.

MetricMeaning
kahuna.keyvalues.applied_log_idHighest key/value log id applied on this node for the partition.
kahuna.durable_tx.committed_head_ledger_entriesCommitted-head ledger entries held on this node for the partition.

Each replica schedules peer comparisons on leadership changes, retrying while fingerprints are not comparable. Equal applied log ids with different committed-head or intent counts indicate apply drift. Kahuna logs this and increments kahuna.keyvalues.apply_divergence_detected. These are count-based fingerprints. They aren't value hashes. Equal counts don't prove equal values, and they don't detect all divergence.

Range splitting performs the same check before copying from the source partition. If another replica has more committed heads than the source leader at the same applied log id, the split is refused with SourceStateIncomplete and kahuna.range.split.incomplete_source_refusals increments. The trigger can retry on a later pass after leadership or replica state converges.

Containment​

A conclusive comparison showing local incompleteness is checked again before containment. The node gates local partition reads and mutations with MustRetry. It gives leadership to the fullest peer or steps down, and it withholds candidacy. It then requests reseeding. Repair requests repeat on a one-minute cadence. Successful whole-partition installation clears containment. The gate is in memory; this is not a subsecond recovery guarantee or proof of correctness for undetected equal-count divergence.

For transfer contents and partial-install behavior, see Snapshot Installation and Raft Recovery.

Missing By-Reference Values​

Containment also follows verified missing reconstruction sources. Live apply checks a missing prepared intent against queued writes and backend rows before concluding that a by-reference value is missing. The first proven live miss gates the partition and withholds candidacy immediately; relinquish/reseed work continues asynchronously. Restart replay similarly gates unresolved results before campaigning. Benign duplicates with sufficient local state and keys now owned by another partition do not imply a missing value.

For source selection and metrics, see restart replay and missing-value alarms.