Skip to main content

Transaction Lifecycle

A transaction groups several key/value operations into one attempt to commit or roll back, like a SQL transaction. In Kahuna, those keys can belong to different partitions and be served by different nodes. The transaction coordinator tracks the work and coordinates the outcome.

This page starts with the vocabulary and a worked example, then follows the implementation in more detail. You don't need prior knowledge of Raft or MVCC, or of two-phase commit. If you want to write an application first, start with Transactions and the .NET or TypeScript client examples.

Keep the difference between three states in mind: staged, prepared, committed. A successful write in an open transaction is staged work. It isn't a committed change. Persistent prepare makes that proposed work recoverable. The canonical commit decision determines whether it becomes visible; copying it into the normal backend can happen later.

Basic Concepts​

This table is the shared glossary for the transaction pages.

TermMeaning
NodeA running Kahuna server or embedded host.
PartitionA group of keys with a separate replication and ordering. A transaction can involve several partitions.
Leader and replicaA partition's leader coordinates its persistent writes. Other hosting nodes hold replicas of that partition's replicated state.
CoordinatorThe server component that owns the transaction session and tracks completed operations. It drives commit or rollback. It can be on a different node from the keys.
ParticipantA partition that executes work for the transaction. Modified persistent participants must prepare their changes before the coordinator decides commit.
Transaction handleThe identity the client uses for later operations and finalization. It routes the live session back to its original coordinator node.
Working setThe coordinator's record of confirmed reads and modified keys, with the acquired locks. Commit uses this record.
Read set and write setThe keys the server observed during latest-state reads (used for conflict detection when validation is enabled), and the keys it confirmed as modified by the transaction.
Operation IDStable identity assigned to an interactive operation. A retry can then return the same result, and the mutation isn't applied twice.
MVCCMulti-version concurrency control: keep proposed transaction values separate from committed values, and retain history for historical reads.
Write intentState identifying a transaction that intends to change a key. An unprepared intent is leader-local; a persistent prepared intent is replicated and includes the proposed value.
Revision and write baseA revision is a per-key version number. A write base is the committed revision a proposed change was derived from.
Read dependencyA value or absence the transaction observed and depends on. Validation checks whether competing work invalidated that observation.
Lock and leaseA transaction lock excludes conflicting operations while held. A lease limits how long ownership lasts if it isn't renewed. These locks are leader-local, and renewal can leave gaps.
Prefix and range locksPredicate protection: pessimistic locks over a bucket prefix or an ordered key range that block conflicting mutations, including new keys, while held. They are leader-local; renewal is best-effort and final validation remains necessary.
Historical readA read at a fixed ReadTimestamp that selects retained revisions committed at or before that HLC. Historical sessions cannot write.
ValidationChecking whether the observations and write bases used by the transaction are acceptable. A concurrent change can cause an abort.
Raft and quorumRaft orders replicated entries for a partition. A quorum is the required majority of that partition's voters; writing on one node alone is insufficient for persistent commit.
WALWrite-ahead log: the ordered records used to reconstruct replicated state after failure. Process-loss durability requires a persistent WAL and durable write settings.
HLCHybrid Logical Clock: a timestamp containing physical time and logical ordering information. Transaction identity and commit time have different roles, and an explicitly requested historical read time has a third role.
Canonical decisionThe authoritative transaction record, which moves from Undecided to Commit or Abort. Participants resolve their prepared work from it.
Decision durabilityThe session policy for finalization. Persistent modifications use a canonical transaction record and replicated prepared intents under both BestEffort (the default) and Durable; with explicit DecisionDurability.Durable, ephemeral modified keys also aren't allowed.
Materialization and settlementMaterialization installs committed values into the normal key/value projection. Settlement finishes participant work and removes prepared intents.
Priority admissionOptional per-node start gate that can queue transactions by priority when script or session concurrency ceilings are enabled.

An actor is a local worker that processes one message at a time and owns mutable state for its keys. Actors provide local serialization; Raft provides replicated ordering. An actor and a Raft partition are different units. This means that one actor can handle keys from several partitions.

Walk Through a Persistent Transaction​

Suppose an application transfers 10 units from Alice to Bob. In this example, the accounts are persistent and the keys are on different partitions. Alice starts with 100, and Bob starts with 50. The application checks that Alice has enough funds and stages the two new balances.

StepWhat happensWhat it means
1. BeginKahuna admits the transaction and creates its identity and coordinator session.The client receives a handle for this attempt.
2. ReadParticipants return Alice's 100 and Bob's 50.Latest transactional reads record committed observations per key. They are not automatically a shared transaction-start snapshot.
3. StageThe application writes Alice = 90 and Bob = 60 in the transaction.Later reads in the same transaction can see these values. Other transactions cannot treat these uncommitted writes as committed balances.
4. CloseThe client calls commit. The coordinator stops accepting new work and waits for registered operations. Then it freezes the working set.The attempt cannot accept another write while commit is being retried.
5. Prepare and validateThe persistent participants replicate the proposed values as prepared intents. The coordinator checks staged bases and read dependencies.The proposed values can now survive participant failover, but prepare alone does not mean commit.
6. DecideIf prepare and validation pass, the coordinator establishes the canonical Commit decision. Otherwise it establishes or follows Abort.This record decides the persistent transaction's outcome.
7. SettleCommitted values are materialized and prepared intents are removed.By default, commit can return before this work finishes. Reads resolve remaining intents from the decision.

