Skip to main content

Backup, Restore, and PITR

Read this page when you need to know exactly what a backup contains, how a restore can stop at a chosen moment, or why a backup or restore was refused. Kahuna builds backup and point-in-time recovery (PITR) from two existing durability layers.

  • The materialized storage backend, which contains the state that was already flushed to the storage engine
  • The Raft write-ahead log (WAL), which contains ordered and timestamped committed mutations

A full backup captures the materialized state. Incremental backups preserve later WAL entries. A restore combines both and can stop at a selected Hybrid Logical Clock (HLC) timestamp.

storage checkpoint + optional intent frontier + committed WAL segments = state at timestamp T

For configuration and operator-facing behavior, see Backups and Point-in-Time Recovery.

Main Components​

ComponentResponsibility
BackupServiceOwns the driver and catalog, then exposes backup and restore operations through IKahuna.
BackupDriverCreates full checkpoints and incremental WAL segments.
BackupManifestRecords backup identity, such as the type and parent. It also records partition ranges and checksums, and an optional cluster snapshot time.
BackupManifestMacSigns and verifies current-format manifests when a backup MAC key is configured.
BackupCatalogStores manifests and resolves parent chains. It also validates the chain structure.
BackupArtifactVerifierVerifies the manifest schema and the expected file sets before publish or restore. It also checks sizes and checksums, and path safety.
BackupRetentionPlans and applies chain-aware backup retention and orphan artifact sweeps.
IBackupStorageTargetAbstracts manifest storage.
IBackupArtifactStoreAbstracts checkpoint and WAL artifact bytes.
PitrHorizonConverts the configured time window into a protected WAL index for each partition.
LogTimeIndexLocates committed WAL positions by HLC timestamp.
SnapshotCoordinatorSelects one HLC boundary for a coordinated multi-partition backup.
RestoreEngineReplays incremental key/value mutations through a selected timestamp.
IPersistenceBackend.CreateCheckpointProduces the storage-specific base image.

BackupService owns these internal components and exposes them through IKahuna. Kahuna Server maps that surface to REST and gRPC. Kahuna.Client and the TypeScript client provide public client operations, and so does kahuna-cli.

Full Backup Invariant​

Committed state reaches the materialized backend asynchronously.

client write
-> Raft commit
-> in-memory state
-> background persistence queue
-> RocksDB or SQLite

This creates a short interval where a mutation is committed in the WAL but not yet present on disk. BackupDriver must close that gap before taking a checkpoint.

This is the required order.

1. copy live prepared intents and their per-partition applied positions
2. capture M, the last committed WAL index
3. wait until committed writes through M have applied and entered the persistence queue
4. flush pending persistent writes
5. create the backend checkpoint
6. fold the WAL into the prepared-intent frontier at each range end and verify that later records can be reconstructed
7. verify artifact bytes against size and digest records
8. write the backup manifest claiming coverage through M

Capturing M before the flush is essential. If the code flushed first and read M later, a write could commit between those operations. The manifest would claim that write even though it was not included in the checkpoint.

Writes can also commit after M but before the checkpoint. The checkpoint can therefore contain more state than its manifest claims. This is safe because later replay uses revision-keyed upserts and is idempotent.

The apply barrier is equally important. A committed write can be waiting to apply to in-memory state, and the flush can persist only what is already applied. The barrier waits only for committed writes above each partition's persisted application-durability floor, which avoids waiting again for state already durably recovered after restart. BackupApplyBarrierTimeout (--backup-apply-barrier-timeout-seconds, default 30 seconds) bounds the wait. If the barrier times out, capture lists all lagging partitions as retryable PartitionCaptureFailed. A backend that can't flush durably or produce an exact image returns ExactCheckpointUnavailable. Neither publishes a checkpoint that might omit committed data.

Active partitions contribute a PartitionBackupRange from index 1 through their captured committed index. Draining and removed partitions are skipped.

Storage Checkpoints​

Each backend implements CreateCheckpoint(destinationPath, appliedIndex, appliedTime).

  • RocksDB uses the native checkpoint facility. Existing immutable files can be hard-linked when supported by the filesystem.
  • SQLite copies each shard with VACUUM INTO while holding that shard's exclusive lock. Writes to the shard pause during its copy.
  • Memory serializes key/value and lock tables to JSON files. OpenCheckpoint can reopen this representation for restore tests. However, PITR replay applies only key/value mutations. The memory backend is useful for testing. It isn't for durable production recovery.

Each checkpoint includes checkpoint.manifest, which records the applied WAL index and HLC as JSON. The checkpoint is first written to a temporary sibling path and then moved into place so a failed operation does not leave a partial directory that appears complete.

