Transaction reads and locks
This is an advanced reference. It defines exactly what a transaction sees when it reads, and exactly when two transactions conflict, including the edge cases around leader failover and background settlement.
Read this page if you need to reason precisely about isolation in your application: for example,
to decide whether a read-then-write pattern is safe when it doesn't use a lock, to choose between latest and
historical reads, to protect a scan with range or prefix locks, or to understand an unexpected
Aborted or MustRetry. If you are new to Kahuna transactions, start with
Transactions.
This page uses these terms.
- Pin: the committed value, or absence, that a transaction records the first time it reads a key. Later operations on that key compare against it.
- Intent: a write intent, a change a transaction has staged but not finished.
- Canonical decision and settlement: the single record that says whether a transaction committed or aborted, and the background step that then installs committed values and removes the intents. See the transaction glossary.
- Anchor: the partition that stores a transaction's canonical decision, chosen from the first persistent key the transaction modifies. Its leader is the anchor leader.
- Head: the newest committed version of a key in the normal key/value data.
- Term: a Raft leadership epoch. It changes each time a partition elects a new leader.
- WriteFence: a range lock that Kahuna takes during a range split or merge. It stops new writes in the range, but shared readers can continue.
These are the main rules.
- A transaction's first read of each key pins that key's committed value. Reads of different keys can observe different moments; they do not share one snapshot.
- With read validation, if a key you read changes before you commit, a later operation or the commit
returns
Aborted. Start a new transaction and repeat the work. - Historical reads at a fixed
ReadTimestampuse a separate, read-only path. - Transaction locks live in the partition leader's memory. A leader change drops them, and the
commit then returns a
Lost lockreason, and the unprotected work isn't committed.
For finalization and retries, see the coordinator guide and transaction lifecycle.
Latest transactional reads
A first transactional GET or EXISTS that doesn't have a read timestamp records an MVCC observation per key.
It pins a committed value or absence, including a committed prepared intent that has not yet settled.
An undecided durable intent requires decision resolution before the read can choose its base.
The routed path can consult the intent's anchor leader when the canonical decision is not local;
an unresolved decision is retryable. It doesn't permit the read to serve an older value.
The transaction reads its staged value or tombstone (delete marker). Otherwise, if the committed revision moves
past its pin, a follow-up point read or write can answer Aborted immediately. This check uses the
full transaction HLC identity, including a nonzero logical counter. It also detects an observed
absence followed by another transaction creating the key. Commit also validates the registered
read dependencies; early detection does not replace final validation.
This example uses optimistic locking.
Reading x and then y for the first time can observe commits from different moments. The pins are
not a shared read timestamp. Transactional scans also record observations, but callers must not
infer predicate stability from per-key pins alone: range locking and finalize validation govern
scan dependencies.
Bounded Waiting Before the First Read
For an optimistic read-modify-write, waiting briefly for another writer can avoid pinning a revision that writer is about to replace. The .NET session overload takes KeyValueIntentWait. Lower-level point-get and batched-probe requests also carry the option, over REST and gRPC, and in inter-node forwarding.
KahunaKeyValue value = await session.GetKeyValue(
"inventory/widget-42",
new KeyValueIntentWait(LimitMs: 500, HoldsLocks: false));
REST point gets use intentWaitMs and intentWaitHoldsLocks; omitting them disables the wait.
This applies to the transaction's first latest read of a key, before it has read or staged that key, if the read doesn't use a fixed read timestamp. The server parks the request and reruns the read when the foreign intent clears or its lease ends. It caps the wait at MaxIntentWaitMs (default 1,000 ms), with at most 64 parked reads per key and 4,096 per key/value actor by default.
At the deadline or a capacity limit, the read proceeds with ordinary read semantics; expiration of the wait is not itself an error or a lock grant. Set HoldsLocks: true if the transaction already has a lock or write intent on any key. A younger reader that has locks doesn't wait for an older holder. This prevents a cyclic wait. An incorrect false can make transactions wait on each other until the deadline. Leadership loss can return MustRetry; waiting does not guarantee the next write commits. Reads that don't use the option behave as before.
Experimental Early Conflict Controls
KeyValueFlags.AbortWhenDoomed makes a transactional set return terminal Aborted when a live foreign intent blocks a key the transaction already read but has not staged. If the flag isn't set, that case returns MustRetry. The caller can then wait for the holder, whose rollback could make the write succeed. Use the flag when restarting the transaction is preferable to waiting.
KeyValueFlags.YieldToOlderReaders makes a younger transactional writer return Aborted before staging when an older transaction read the key but didn't stage it. The older transaction must also have an open coordinator session on the node that leads the key. This is experimental and local to that process: it cannot prioritize readers whose sessions live on another node. It applies to sets and flagged items of a batched delete. The single-key delete API doesn't have this flag. The .NET client's batched-delete conversion currently omits the field. For this reason, flagged deletes require the core or lower-level wire API. A writer that already staged the key bypasses this older-reader check. Unflagged writes retain their existing behavior. kahuna.kv.set.older_reader_yields counts these refusals.
Experimental Read Floor for Embedded Transactions
An embedded caller can set KeyValueTransactionOptions.ReadFloor = true to check that registered latest point reads can share a point in time. When a newly read key cannot be proven to have held its revision since the current floor, Kahuna rechecks the previously read keys outside the transaction. If any revision changed, the new read returns Aborted; otherwise the floor advances. For example, a transaction that read one wallet before a transfer cannot then receive the other wallet's post-transfer revision when the first wallet's revision has changed.
The node starting the transaction must also issue its reads. The option is process-local, absent from client wire options, and experimental. It covers registered point reads and batched probes, excluding scans and the transaction's own staged writes. Remote or missing-key reads force a refresh because they cannot supply a local head-install time. It adds validation work. It doesn't replace commit-time validation or predicate locks, or fixed-timestamp reads. Default transactions continue pinning keys independently.
Committed intents and newer heads
A canonical commit makes a prepared value visible before background settlement installs it in the
backend. A committed delete is absent, including for conditional writes such as SET ... NX.
A subsequent direct mutation can move the committed head beyond that lingering intent. Latest point
reads and scans then use the strictly newer revision, including a newer delete or expired value;
the old intent must not resurrect the key. The same rule applies after a persistent cache miss.
Equality alone does not prove an intent is materialized. EXTEND doesn't change the revision when it changes
expiry. However, each mutation, including a transactional stage, is stamped strictly after the
head it replaces, including a head loaded from another leader or materialized from a coordinator-stamped
durable intent. EXTEND advances LastModified, and replicas order equal-revision heads by that
timestamp. This means that revision equality alone doesn't establish which expiry is current. At equal revision, a head
whose LastModified is strictly later than the intent's commit timestamp supersedes the intent for
latest reads and snapshots at or after that later stamp. The intent remains authoritative for a
snapshot before the later head, or when the head's stamp is equal or older. SET and DELETE advance the revision.
Historical reads select according to commit time. This means that an older intent can be visible at a
snapshot between commits. See durable settlement for the log encodings.
Fixed-timestamp reads
A nonzero ReadTimestamp selects the revision committed at or before that HLC through the as-of
history path. It doesn't create a latest-read MVCC pin. A snapshot before an intent's commit HLC
uses the earlier committed state; at or after it, the intent's canonical decision determines visibility.
An open writer does not by itself block the read. If its staged write or lock was planted at or before the snapshot, the read records that timestamp as the intent's commit floor, serves the earlier committed state, and forces the writer's eventual commit strictly above that floor. A writer already staged above the snapshot can also be skipped. Repeating the read at the same timestamp therefore does not start seeing that writer's later commit.
Once the writer is prepared or its commit probe has claimed the intent, readers cannot push its commit timestamp. A writer whose fixed or not-yet-reported commit timestamp could fall in the snapshot causes a safe-time wait, even when another committed intent could otherwise answer the read. The read polls with delays up to 50 ms; range pages fail retryably if they use up the page retry budget. They don't wait indefinitely.
Clock and flush fences prevent answering from incomplete history. Persisted-history fallback can
answer MustRetry while relevant committed revisions are unflushed. Reads more than 5 seconds ahead
of the serving node's HLC return MustRetry. They aren't served past the clock fence.
Retry the same cluster-minted timestamp after the serving clock catches up. Arbitrary future timestamps
can remain refused. kahuna.kv.snapshot_clock_fence_refused_total counts these refusals. TTL filtering uses the current read time; a fixed timestamp does not freeze expiration.
History suppression (SetNoRevision) and reclaimed revisions also limit historical reads.
Persistent reads below the backend's durable pruned-history floor return SnapshotTooOld (116). This applies to point gets and existence checks, and to scan pages. A scan returns the refused page as an error. It doesn't return a partial result as a success. The floor is backend-wide. This means that a key whose individual history remains can also be refused. Retrying the same timestamp cannot restore pruned history: choose a newer timestamp or report that the historical view is unavailable. This differs from temporary flush/clock fences and transfer coverage refusals, which use MustRetry.
A snapshot hold protects retained history; it does not turn a caller's arbitrary timestamp into a safe cluster cut or recreate already-pruned history.
Statement snapshot reads
The lower-level KeyValueReadMode.StatementSnapshot is for a transaction that wants one fixed timestamp per statement, and it sees its staged writes as usual. All read types that carry this mode use the supplied timestamp for other keys, for example point reads and scans. They do not reuse or check an earlier latest-read pin, and they leave no new pin. A later statement can use a later timestamp and see newer commits.
A registered statement read also records the revision it served for commit-time validation. If a later write changes a registered key, an optimistic commit can abort. A read of the transaction's own staged key is validated as a write instead. This mode requires a nonzero read timestamp. If the timestamp is zero, the request returns InvalidInput. Outside a transaction it behaves like the default mode. All serving nodes must understand the mode before an application relies on it; an older node can serve the default behavior.
The current high-level .NET and TypeScript client methods use the default read mode. StatementSnapshot is available through the lower-level read requests: in-process, gRPC, REST.
Transaction locks
Public REST/gRPC acquisition requires the owning session's coordinator key and a nonempty operation ID; unregistered acquisitions return InvalidInput.
These are key/value transaction locks, separate from the distributed lock subsystem. They are leader-local actor state. They aren't replicated lease records. Quorum-confirmed admission fences stale leaders, but leadership loss purges staging and locks. Locks reduce contention; validation and staging-continuity checks remain necessary for correctness after a leader change.
A point-lock grant first converges the committed base, including a decided but unsettled predecessor
and a parked committed head. Re-acquiring a same-owner point lock follows the same rule. The grant's
base becomes a coordinator read dependency. This means that a loss of exclusion can't authorize a stale computation.
An unresolved predecessor requires a retry/wait; a live foreign lock can answer AlreadyLocked.
This table shows range-lock compatibility for overlapping ranges owned by different transactions.
| Requested / held | Shared | Exclusive | WriteFence |
|---|---|---|---|
| Shared | compatible | conflict | compatible |
| Exclusive | conflict | conflict | conflict |
| WriteFence | compatible | conflict | conflict |
Shared and Exclusive acquisition also check covered foreign write intents. An undecided live
writer blocks acquisition; an in-flight direct replication or unresolved durable decision requires
waiting. A decided intent is different.
Sharedcan be granted before background settlement finishes. Reads resolve the decision.Exclusivewaits for predecessor intent slots to clear. The acquire loop helps settle the named decided keys and retries, reporting at most 4,096 blocking keys per response.WriteFence, used by split/merge quiesce, skips the per-key intent probe and places no per-key intents. It prevents new writes through the write-path range check while allowing Shared readers.
The session's renewal sweep re-acquires range locks through current routing, with bounded concurrency and a deadline. Renewal is best-effort: failures, scheduling delays and failover can leave gaps. It continues through finalize drain until cleanup owns the lock set, and stops after session loss or the reap deadline. Durable prepares and the canonical decision, once replicated, are recovered separately from these in-memory locks.
Failure and regression coverage
Aborted is terminal for that transaction and requires a new transaction. MustRetry is an
unestablished outcome. It doesn't prove a rollback. Retry an unresolved durable finalize with the same
identity; see the coordinator guide for session and operation deduplication limits.
The edge cases on this page are covered by regression tests in Kahuna.Server.Tests.
Detecting Locks Lost During Failover
A lock grant carries the partition and Raft term in which it was issued. The coordinator stores the first grant term for each partition. A later grant or renewal under another term records lost exclusion. It doesn't silently replace that evidence.
Commit checks that each recorded grant routes to the same partition, and that its confirmed leader leads under the grant's term. This check also applies to read-only transactions. An interactive commit returns terminal Aborted and a Lost lock: … reason if the term changed or the range moved. The same result occurs if leadership can't be confirmed after bounded attempts. A self-contained script instead returns MustRetry with the reason so the client can rerun it as a new transaction; real conflicts remain Aborted. Start a new transaction and repeat its reads and computation; reacquiring a lock cannot make the earlier computation safe.
In this example, an interactive session loses its lock in a failover. Its commit is refused, even after it renews the lock.
The proof also fails for a transaction when the leader has recorded that one of its range locks lapsed, even if the term is unchanged. A later renewal or regrant does not erase that record. The actor records the holder in the same turn that first observes the dead lock, before permitting work that relies on its absence. This includes a session-owned range lock exceeding its configured ceiling.
Explicit range-lock leases held by an actor use the node's monotonic elapsed-time clock. A forward wall-clock or HLC jump does not immediately expire those leases. Export for split/merge or listing converts the remaining duration into an HLC deadline; import converts that deadline back into a local monotonic lease. Transfer is therefore sensitive to HLC differences while the lock is in transit. Write-intent expiry and the age ceiling for session-owned locks remain HLC-based.
This is an observed-lapse check. It isn't an apply-time proof of continuous lease ownership. A lease that expires between one-phase bundle validation and apply remains outside it. Lapse records are node-local and retained for the configured session-owned ceiling, or ten minutes when that ceiling is disabled; they are not permanent revocations. Older nodes that don't include grant terms don't supply evidence for their grants. This means that this protection is incomplete during a mixed-version rollout. Upgrade all lock-granting replicas and coordinators before relying on it. Script and interactive transaction paths carry the evidence automatically. This means that application lock calls don't need extra arguments.
With one-phase apply-time validation, the commit bundle carries the anchor partition's grant term and replicas reject a bundle proposed in another term. If that validation isn't enabled, a multi-process transaction carrying lock evidence uses the two-phase path.
| Metric | Meaning |
|---|---|
kahuna.transactions.lock_grant_term_changes | Later grants detected under a different term. |
kahuna.transactions.lost_lock_aborts | Aborts tagged by how the failed lock proof surfaced; detected="lease_lapsed" identifies recorded range-lock lapses. |
kahuna.durable_tx.one_phase_gated_commit_leader_change_rejections | Bundled decisions rejected for mismatched proposal/grant terms. |
Staged Writes and Commit Probes
Each staged write plants a write intent, for any conflict policy. This includes DELETE and EXTEND. Commit checks the exact intent that the first stage used. The intent must own the key and be live, and a lapse must not have been observed. Renewal cannot repair a lapse. A lost intent is a lost-exclusion refusal: interactive sessions return Aborted, while scripts return MustRetry and rerun their computation.
A successful probe claims the intent for commit. After that, its ordinary staged-write lease doesn't expire. Commit or rollback clears it, and the session-owned liveness ceiling bounds abandoned claims. This prevents a slow one-phase append from opening a snapshot-read gap merely because the original lease elapsed. The probe returns the confirmed participant term; one-phase replication checks the anchor's expected term before append, even with apply-time validation disabled. A different term stops the bundle before durable entries exist; a missing term disables bundling and uses the standard flow.
A probe passes a key only on its clean DoesNotExist answer. Other answers, for example WaitingForReplication, prove neither cleanliness nor conflict, and the probe returns MustRetry. Two-phase prepares remain available for an interactive retry under the same identity. A detected conflict aborts as usual; a missing result for a requested key is treated as a broken probe contract and aborts too.
| Metric | Meaning |
|---|---|
kahuna.transactions.lost_staged_intent_aborts | Commit refusals because a staged write lost its original intent. |
kahuna.durable_tx.commit_probes_unproven | Retryable refusals when a returned probe answer didn't establish a result. |
kahuna.durable_tx.one_phase_bundle_term_fence_refusals | One-phase bundles refused before append because the anchor term changed. |
kahuna.kv.staged_chain_break_rollbacks | Transactions with lost-staging detections rolled back or reaped before a commit attempt. |