This diagram shows the usual persistent path. The client can receive a retryable result between steps, and it doesn't know which decision won. Some eligible single-partition transactions combine prepare and decision into one Raft proposal, as described later.

If another transaction changes an observed account, a later point operation or final validation can abort this attempt. After a definite abort, start a new transaction and read both balances again. If commit returns MustRetry, resolve that same attempt first: blindly repeating the transfer in a new transaction could apply it twice.

Persistent writes share the canonical outcome, but reading several keys one by one does not by itself provide a fixed snapshot. For exact read and lock rules, see Transaction Reads and Locks.

Outcome Contract​

The first question after a failed request is whether Kahuna established a final outcome. Use the result to choose the next action.

OutcomeMeaningWhat the caller should do
CommittedThe canonical persistent decision is commit, or the in-memory commit completed.Treat the attempt as successful. Do not repeat its business changes.
RolledBackMandatory rollback cleanup was acknowledged.The attempt is finished. Start a new transaction if needed.
AbortedA definite non-committing outcome, for example a conflict or a confirmed presumed abort.If retrying the business operation, start a new transaction and recompute from new reads.
MustRetryThe outcome is uncertain or transient work remains.Retry the same finalization with the same handle; do not add new operations or assume rollback.
ErroredThe handle is unknown or expired, or its outcome isn't available.Resolve the uncertainty at the application boundary; this result alone does not prove rollback.
InvalidInputThe request or policy combination is invalid.Fix the request.

Aborted is terminal. It can come from stale validation or lost staging, or from a confirmed deadline or presumed abort. Admission rejection surfaces as AdmissionRefused before a transaction starts. Infrastructure failures and unresolved finalization return MustRetry when the outcome cannot yet be established; retry with the same identity.

Lost Exclusion and Retryable Commit Checks​

An interactive transaction that loses a lock or its staging returns terminal Aborted. The loss of the original write intent has the same result. Start a new session and recompute from new reads. A self-contained script maps this lost-exclusion abort to MustRetry, and it preserves the reason. This means that SDK retry handling can rerun the script as a new transaction. Detected data conflicts return Aborted, as usual. This distinction does not turn a general MustRetry or a transport timeout into proof of rollback.

Commit probes also fail closed with MustRetry when they can't prove that a key is clean or conflicting. Leadership or containment can prevent the proof, and so can a peer response. An interactive durable finalize retains prepares for retry under the same transaction identity. Successful staged-intent probes protect the intent through commit, and they don't only renew its ordinary lease, and one-phase bundles fence the anchor leadership term before append. See Staged Writes and Commit Probes for semantics and metrics.

Transaction Shapes​

Kahuna has two transaction shapes.

ShapeDriven byEntry pointTransport
Script transactionThe server executes a submitted scriptTryExecuteTransactionScriptREST, gRPC, embedded
Interactive transactionThe client sends operations one by oneStartTransaction, operations, CommitTransactionREST, gRPC, embedded

Both shapes converge on the same coordinator machinery. A script builds the working set while the script executor executes statements on the server. An interactive session builds the working set across several client round trips.

A bare multi-statement script is treated as one auto-commit transaction. A single-command script can be optimized into the direct command path and does not need the full transaction coordinator.

Entry and Routing​

Routing finds the partition that owns the key and the node that currently leads that partition. The request then reaches the local worker that owns the key's mutable state. This is the path in code.

REST / gRPC / embedded
-> IKahuna
-> KahunaManager
-> KeyValuesManager
-> partition routing
-> actor routing

KeyValuesManager first resolves the key space and data partition. The partition leader is the only node allowed to commit durable state for that partition. If the receiving node is not the leader, the request is forwarded over inter-node communication.

After leader routing, a consistent-hash actor router selects the local KeyValueActor shard that owns the state of the key or range. Actors process one message at a time. This means that the mutable maps of the actor don't need broad shared locking.

Priority Admission​

Admission limits how many transactions may start at once; it does not decide whether their changes commit. Transaction priority admission sits after coordinator-leader routing and before the transaction ID is created. With this order, a queued transaction gets the HLC timestamp of its actual start. It doesn't get a timestamp from before it waited.

The gate is per node and in memory. It has separate orderers for script transactions and interactive sessions. A script uses a slot for bounded server execution. A session uses a slot for as long as the client has the session open.

When a ceiling is disabled, admission is pass-through and only records priority metrics. When a ceiling is enabled, the orderer either grants a slot immediately or parks the caller in a priority queue. A slot is released when a script transaction exits. It is also released when an interactive session ends, for example after finalization or reaping.

Aging raises the scheduling priority of a transaction that has waited, helping it move forward in the ordinary queue. Slots reserved for High and Critical require that original priority; waiting does not make a Background transaction eligible for a reserved slot.