Current manifests record the backup ID and creation time, and the artifact format version. They also record a SHA-256 checksum and a size for each file. The covered partitions and the required artifact names for the backup type are also in the manifest. Legacy manifests are listed as unsupported. They aren't treated as valid current artifacts.

Current manifests also record the configured backup cluster ID and the node that produced the backup. A chain that mixes different non-empty cluster IDs fails validation. When BackupMacKeyFile is configured, Kahuna signs the manifest identity and coverage metadata with HMAC-SHA-256, together with the digest metadata. It verifies the signature before restore.

Full backup artifacts have this shape.

artifacts/
<backup-id>/
checkpoint/
checkpoint.manifest
<backend files>
catalog/
<backup-id>.manifest

Incremental Backups​

An incremental backup begins at parent.ToIndex + 1 for each partition. BackupDriver pages through the WAL and copies only committed entries into partition_<id>.wal segment files.

full: partition 7, indexes 1..100
incremental: partition 7, indexes 101..145
incremental: partition 7, indexes 146..190

Before reading a segment, the driver compares its starting index with the partition's actual WAL compaction floor, both before and after taking its retention hold. A newer application checkpoint alone does not require a full. If required entries were already removed, the public incremental API takes a new full backup. In the returned DTO, ActualKind is Full and RequestedKind is Incremental. SubstitutionReason explains the substitution. Direct facade failures expose NeedsFull. They don't substitute a full backup. Missing indexes in the claimed range fail closed. Holes aren't published.

Topology divergence from a stamped ancestor also requires a new full, for example a membership change or a partition split or merge. The backup service substitutes it the same way. Ancestors that don't have a topology stamp use the legacy compatibility path. This means that a missing stamp doesn't prove that the topology matched.

Each incremental manifest points to its immediate parent. Segment files receive SHA-256 checksums, and manifest writes use a temporary file followed by an atomic move.

Incremental segment files are JSON Lines, one WalSegmentEntry per line. Restore streams them one record at a time. It doesn't load a complete segment into memory. It verifies each segment immediately before replay and stages the exact bytes that will be consumed, which reduces verify-then-use races. Older single-array segment files are also readable for compatibility, but current artifacts use the streaming format.

Chain Validation​

BackupCatalog.ResolveAndValidate walks parent links from the selected backup to its root, reverses the result into chronological order, and validates it before replay.

The chain must follow these rules.

  1. It is not empty.
  2. Its first entry is a full backup.
  3. All later entries are incremental.
  4. Each parent ID matches the previous manifest.
  5. Partition ranges are contiguous: the next FromIndex equals the previous ToIndex + 1.
  6. Parent links do not contain a cycle.

A missing manifest or index gap is an error. Restore does not attempt to produce a partial result from a broken chain.

Under replica placement, a node may host only some partitions. Backup manifests record both the cluster partition set and the partitions covered by that artifact. Before restore or PITR bootstrap, Kahuna validates that each stamped manifest covers all cluster partitions independently. Coverage can't be assembled from the union of different links. If a manifest doesn't cover all partitions, the operation returns RestrictedCoverage. A partial cluster image isn't produced.

Artifact validation is separate from structural chain validation. Before restore trusts bytes, BackupArtifactVerifier checks these properties.

  • Manifest schema and supported format version
  • Missing or unsafe artifact paths, and extra or duplicated paths
  • Size and checksum key-set agreement
  • File length and SHA-256 digest
  • Symlinks or reparse points at the artifact root or below it
  • Segment contents against the partition ranges declared in the manifest

PITR Retention Floor​

Normal Raft checkpointing allows old WAL entries to be compacted. PITR must retain them long enough to connect a base checkpoint to the oldest allowed restore time.

PitrHorizon computes a boundary for each partition.

boundary = now - PitrWindow - BaseSnapshotInterval

LogTimeIndex.LastIndexAtOrBefore finds the largest committed index at or before that HLC boundary. The background writer supplies this protected index to Raft as the minimum retained position.

LogTimeIndex performs binary-search-style probes over WAL indexes. Proposed and rolled-back entries can appear between committed entries. For this reason, each probe pages forward until it finds a committed entry or reaches the tail. Its correctness depends on committed HLC timestamps being monotonically non-decreasing with WAL index.

If no retained committed entry exists at or before the boundary, the floor uses the first retained committed index; if no committed entry remains, it uses the first index that the WAL can contain. The floor is positive under load. The protection isn't cleared immediately after compaction. Log-time searches start at the compaction floor. This protects available history going forward and cannot recover an already-removed prefix.

Point-in-Time Replay​

Restore is an offline operation with two parts.

  1. The caller resolves and validates the chain, then opens the root full checkpoint into the destination backend.
  2. RestoreEngine processes incremental manifests in order and replays their partition segments.

For each segment, entries are ordered by WAL index. Replay decodes key/value entries and applies only those whose transaction commit HLC is at or before the target.

entry.payload.LastModified <= targetTime

The commit HLC is the timestamp that all participants of a committed transaction share. A cut on it includes or excludes a distributed transaction as a unit. The per-partition WAL entry time is not used as the cut axis because different partitions may append the same transaction at different local times.

Commit HLC isn't globally monotonic with WAL index across independent coordinators. For this reason, replay doesn't stop at the first entry beyond the target. It skips entries beyond the target and continues to scan. Mutations are written in batches of 256.

Key/value messages are decoded through the same KeyValueMessageDecoder used by normal log restoration. Writes are upserts keyed by key and revision, making replay restartable after interruption.

Only Raft-committed WAL entries are stored in backup segments. A transaction prepare is itself a committed Raft delta and can appear before the transaction has a commit decision. Replay retains prepares for reconstruction; an unfinished or aborted transaction does not become a visible key/value mutation merely because its prepare is present.

Current PITR image scope

RestoreEngine replays key/value replication messages. Sequence state is stored in the key/value subsystem and is replayed. PITR does not restore lock state, including persistent locks: the as-of checkpoint behind a full backup deletes all lock records from the copy, and replay skips lock WAL entries. After a restore, clients must acquire their locks again. Range metadata is owned by cluster membership and partition-management flows and should be recovered through normal cluster catch-up.

Exact Cuts and Pruned History​

Backends may prune old persisted revisions to bound storage. A point-in-time cut can be exact only if the boundary revision of each key is retained. This revision is needed to reconstruct the value at that cut.

Kahuna persists a monotonic pruned-history floor before deleting the revisions it accounts for. A full backup whose requested cut falls below that floor fails closed with ExactCheckpointUnavailable. If a backend can't read a trustworthy floor, it behaves conservatively. It doesn't assume that all history exists.

No-revision writes don't have a historical boundary to roll back through. If a no-revision key was modified after the requested cut, the exact checkpoint isn't allowed. A value from after the cut isn't silently included.

Restore Staging and Target Safety​

Restore first validates the chain and artifacts. It then copies the full checkpoint into a private staging sibling and verifies the staged copy. Then it opens the destination backend and replays incrementals. After the replay succeeds, it atomically renames the staging directory to the final target path.

BackupService doesn't allow these unsafe targets.

  • Existing non-empty destinations
  • Symlinked destinations or symlinked descendants under a configured restore root
  • Targets outside RestoreRoot when one is configured
  • Targets that overlap the backup directory or live storage directory

Remote restore is refused by default unless RestoreRoot is configured or AllowUnconfinedRemoteRestore is explicitly enabled.

Backup Garbage Collection​

Backup GC has two planners.

  • PlanOrphanSweep finds leftover directories that no valid manifest owns, such as temporary or staging directories.
  • PlanRetention retains the newest chains that satisfy the retention limits: BackupRetentionMaxChains, BackupRetentionMaxAge, BackupRetentionMaxBytes.

Retention works on complete chains. A retained leaf pins its full parent closure, and a deleted chain is removed descendants-first. Delete removes the manifest before artifacts. This means that a crash during GC can't leave a manifest that points at missing files.

GC executes inline after backups and at BackupGcInterval. The public API can execute it on demand or as a dry run. The result shows retention deletions and orphan reclamations, with reclaimed bytes and whether the pass was applied.

Production Hardening​

BackupDir is validated before use. On POSIX, symlinked backup roots and group-writable or world-writable backup roots aren't allowed. Backup files are created with restrictive permissions. Restore target confinement remains separate and is governed by RestoreRoot.

Coordinated backups are owned by the current leader of partition 0 (the system partition). Non-coordinator nodes return NotBackupCoordinator for coordinated backup requests. They don't produce partial cluster backups. If topology or membership changes during a backup, the operation returns TopologyChanged, and no backup is published.

Backup manifests and artifacts are stored through separate contracts. The built-in target stores both under the local backup directory. Other targets can be registered by the host so artifact bytes live in object storage or another external system, with local scratch space used when the storage engine must first create a filesystem checkpoint.

Backup and restore errors returned to remote callers are sanitized and carry an operation ID. The full path and backend exception detail stay in server logs under the same ID.