If the wait queue is full or the caller's admission wait expires before starting, admission returns AdmissionRefused. No transaction has started. This means that a retry is safe. However, clients should back off, because the node is shedding load.

Separate Keyspaces​

Choose durability for each operation. It decides where the key's state is stored and what can survive a failure.

DurabilityStorageTransaction implication
EphemeralIn memory onlyAllowed under BestEffort. Explicit DecisionDurability.Durable doesn't allow ephemeral modified keys.
PersistentRaft plus materialized backendEligible for durable-intent two-phase commit

The ephemeral and persistent keyspaces have separate actor routers. A key named session/1 in ephemeral storage is not the same object as session/1 in persistent storage. This separation is important under deferred settlement because persistent prepared intents must not be visible to ephemeral reads or writes for a same-named key.

Staging Before Commit​

Staging stores a proposed write separately from the committed value while the application works. A successful transactional SET means that the operation was accepted into this attempt. It doesn't mean that the transaction committed. The owning KeyValueActor stages two items.

  • an MVCC entry for the transaction ID, which contains the proposed value and its metadata (revision, expiry, state)
  • a write intent with a short lease, which lets other transactions detect an in-progress writer

Pessimistic transactions acquire locks before or during operations to reduce competing work. Optimistic transactions don't take exclusive locks for reads, and they rely on conflict checks. A point lock protects a key; prefix and range locks protect groups of keys and help guard against new keys appearing in a scanned group. They are leader-local. This means that failover can remove them, and validation remains necessary.

Reads in the same transaction can see their own staged MVCC entries. A first latest transactional point read pins its committed value or absence per key; later operations and finalization use those observations for conflict checks. Snapshot reads are different: they read at a fixed historical HLC timestamp and do not create latest-state dependencies.

Non-transactional persistent writes skip transaction staging and go directly through the partition write aggregator.

Staging Continuity and Read Observations​

Latest transactional reads pin committed observations per key, including committed unsettled intents. SET and DELETE advance staged revisions; EXTEND changes expiry, but it doesn't advance the revision. Before granting a point lock, Kahuna resolves committed predecessor work so the grant observes the correct committed base. That base becomes a coordinator read dependency. These checks also apply after failover.

Leadership loss clears actor-local staging and locks, but the active session remains on its original coordinator node. Before durable finalization, the coordinator verifies the confirmed staged revision chain and reads of staged values. A broken chain terminates an interactive session with Aborted and a Lost staging: … reason; a script returns MustRetry so it can rerun with new reads. Process loss can lose the session entirely. Metrics include kahuna.kv.staged_chain_breaks and kahuna.kv.staged_chain_break_aborts.

For visibility rules, see Transaction Reads and Locks. For settlement encodings and upgrade requirements, see Durable Settlement.

Leadership Proof for Transaction Locks​

A successful lock grant includes its partition and Raft term (the leadership epoch). The coordinator retains the first term per partition. A grant or renewal under a different term marks lost exclusion, and commit checks leadership continuity even for a read-only transaction. A changed term, a moved range, and an unconfirmed proof have the same result. An interactive session gets terminal Aborted with Lost lock: …. A self-contained script gets MustRetry. Reacquiring the lock does not repair a computation based on earlier reads.

The leader also remembers a transaction whose range lock it observed lapsing. Commit fails for that transaction, even within an unchanged term and after renewal. Explicit range-lock leases use monotonic elapsed time in the actor. Write intents and session-owned lock ceilings use HLC, and expiry between one-phase validation and apply isn't covered. Older nodes that don't include the term leave their grants unchecked. One-phase bundles with apply-time validation also check the grant term against the proposal term. For an example and the rollout limits, see Detecting Locks Lost During Failover.

Server-Owned Working Set​

The working set is the coordinator's record of what actually succeeded. For example, a successful write to Alice enters the modified-key list; a failed conditional write does not. Clients carry a transaction handle, but they do not provide the final list of keys to commit.

As operations complete, the coordinator records these items.

  • modified keys and durability
  • the locks that the transaction has
  • latest-read observations and validation policy
  • transaction-wide snapshot timestamp policy
  • registered operation IDs and pending operations, with the completed operation responses
  • the session policy, for example the timeout and locking mode, and the lifecycle and finalization state
  • the coordinator key and the durable record anchor, once a persistent modified key establishes one
  • variables and script parameters, for script execution

Only confirmed effects are folded into this state.

  • Successful writes record modified keys. Deletes and extends also count as writes.
  • Successful lock acquisitions of all types record held locks.
  • Explicit releases remove matching lock descriptors.
  • Latest point reads record read observations for cleanup and optional validation.
  • Snapshot reads do not record live read dependencies.

Failed conditional writes and failed lock acquisitions do not become modified keys or held locks.

Operation Registration​

A lost response does not necessarily mean an operation failed. For this reason, interactive operations use a stable operation ID and a digest (a fingerprint of the request inputs). The same request can then be recognized when it is retried. Registration and the finalization fence share the same critical section.