Coordinated Cluster Timestamp​

WAL indexes are local to partitions. This means that index 100 on one partition is unrelated to index 100 on another. A coordinated backup uses one HLC timestamp T and caps each partition at its last committed entry where Time <= T.

Durable participants share one coordinator-minted commit HLC, but their partition-local append times may differ. The risk during capture is partial materialization: one participant's row can reach the checkpoint before another's, despite sharing a commit timestamp. The cut selection and verification below prevent that.

SnapshotCoordinator asks actor shards for the earliest transaction currently preparing, across live prepared intents and prepared actor intents.

  • If an in-flight commit exists at timestamp M, the coordinator chooses the immediate HLC predecessor of M.
  • If the cluster is quiescent, it chooses the maximum committed HLC found across active partitions.
  • If the cluster is empty, it returns HLCTimestamp.Zero.

Choosing a timestamp before active commits prevents the backup from cutting through a transaction currently preparing. Restore then cuts key/value replay on the shared commit HLC in the transaction payload. This means that an already committed distributed transaction is applied as a unit, or skipped as a unit.

Restore and Cluster Membership​

Restore reconstructs storage state; it does not register the node with a cluster. A restored node must join through the normal membership path and catch up through Raft.

Keeping these operations separate prevents backup artifacts from depending on node identity or the current membership roster. It also allows a recent restore to seed a node before normal replication transfers the remaining WAL entries.

Durable Materialization Replay​

PITR tracks prepared intents from committed preparedintent deltas. It expands by-reference MaterializeIntent records (including legacy logged type 30) and opt-in materializing settlement resolves from those prepares, using the transaction's commit HLC for the target-time filter. Recent duplicate settlement is tolerated. If neither a prepare nor recognized duplicate history can reconstruct a materializing resolve, restore fails closed. It doesn't omit a committed value.

Readers must support these encodings before producers enable them. Disabling an option later does not make older readers safe for existing records. See Durable Settlement.

Durable Intents Across a Full Backup Boundary​

The full's optional intent_frontier.pb supplies prepares whose values would otherwise be absent from incremental replay. A full writes it only if reconstruction state is nonempty, and the manifest covers its size and checksum. It carries the prepared intents live at each partition range end, including their values, plus settled identities used to recognize duplicates. An incremental can contain only a by-reference materialization, or a materializing settlement, for a prepare that occurred in the range of the full; the frontier supplies the value that replay would otherwise lack.

BackupDriver copies live intents and applied positions before recording range ends; IntentFrontier folds the WAL into live and settled reconstruction state at those ends and checks records already present beyond each end, including entries not yet marked committed, with restore's expansion rules. If compaction removed a necessary prepare and neither the copy nor the fold supplies it, publication is refused with retryable CutUnverified. The check is fail-closed. It doesn't permit missing source data to be ignored.

Restore verifies and stages the artifact and seeds prepares and settled identities before segment replay. Recognized duplicate by-reference records after settlement are skipped; unknown references fail closed. Full backups that don't have a frontier also restore. However, they don't get the missing reconstruction data. Older artifact verifiers reject the additional file. For this reason, upgrade restore readers before producers write fulls with a frontier.

For coordinated capture, BackupService opens a prepared-intent observation before choosing a cut. After checkpoint creation, it confirms local application on all covered partitions and verifies the observation's minimum commit timestamp is strictly above the cut. A failed check discards the image. After three attempts, it returns CutUnverified. This check verifies durable prepared-intent transactions. It doesn't verify the actor-only ticket-path staging of all participants. Persistent transactions on the ticket path, such as extend-only transactions, keep pending state on participant actors. The coordinator sees only the actors on its node. See Coordinated Cut for scope and operational behavior.

Composed Captures​

BackupService.Composed assigns partition shares to materialized voters, captures them at an agreed cut, and merges checkpoint images plus intent frontiers into one backup. Learners and removing replicas are not capture sources. All participating nodes need backup configuration and the same storage engine. Share scratch defaults to BackupScratchDir, otherwise system temporary storage; shares are not separately published backups. The driver returns LaggingPartitions when its apply barrier expires; coordinated retries can reassign those (node, partition) pairs to other voters. Only the affected partitions move to another source, and a preferred source is not guaranteed to be caught up. A full backup that isn't composed is local. A composed incremental continues whole-cluster coverage, and it uses a coordinated full backup if necessary. Coverage validation checks each stamped link. It doesn't check their union.

For barrier timeouts and the capture I/O budget, see Capture Cost and Lagging Replicas.