BeginOperation
-> participant execution
-> CompleteOperation with confirmed effects
-> fold effects into TransactionContext

This closes two failure windows. A duplicate operation ID with the same declaration can replay the original response. The same ID with different inputs is rejected. If finalization has already closed the session, new operations cannot slip into the frozen working set.

Participants also keep a bounded in-doubt result cache. If a participant applied a mutation but the completion acknowledgement to the coordinator was lost, a retry with the same operation ID can replay completion, and the mutation isn't applied twice. This cache is a short retry aid. It isn't durable history.

Finalization Fence​

Finalization means finishing the attempt through commit or rollback and cleanup. Its fence closes the session to new work. This means that a late write can't be omitted from a commit that is already in progress. All finalization paths share one finalization slot for each session, including abandoned-session cleanup.

Finalization has these steps, in this order.

  1. Close the session to new operations.
  2. Drain operations registered before the fence.
  3. Freeze an immutable copy of the server-owned working set.
  4. Run commit or rollback from that snapshot.
  5. Perform required cleanup.
  6. Publish the same outcome to the owner and any concurrent callers.
  7. Retain the terminal outcome before removing the active session.

A retryable finalization failure releases the attempt slot, but it does not reopen the session to new reads or writes. The caller should retry commit or rollback with the same handle.

Session Ownership After Leader Changes​

An interactive session remains in memory on the node that began it. It doesn't migrate with the coordinator partition's leadership. A node that has the session can serve it after it steps down. When the current coordinator leader doesn't have the session, it probes peers for the owner before it answers a session request. Examples are commit and rollback, and operation registration.

The probe also happens when a non-leader forwarded the request once, such as a commit sent through a data leader. The forwarding node doesn't probe, and deeper hops answer locally. This limits the search to one round of peer probes. An owner takes an inbound completion for any current leadership. This means that it doesn't send the completion back to the new leader.

This preserves routing to a reachable session owner; it does not replicate the active session or recover it after owner process loss. A participant leadership change can also invalidate transaction locks and abort commit. Retry uncertain finalization with the same handle, as described in Transactions.

Commit Paths​

TransactionCoordinator.TwoPhaseCommit splits the frozen working set by durability.

Working setCommit path
Read-onlyCommit succeeds, and prepare isn't needed
All ephemeralIn-memory prepare and commit
All persistentDurable-intent two-phase commit
Mixed under BestEffortThe ephemeral subset prepares before persistent durable finalization, which then drives ephemeral commit or rollback. The ephemeral subset can be lost on process failure.

DecisionDurability is the session policy. Its default, BestEffort, allows ephemeral work; the name does not mean persistent writes skip durable preparation. Persistent modifications use durable-intent finalization under either decision policy. BestEffort allows mixed work, but does not make the ephemeral subset survive process loss. Explicit Durable mode doesn't allow ephemeral modified keys. The active session itself remains in memory.

Durable-Intent Two-Phase Commit​

Two-phase commit separates prepare (preserve the proposed changes) from decide (choose commit or abort). It prevents a participant from treating its successful prepare as permission to commit independently. The persistent implementation uses two replicated stores.

StoreScopeRole
TransactionRecordStoreAnchor key partitionCanonical record keyed by (TransactionId, Epoch). It moves once from Undecided to Commit or Abort.
PreparedIntentStoreModified key partitionOne live intent per modified key, carrying the proposed value until its decision is resolved.

The first confirmed persistent modified key becomes the record anchor: the key used to locate the partition holding the authoritative decision. The transaction record is internal metadata. It isn't a new user key/value record. A participant manifest lists the participants; its hash identifies the frozen finalize input. The transaction epoch is part of the internal record identity.

The durable finalizer follows this sequence.

  1. Build an immutable finalize input. It contains the transaction identity and manifest hash, the record anchor, the commit timestamp, and the decision deadline. It also contains the participant manifest and the exact prepared intents.
  2. Initialize the canonical record as Undecided and prepare the anchor partition's intents in one atomic ordered proposal when the anchor is also a participant.
  3. Prepare all other participant partitions concurrently.
  4. Retry a prepare in place when it is blocked only by a predecessor's committed-but-unsettled intent.
  5. Validate staged bases and the read set after all prepares are durable.
  6. Confirm staged-base fence verdicts from prepared replicas before committing.
  7. Atomically change the canonical record from Undecided to Commit, but only if all prepares succeeded and validation passed. Otherwise attempt the same conditional change to Abort.
  8. Resolve prepared intents from the record outcome.

The decision record is the point of no return. Once it commits as Commit, Kahuna must not later report a definite abort for that transaction. If a concurrent recovery pass wins the record as Abort, the finalizer returns the record's actual outcome. It doesn't return the outcome that it tried to write. If a participant cannot be resolved immediately, the transaction remains retryable and recovery continues from the canonical record and prepared intents.

A write's base is the committed revision from which it was derived. A lost update would occur if a transaction overwrote a competing change using that outdated base. Validated-base writes get a second check after prepare. The leader checks the current committed base before prepare, each replica remembers the committed head it saw while applying the prepare, and the finalizer asks replicas for those verdicts before writing Commit. A StaleBase verdict aborts the transaction as a conflict. Missing or unreachable verdicts are counted as unattested, and they don't block commit by themselves; the canonical decision still follows the ordered record path.

The replica fence has a per-endpoint lag breaker. A replica can fail to attest within the apply wait again and again, for example during a disk pause or a snapshot install. Kahuna then continues to ask it for instant verdicts, but it stops waiting for its apply path on each commit. When this node leads the participant partition, the breaker also reads Raft follower progress: a replica whose durable frontier is too far behind, or whose WAL is stalled, is treated as lagging immediately and is not restored until it both attests and its frontier is back within the bound. Full-wait probes bring the replica back into the normal fence after sustained recovery. Operators can watch these metrics: kahuna.durable_tx.replica_fence_lag_transitions{state,reason}, kahuna.durable_tx.replica_fence_lagging_replicas, kahuna.durable_tx.replica_fence_lagging_asks{kind}, kahuna.durable_tx.replica_fence_unattested, kahuna.durable_tx.finalize_replica_fence_ms.

Frozen Finalization After a Range Move​

Prepare and record submissions carry the partition and range generation frozen with the transaction. A split between freeze and dispatch makes those stale submissions fail. They aren't appended to the old owner. Retry cannot reuse that frozen route indefinitely: the finalizer concludes the attempt through the record fence at the anchor key's current route, where range handoff moved its canonical record.

Rollback and abandoned-session cleanup use the same current-route fence to release claimed intents on both the moved and unmoved keys. A recorded commit remains authoritative; a split does not turn a committed transaction into an abort. If the reaper can't install the record fence or acknowledge mandatory lock releases, it logs a Warning. The session is then retained for a later sweep. A timeout alone doesn't prove that all intents were released. A caller that receives an uncertain outcome must resolve it with the same handle.

Decision Deadlines​

The decision deadline limits how long an undecided transaction can block recovery. It is separate from the timeout for the entire interactive session. Each durable finalize freezes this deadline.

commit timestamp + clamp(multiplier x max(finalize p99, per-intent p99 x intent count), floor, ceiling)

The p99 is the estimated duration below which 99% of locally observed finalizations fall. clamp limits the computed margin to the range between the configured minimum and maximum values. It gives healthy coordinators enough time to finish under current load, while bounding how long recovery waits before presuming an undecided transaction was abandoned.

A late commit attempt does not force the record to Commit; finalization or recovery drives presumed abort and follows the canonical decision that wins the race. A rising kahuna.durable_tx.late_commit_rejections or kahuna.durable_tx.deadline_expiry_aborts rate usually means the deadline margin is too tight for current latency.

The deadline estimator measures local elapsed duration. It doesn't measure distributed event order. It sizes the margin for the current manifest as well as observed total latency. Samples with at least 64 intents feed the per-intent estimate; until such a sample exists in the window, all samples feed it conservatively. Estimates are usable from the first sample; before any sample, the floor applies. The configured ceiling caps the margin. This means that the margin is adaptive headroom. It doesn't promise that arbitrarily large finalizes finish before their deadline.

Aggregator Role​

The write aggregator is a per-partition batching step before Raft. All durable transaction records enter Raft through it. This lets concurrent durable transactions targeting the same partition share one ReplicateEntries call.

Each aggregator submission has an admission class.

ClassUsed forPurpose
OrdinaryDirect persistent writes, record init, prepareNormal partition write admission
TerminalDecision, materialize, settle, recovery, metadata handoffReserved headroom so ordinary-write bursts cannot starve already-prepared transactions

The anchor partition can submit [TransactionRecord init, PreparedIntent prepare] as one ordered bundle. A batch can mix direct key/value records and durable transaction records, but each submission has a separate completion path.

Durable transaction stores are written only by the ordered Raft apply stream. Proposal completion waits for the ordered apply result for its log index, then resolves the finalizer. If this node loses leadership before that local apply result arrives, or the wait exceeds the proposal timeout, the completion is released as unobserved and the coordinator retries through the current leader. The relevant counters are kahuna.durable_tx.ordered_apply_waits_released_on_leadership_loss, kahuna.durable_tx.ordered_apply_wait_timeouts, kahuna.durable_tx.redundant_applies_skipped.

One-Phase Durable Fast Path​

When a durable transaction's full participant set is the anchor partition, Kahuna can combine the finalization steps into one Raft proposal: record initialization, prepare, read validation, commit decision. That removes the usual two durable barriers for single-partition transactions while keeping the decision replicated. In a single-process embedded node, read-carrying transactions can also bundle the steps in one ordered apply. In a multi-node group, a read-carrying bundle needs apply-time validation.

If another node leads the anchor partition, the coordinator forwards the complete one-phase bundle as a typed durable operation. The receiving leader submits the bundle entries as one atomic scheduler submission under the original range fence. If the remote leader is too old to understand that typed operation, the coordinator uses the standard two-phase flow. It doesn't approximate the result.

For hash-routed schemas, placement groups such as orders|rows/... and orders|by_customer/... help keep row and index dependencies on the same partition. This means that more transactions remain eligible for this path.

With OnePhaseApplyTimeValidation enabled, replicas also check same-partition point-read dependencies and validated write bases at apply time against the committed-head ledger. With this option, read-modify-write transactions remain eligible for the fast path in a multi-node group. Predicate dependencies, such as prefix or range locks, and off-partition read dependencies use two-phase commit as usual.

The main metric is kahuna.durable_tx.one_phase_gate{outcome}.

OutcomeMeaning
enteredThe transaction was eligible for a one-phase attempt.
disabledThe node doesn't have a one-phase commit path.
read_set_beyond_writes, validated_base, or held_lockApply-time validation is off. The bundle can't safely carry that dependency in a multi-process group. The dependency is a read beyond the writes, a validated write base, or a held lock.
predicate_readA prefix or range dependency requires the two-phase path.
off_partition_readA read dependency routes to a different partition than the anchor. Co-locate related hash key spaces with a placement group when the workload should stay single-partition.
non_persistent_readThe dependency doesn't have a persistent committed-head ledger entry.
multi_partition or anchor_off_partitionThe write set cannot be represented by one anchor-partition bundle.

Related counters and histograms include kahuna.durable_tx.one_phase_commits, kahuna.durable_tx.one_phase_fallbacks, kahuna.durable_tx.one_phase_bundle_ms, kahuna.durable_tx.one_phase_pre_bundle_ms. Use them together: a high gate-entered count with low commits means the workload looks eligible at first but is falling back before the bundle commits.

Deferred Settlement​

Commit answers “did the transaction commit?” Settlement finishes installing and cleaning up that committed work. They are separate events. DurableDeferredSettlement defaults to true. With the default, these steps happen.

  1. The finalizer returns Committed as soon as the canonical decision record is durable.
  2. Materialization and intent settlement run on a background task.
  3. Recovery finishes settlement if that background task is lost.

This moves settlement off the commit critical path. Until settlement finishes, a committed value can be in a prepared intent whose local resolution is Pending. Failure or overload can prolong this interval. A pending intent doesn't mean that the canonical decision is undecided.

Kahuna handles that window through intent-aware visibility.

OperationBehavior in the deferred window
Point read or existsResolves the canonical decision; a strictly newer committed head supersedes a lingering intent, including newer tombstones/expired values
Bucket, prefix, or range scanOverlays visible prepared intents, honoring strictly newer heads and resolving foreign decisions when needed
New writeMaterializes a committed predecessor intent before it derives the revision and the conditional checks
New transaction prepareWaits or retries while a predecessor owns the live intent
Snapshot readFails safe and retries when it meets a live foreign intent whose commit timestamp is unknown. It doesn't guess around it.

When the canonical record is not local, the read or write path can route a lookup to the anchor-partition leader and retry with the terminal decision. It does not serve the stale pre-transaction value just because settlement has not materialized yet.

Setting DurableDeferredSettlement to false in embedded or code-level configuration restores synchronous settlement: the finalizer waits for materialization and settlement before returning success.

By default, durable materialization writes MaterializeIntent records. These records carry the intent identity and its metadata, but not the value bytes. Each replica resolves the value from the prepared intent that it already has. This means that the same committed value isn't sent and stored through Raft and the WAL a second time. It reduces serialization and network traffic, and write amplification. Use by-value materialization (DurableMaterializeByReference = false) only during mixed-version upgrades from builds that can't apply MaterializeIntent. Use it until all nodes are upgraded.

One-Phase Apply-Time Validation​

The fast path above needs the same conflict checks as two-phase commit. Apply-time validation means that replicas check the bundled operation when it reaches its position in the committed log. They don't rely only on checks made before submission. The committed-head ledger records the heads used to judge those dependencies.

OnePhaseApplyTimeValidation extends that fast path to read-modify-write and read-carrying durable transactions in multi-process Raft groups. The bundled commit carries its written keys and validated bases, with its same-partition point-read dependencies. Each replica judges the bundle at apply time, in log order, against the committed-head ledger. If another committed write moved a base or read dependency before the bundle applies, the bundled commit is rejected. A lost update isn't committed.

The option is off by default. Enable it only after all nodes in the group use a version that persists the committed-head ledger and applies the extended gate. While it is enabled, StagedBaseFenceRetentionMs and CommittedHeadLedgerMaxEntries must match across the group because they control how long the ledger can prove a base or read has not moved.

Committed-Head Ledger Budget​

The committed-head ledger remembers recently written keys for conflict validation. CommittedHeadLedgerMaxEntries defaults to 500,000 heads per partition in KahunaConfiguration and EmbeddedKahunaOptions. A corresponding server CLI flag isn't available. 0 disables the size budget. Above the budget, a slice raises a persisted time floor and drops older heads, targeting three quarters of the configured budget. Validated prepares or commits from transactions that began before the applicable floor are refused. An evicted head isn't treated as proof that no commit occurred. Heavy writes to distinct keys can therefore shorten the usable validation window and increase transaction restarts.

This is a soft memory bound. The floor is always at least 15 seconds behind the slice's commit watermark. If writes within that span exceed the budget, the ledger remains over budget and logs a warning. A node hosts one ledger slice for each hosted partition. Size the budget for their combined memory and checkpoint copies. Checkpoints and partition transfers carry the floor. kahuna.durable_tx.committed_head_ledger_size_floor_raises and kahuna.durable_tx.committed_head_ledger_over_budget track floor raises and over-budget cases.

With OnePhaseApplyTimeValidation enabled, all replicas must use the same budget and retention horizon, because these are apply-time decisions. A version that doesn't have the size budget behaves as 0; keep upgraded nodes at 0 during that mixed-version rollout, then enable an identical budget after all replicas support it.

Recovery​

Recovery finishes durable work when the original finalizer cannot, for example after a coordinator crash or participant leader change. It reads the authoritative decision. A missing response isn't treated as an abort. PreparedIntentRecoveryActor drives DurableTransactionRecovery for partitions the node currently leads. It wakes periodically and when leadership changes.

Recovery handles each unresolved intent whose recovery deadline is due.

  • record says Commit: materialize the value and settle the intent
  • record says Abort: discard and settle the intent
  • record is Undecided and its deadline hasn't passed: leave it for the live coordinator
  • record is Undecided after its deadline, or missing within the protected canonical-record retention horizon: drive an idempotent presumed abort, then resolve from the record that actually won
  • a matching completion receipt: recognize a participant that already committed

Recovery and request-path finalization can run concurrently. All finalization steps are idempotent. A repeat for the same identity doesn't create a second independent transaction or reverse a terminal decision. Recovery doesn't guess a terminal decision while the canonical record is undecided and its deadline hasn't passed.

Missing Canonical Records Beyond Retention​

A missing canonical record is not always proof of abort. Beyond the protected outcome-retention horizon, recovery requires a matching completion receipt as commit proof. If it doesn't find a receipt, it retains the intent. It doesn't guess that a reclaimed record means abort. The horizon uses DurableRecordRetentionFloor when retention budgets are enabled; the floor is raised to at least the decision-deadline ceiling plus two maintenance intervals. Undecided records and unresolved intents are not evicted to admit new work.

Completion Receipts and Range Movement​

A completion receipt is evidence that a participant already applied a committed change. When a committed intent materializes, Kahuna records this receipt with the key/value commit. A duplicate commit or recovery re-drive can use the receipt to prove that the participant already applied the transaction after the original MVCC state is gone.

The receipt identity includes the transaction and key, with the durability. This means that a persistent receipt can't satisfy an ephemeral operation for the same logical key. Receipts are restored from the committed key/value log and included in snapshots before WAL retention advances.

Range split and merge transfer the durable transaction state to the destination partition before cutover. This state includes records and prepared intents, with completion receipts. The transfer is replicated on the destination partition's Raft log and gates cutover. If the handoff can't be made durable, cutover is aborted, and recovery state isn't put at risk. Range-lock transfer is separate and best-effort because range locks are in-memory leader state.

WAL and Persistence​

The Raft WAL records the ordered changes used for recovery. The backend contains the materialized key/value rows used for normal storage and reads. These layers are separate. A commit doesn't need to wait for the backend to flush all rows. This is the usual persistent sequence.

  1. The partition leader proposes an ordered batch.
  2. A quorum persists it.
  3. The committed entries apply to the in-memory state machines.
  4. The background writer later flushes materialized state to the configured storage engine.

Backend persistence is not the commit point. The materialized store means that a node doesn't need to replay all logs from the start. It also lets the node serve evicted persistent entries after reload.

These storage optimizations affect how WAL writes are grouped and acknowledged.

  • Group commit can coalesce several partitions into one storage flush (fsync).
  • Single-fsync commit removes one disk flush from the caller's wait. If it isn't enabled, an auto-commit proposal waits for two flushes in a row: the proposal, then a "committed" marker. With it, Kahuna acknowledges once a quorum has durably stored the proposal, which is already the commit point, and writes the committed marker later.

Bounds and Backpressure​

Bounds limit memory and queued work. Backpressure means that new work is refused or delayed when those limits are reached. Unlimited requests aren't admitted. Application authors should keep transactions short and handle admission/retry responses; operators can use these settings to diagnose capacity pressure.

These transaction bounds are important.

Setting or limitDefaultPurpose
TransactionOutcomeRetentionMax10000Retained terminal outcome count for duplicate finalize idempotency. A non-positive value disables best-effort outcome retention.
TransactionOutcomeRetentionTtl5 minutesAge window for terminal outcomes and completed durable decisions. A non-positive value disables age-based removal.
DurableDecisionOutstandingMax100000Hard cap on outstanding undecided canonical records admitted by a node. Completed records do not count against this budget.
DurableRecordRetentionMax200000Count budget for resident terminal durable records per node before older records are reclaimed early. 0 disables the count budget.
DurableRecordRetentionMaxBytes268435456Estimated heap-byte budget for terminal durable records plus completion receipts. 0 disables the byte budget.
DurableRecordRetentionHeapPressure0.85Last-resort managed-heap pressure threshold that triggers aggressive reclamation of terminal records older than the retention floor. 0 disables it.
DurableRecordRetentionFloor90 secondsMinimum terminal-record age protected from early reclamation by the retention budgets.
DurableMaintenanceInterval5 secondsTick interval for prepared-intent recovery and durable retention sweeps, clamped to CollectionInterval; nonpositive uses that interval.
DurablePreparedIntentMaxCount500000Resident prepared-intent count bound. A non-positive value disables the count bound.
DurablePreparedIntentMaxBytes1073741824Resident prepared-intent value-byte bound. A non-positive value disables the byte bound.
DurableDeferredSettlementtrueExecutes durable materialization and settlement after the decision record is durable and success can be returned. false awaits settlement inline.
DurableMaterializeOnResolvefalseInstalls values from local prepared intents during settlement apply; enable only after all readers support it. See Durable Settlement.
DurableMaterializeByReferencetrueUses value-free MaterializeIntent records after commit. Set false during mixed-version rollouts from builds that cannot apply that record.
SessionOwnedIntentCeilingMs0Maximum age for orphaned session-owned write intents and no-expiry range locks. 0 derives the ceiling from the transaction timeout and reaper grace, with the participant-effect TTL.
OnePhaseApplyTimeValidationfalseEmbedded/code-level option that allows eligible bundled durable commits in multi-process Raft groups to validate reads and bases at apply time. Enable only after all nodes support the committed-head ledger.
DurableDecisionDeadlineFloorMs5000Lower clamp for the durable decision-deadline margin.
DurableDecisionDeadlineCeilingMs60000Upper clamp for the durable decision-deadline margin.
DurableDecisionDeadlineMultiplier4Multiplier applied to the larger of total finalize p99 and per-intent p99 × manifest size, before clamping the decision-deadline margin.
CollectionInterval60 secondsTransaction reaper and range-lock renewal cadence, and upper bound for the durable maintenance cadence.
MaxTransactionTimeout300000 msUpper bound for admitted interactive session lifetime and script transaction timeout.
MaxConcurrentTransactions0Script transaction concurrency ceiling. 0 disables the script gate.
MaxConcurrentSessions0Interactive session concurrency ceiling. 0 disables the session gate.
TransactionPriorityReservedSlots0Slots reserved for High and Critical work when a gate is enabled.
TransactionPriorityAgingThreshold1000 msWait time per effective priority promotion. 0 disables aging.
TransactionPriorityMaxQueued4096Waiters allowed per gate before admission returns AdmissionRefused. 0 makes the queue unbounded.
DefaultAdmissionWaitMs5000Admission wait used when the caller does not specify one.
MaxAdmissionWaitMs30000Maximum admission wait allowed by the server.
Pending operations per session4096Safety bound for in-flight registered operations in one transaction. Additional registrations receive a retryable capacity rejection.
Total operations per session65536Safety bound for retained operation records in one transaction. Exceeding it is terminal for that session.
Participant in-doubt results8192 per nodeBounded cache for acknowledgement-loss recovery.
Participant finalize retries20 retries, 250 ms apartRetry window used while committing or rolling back prepared participants.

Durable admission is bounded by DurableDecisionOutstandingMax, independently of TransactionOutcomeRetentionMax. A new durable transaction is refused before prepare when the outstanding-record budget is full. Recovery state isn't evicted to make room.

DurableDecisionDeadlineFloorMs and DurableDecisionDeadlineCeilingMs are embedded/runtime options. The server CLI exposes durable record-retention budgets and the durable maintenance interval, while DurableDecisionDeadlineMultiplier remains a code-level configuration field.

These aggregator bounds are important.

Setting or limitPurpose
KeyValueWriteMaxBatchItems / KeyValueWriteMaxBatchBytesSubmissions and payload selected for one partition Raft call; one bundle can contain multiple entries
KeyValueWriteMaxQueuedItemsPerPartition / KeyValueWriteMaxQueuedBytesPerPartitionPer-partition admitted work
KeyValueWriteMaxQueuedItemsGlobal / KeyValueWriteMaxQueuedBytesGlobalNode-wide ordinary admitted work
KeyValueWriteTerminalReserveItemsPerPartition / KeyValueWriteTerminalReserveBytesPerPartitionPer-partition terminal reserve
KeyValueWriteTerminalReserveItemsGlobal / KeyValueWriteTerminalReserveBytesGlobalNode-wide terminal reserve
KeyValueWriteMaxOperationBytesHard ceiling for one admitted serialized write
KeyValueWriteBatchExecutionTimeoutMsMaximum Raft round-trip time for one aggregator batch

Where to Go Next​

For application development, use Transactions for API examples and Transaction Reads and Locks for read visibility and lock behavior. For operations or implementation work, continue with Durable Settlement and WAL and Persistence. Also see Snapshot Installation and Raft Recovery.