Transactions
A transaction groups several reads and writes so they take effect together or not at all, like BEGIN ... COMMIT in a SQL database. Use one when a single business change touches more than one key, or when a write depends on a value you read first.
For example, a job dispatcher assigns job jobs/1042 to worker w-7 only if the job is pending and the worker has fewer than three jobs. The dispatcher must read two keys and check both, and then write both back. If it doesn't use a transaction, three things can go wrong.
- The dispatcher crashes after it marks the job as assigned but before it updates the worker's job count. The job and the worker then disagree (a partial update).
- Two dispatchers both read
pendingand assign the same job to different workers, and one assignment silently overwrites the other (a lost update). - Another dispatcher assigns jobs while you read. You then see the job from before its change and the worker's count from after it (read skew).
In a Kahuna transaction, both writes commit together or neither does. With read validation or locks, a conflicting change by another client makes the transaction abort, and you retry it. A wrong result isn't produced. This guarantee applies even when the keys are on different partitions and nodes.
A Kahuna transaction differs from a SQL transaction in three ways.
- You choose pessimistic or optimistic locking.
- A normal read pins the committed value that it first saw for each key. It doesn't read all keys from one snapshot taken at
BEGIN. - A commit can return
MustRetry, an unknown outcome that you resolve by retrying the same commit.
Kahuna offers two ways to run a transaction.
- Scripts: send the complete read-check-write logic to the cluster as one request. This is the simplest and fastest option when the logic fits in Kahuna Script.
- Interactive transactions: open a session from the .NET or TypeScript client, run operations one by one with application code in between, and then commit or roll back.
You do not need a transaction for a single-key update. A single SET, or a compare-and-set when the new value depends on the old one, is cheaper.
Client sessions and script transactions default to separate limits of 20,000 written keys and 20,000 acquired locks. See Key/Value Request Limits for counting and refusal behavior.
How Kahuna Executes Transactions
Kahuna coordinates reads and writes across partition leaders. For persistent keys, each partition stages the transaction's changes as replicated write intents, and one commit-or-abort record (the canonical decision) decides the outcome for all of them. Once that record says commit, the new values are visible, even if background cleanup (settlement) has not yet installed them as normal values. Ephemeral values, and transactions that mix persistent and ephemeral keys, do not have the same guarantees when a process is lost.
For interactive transactions, Kahuna uses a server-side transaction coordinator. The client has a session handle, but the server owns the authoritative working set. The working set contains confirmed reads and writes, with locks and cleanup state. Commit and rollback use that server-owned state. The client doesn't send a final list of touched keys.
What Isolation You Get
A Kahuna transaction doesn't read all keys from one snapshot taken at BEGIN. What it sees, and which conflicts it catches, depend on how it reads and on its options.
| Reads and options | What you get |
|---|---|
| Latest reads (the default) | The first read of each key pins the committed value it sees, or that the key is absent. Later reads of that key in the same transaction compare against the pin. Reads of different keys can observe different moments. |
pessimistic locking (the default) | The transaction locks each key before it reads or writes it; a script takes its locks up front. Another transaction cannot change a locked key until this one commits or rolls back. |
optimistic locking, or readValidation: trackAndValidate | At commit, Kahuna checks again each key that the transaction read. If a key changed, or another transaction has a concurrent write intent on it, the transaction aborts. It doesn't commit against a stale read. This prevents lost updates and write skew. |
Bucket and range reads under pessimistic locking | A prefix or range lock blocks writes in the bucket or range, including inserts and deletes. This means that keys can't appear in or disappear from what you already read (phantoms). |
Fixed ReadTimestamp, or snapshot in a script | Default fixed-timestamp reads return committed state at or before one past timestamp, within retained history. They don't register read validation. A script with snapshot is read-only. The lower-level StatementSnapshot read mode has different transactional behavior; see Statement snapshot reads. |
Transaction locks, including prefix and range locks, are stored in the memory of the partition leader. A leader change drops them. The commit then fails. It doesn't commit work that the lock no longer protected. For more information, see Retry Outcomes.
For the exact visibility rules and lock compatibility, see Transaction Reads and Locks. That page also covers failover limits.
Core Concepts
| Concept | Description |
|---|---|
| Session | One transaction attempt. A script is one session on the server. An interactive transaction is a session that you open from a client. Its handle sends later operations to the server that owns the session, including the commit or rollback. |
| Locking mode | pessimistic (the default) takes locks as the transaction reads and writes. optimistic doesn't take exclusive locks for reads, and it checks for conflicts at commit. See Locking Modes. |
| Retry outcome | A transaction that does not commit tells you how to retry. Aborted means start a new transaction. MustRetry means the outcome is not known yet: retry the same commit or rollback with the same handle. See Retry Outcomes. |
The internal terms on the architecture and internals pages, such as coordinator and write intent, are defined in the transaction glossary.
Transaction API
A script with several statements, like the one below, is normally a transaction, even if it doesn't have begin. An eligible single-command script executes directly, and a transaction isn't opened.
set "services/auth" "localhost:8081"
set "services/matchmaking" "localhost:8082"
set "services/inventory" "localhost:8083"
Basic Usage
This script is the job assignment from the introduction. Values read with get arrive as strings. For this reason, the script converts the job count with to_int.
begin
let job = get "jobs/1042"
let load = get "workers/w-7"
if job == "pending" && to_int(load) < 3 then
set "jobs/1042" "w-7"
set "workers/w-7" to_int(load) + 1
end
commit
end
Example: Conditional Write Based on a Read
begin
let config = get "settings/feature-x"
if config == "enabled" then
set "logs/feature-x" "used"
end
commit
end
The transaction pins the committed value of settings/feature-x from its first read. With validation enabled, a competing change can abort a later operation or commit; retry the business operation in a new transaction after a definite abort.
Using get by bucket in a Transaction
In the default hash-routed model, all keys under one bucket prefix (for example services/) are on the same partition. This means that get by bucket is a consistent, transactional read of that group. For an example, see Buckets and Transactions. Key spaces that use Key-Range Sharding can split into several ranges. For these key spaces, use an ordered range read and not a bucket read.
In a pessimistic transaction, get by bucket also acquires a prefix lock for that bucket. While the transaction is open, concurrent writes under the same bucket are blocked or aborted. Repeated reads of the same bucket return the same result. commit or rollback releases the lock.
Using Ordered Range Reads in a Transaction
For ordered key spaces, interactive transactions also support bounded range reads.
await using KahunaTransactionSession session = await client.StartTransactionSession(
new() { Locking = KeyValueTransactionLocking.Pessimistic, Timeout = 5000 }
);
KeyValueGetByRangePageResult page = await session.GetByRange(
prefix: "users",
startKey: "users/000100",
startInclusive: true,
endKey: "users/000200",
endInclusive: false,
limit: 100,
durability: KeyValueDurability.Persistent
);
GetByRange(...) is the right primitive when the working set is an ordered slice of keys. A bucket read covers a complete single-partition bucket.
In a pessimistic transaction, GetByRange(...) acquires a range lock over the requested interval. While the lock is held, it blocks conflicting writes in the interval. Writes outside the interval can proceed. These locks are stored in the memory of the partition leader. A leader change clears them, and renewal can leave gaps. rollback releases the recorded lock set. See lock and failure semantics.
Within the same transaction session, range reads also follow read-your-own-writes semantics: uncommitted inserts and updates made by the session are visible to later reads from that session, and uncommitted deletes stay hidden from that session's later reads.
Locking Modes
Kahuna supports pessimistic and optimistic transactions. Choose the mode with the locking option.
| Mode | Behavior | Best fit |
|---|---|---|
pessimistic (default) | Locks keys up front. Point reads can use point locks, bucket reads can use prefix locks, and ordered range reads can use range locks. | Hot keys, workflows where retries are expensive, and reads that must block phantoms. |
optimistic | Reads don't take exclusive locks, and writes lock only the keys that they modify. At commit, Kahuna revalidates the observed revisions and aborts on concurrent write intents over the read set. | Read-heavy workloads with low write contention. |
Pessimistic locking is the default. It is more conservative and can avoid wasted work under contention, but it can hold locks longer. Optimistic locking allows more read concurrency but relies on conflict detection at commit.
Optimistic reads avoid exclusive locks. The first latest read of each key records its committed value, or that the key is absent; this includes a value whose transaction committed but is not settled yet. Later point operations can abort immediately when that observation is stale. Commit also validates dependencies. Retry definite aborts with a new transaction.
Transaction locks are stored in the memory of the partition leader and have an expiration. This means that they aren't held forever. A leader change can drop them; see Retry Outcomes.
Transaction Lifecycle
- Begin: Kahuna assigns a transaction ID based on a hybrid logical clock (HLC) timestamp and creates a coordinator-owned session.
- Read and write: Operations run on the responsible partition leaders, and the server records each confirmed effect. A retried interactive operation carries the same operation ID. This means that it returns the original result and doesn't apply the mutation twice.
- Validate: Optimistic transactions, and transactions with read validation, re-check the keys they read and abort if one changed. They also abort if another transaction has a concurrent write intent on a key that was read but not written. This prevents write skew. Pessimistic transactions lock the data that they read ahead of time to avoid conflicts and phantoms.
- Finalize: The first commit or rollback, or the first close or cleanup attempt, closes the transaction to new operations and freezes its working set. Commit then applies the write set through two-phase commit. Rollback releases staged writes and locks, with the MVCC read entries.
See Distributed Transactions for the design, and Transaction Lifecycle for the step-by-step mechanics.
Retry Outcomes
A transaction that doesn't commit returns a result that tells you what to do next. The diagram shows where each outcome sends you.
Abortedis definite: the transaction did not commit, for example because of a conflict. To retry the business operation, start a new transaction and recompute from new reads.MustRetrymeans the outcome is not known yet, or transient work remains. The transaction may have committed. Retry the same commit or rollback with the same transaction or session handle, and don't add new operations. Starting a fresh transaction is not a substitute for resolving an unknown commit, and aMustRetryor a transport timeout is not proof of rollback.AdmissionRefusedmeans the node did not start the transaction because its admission queue was full or the admission wait expired. Retrying is safe; back off first. See Transaction Priority Admission.
A partition leader change can drop transaction locks, and reacquiring a lock cannot protect values read earlier. Commit then fails, and the unprotected work isn't committed. An interactive session returns Aborted with a Lost lock: … reason, and a self-contained script returns MustRetry so it can rerun as a new transaction. Detected data conflicts return Aborted, as usual. See Detecting Locks Lost During Failover and Staged Writes and Commit Probes.
The outcome contract lists all results, for example Committed and RolledBack.
Durability Modes in Transactions
| Mode | Behavior |
|---|---|
| Persistent | Commit depends on the replicated Raft WAL and durable decision. The materialized backend flush is asynchronous; process-loss durability requires persistent WAL storage and durable write settings. |
| Ephemeral | Leader-memory state; values and unprepared transaction staging can be lost on leadership or process loss. |
In this example, eset stores session:abc with ephemeral durability (in memory). set stores session:xyz with persistent durability (disk).
begin
eset "session:abc" "active"
set "session:xyz" "active"
commit
end
See Durability Levels.
Key durability is separate from transaction decision durability. Persistent writes are crash-atomic in both the default BestEffort mode and Durable mode. Durable adds a stricter rule. Transactions that modify ephemeral keys aren't allowed. See Durable Commit Decisions for the differences and when to use each.
Best Practices
- Group keys by prefix when you want a single-partition transactional working set.
- Use key-range routing for large ordered spaces that may need to split over time.
- Use ephemeral keys for high-speed, non-critical paths.
- Consider pessimistic locking for highly contended keys to avoid retries.
- Use durable decisions when the server should reject any transaction that modifies an ephemeral key.
- Use transaction priority to keep latency-critical transactions from waiting behind bulk work when admission ceilings are enabled.
- Use yielding transactions for background maintenance that should give way to foreground writers. The foreground writers then don't fail.
- Retry
MustRetrywith the same transaction/session handle and do not add new operations after finalization starts. - Monitor retries to detect hotspots in your workload.
Transaction Options
Options control the behavior of a transaction, for example its locking and timeout. Script transactions set them in begin (...). For all script options, with their values and defaults, see BEGIN Options. That table also shows the matching client options.
Interactive sessions take the options from the client. The .NET client exposes them on KahunaTransactionOptions; the TypeScript client exposes the same options using camel-case names on TransactionOptions.
| .NET option | TypeScript option | Default | Description |
|---|---|---|---|
Locking | locking | Pessimistic / "pessimistic" | Chooses pessimistic or optimistic concurrency behavior. |
Timeout | timeout | server default when 0 | Maximum transaction duration in milliseconds. |
AsyncRelease | asyncRelease | false | Allows eligible post-commit cleanup to continue in the background. |
AutoCommit | autoCommit | true | Carried in the protocol options. However, interactive sessions require an explicit commit. Disposal of a pending session rolls back. |
ReadValidation | readValidation | None / "none" | Set to TrackAndValidate or "trackAndValidate" to record latest reads and validate them against revision or write-intent changes at commit. |
ReadTimestamp | readTimestamp | zero HLC | Uses a fixed historical HLC timestamp for all reads of the transaction, including paginated range reads. Do not combine it with read validation. |
DecisionDurability | decisionDurability | BestEffort / "bestEffort" | Persistent writes are crash-atomic in both modes. Durable also doesn't allow ephemeral modifications, and it requires a record anchor. |
Priority | priority | Normal / "normal" | Admission priority used when MaxConcurrentSessions is enabled on the receiving node. |
AdmissionWaitMs | admissionWaitMs | server default when 0 | Maximum time to wait for an admission slot before the transaction starts. The server clamps it to MaxAdmissionWaitMs. |
ConflictPolicy | not yet exposed | Normal | Set to Yield in the .NET client when retryable maintenance work should yield point-key intents to foreground writers. See Yielding Transactions. |
Priority and the admission wait matter only if an operator enables a per-node transaction concurrency ceiling, which is disabled by default. Priority decides when a transaction starts. It doesn't change how the transaction locks or commits. See Transaction Priority Admission for the queueing behavior and tuning.
Interactive Transactions
Use an interactive transaction when your logic needs your own language and libraries between reads and writes. As with a database transaction, you start it and run operations. Then you commit or roll back. Kahuna's server-side coordinator owns the confirmed working set and finalization state.
Interactive transaction sessions are available through both the gRPC and REST transports.
- .NET
- TypeScript
Start a session with StartTransactionSession, and run operations on it. Then commit.
await using KahunaTransactionSession session = await client.StartTransactionSession(
new KahunaTransactionOptions
{
Locking = KeyValueTransactionLocking.Optimistic,
Timeout = 5000
}
);
KahunaKeyValue job = await session.GetKeyValue("jobs/1042");
KahunaKeyValue load = await session.GetKeyValue("workers/w-7");
if (job.ValueAsString() == "pending" && load.ValueAsLong() < 3)
{
await session.SetKeyValue("jobs/1042", "w-7");
await session.SetKeyValue("workers/w-7", (load.ValueAsLong() + 1).ToString());
}
await session.Commit();
Call Commit explicitly when the work should become visible. Disposing a still-pending session rolls it back, which makes await using a safety net for exceptions and early returns.
For an optimistic read-modify-write on a contended key, the .NET session can wait briefly for a foreign write intent before it chooses the revision to read.
KahunaKeyValue item = await session.GetKeyValue(
"inventory/widget-42",
new KeyValueIntentWait(LimitMs: 500, HoldsLocks: false));
Use HoldsLocks: true if the session already has a lock or a staged write. On timeout or a waiter limit, the read uses its ordinary behavior; waiting does not guarantee the following write commits. For limits and early-abort flags, see bounded waiting and conflict controls.
The session exposes these properties for diagnostics and advanced integrations: Status, TransactionId, Handle, RecordAnchorKey. Most applications should keep using the session object and let the SDK carry the routing identity.
A transaction can abort on a conflict, or when it meets another transaction's exclusive lock under pessimistic locking. Retry it from the client.
The clients provide helpers that rerun a transaction body with a short jittered backoff. Use them for operations that are safe to execute more than once.
KahunaTransactionOptions txOptions = new()
{
Locking = KeyValueTransactionLocking.Pessimistic,
Timeout = 5000
};
await client.RetryableTransaction(txOptions, async (session, cancellationToken) =>
{
KahunaKeyValue job = await session.GetKeyValue("jobs/1042");
KahunaKeyValue load = await session.GetKeyValue("workers/w-7");
if (job.ValueAsString() == "pending" && load.ValueAsLong() < 3)
{
await session.SetKeyValue("jobs/1042", "w-7");
await session.SetKeyValue("workers/w-7", (load.ValueAsLong() + 1).ToString());
}
await session.Commit();
});
RetryableTransaction(...) starts a fresh transaction for each attempt. It retries the three retryable outcomes: Aborted, MustRetry, AlreadyLocked. When the budget is used up, it throws a KahunaException. MustRetry can represent an unknown commit outcome. For this reason, use this helper only for a business operation that is safe to repeat. For an unresolved durable finalize, retry the same identity instead.
Durable commit decisions can be requested when all modified keys are persistent.
KahunaTransactionOptions options = new()
{
Locking = KeyValueTransactionLocking.Pessimistic,
Timeout = 10_000,
ReadValidation = ReadValidation.TrackAndValidate,
DecisionDurability = DecisionDurability.Durable
};
await using KahunaTransactionSession session =
await client.StartTransactionSession(options, cancellationToken);
await session.SetKeyValue(
"jobs/1042",
"w-7",
durability: KeyValueDurability.Persistent,
cancellationToken: cancellationToken
);
await session.SetKeyValue(
"workers/w-7",
"3",
durability: KeyValueDurability.Persistent,
cancellationToken: cancellationToken
);
bool committed = await session.Commit(cancellationToken);
if (!committed)
throw new KahunaException("Commit must be retried", KeyValueResponseType.MustRetry);
Commit(...) and Rollback(...) return true when the requested terminal outcome is reached. A false result means the outcome is not known yet and the same finalization action should be retried with the same session handle. After commit or rollback starts, do not add new operations to the session.
The TypeScript client exposes interactive transactions through beginTransaction(...) and withTransaction(...).
await using session = await client.beginTransaction({
locking: "optimistic",
timeout: 5000
});
const job = await session.get("jobs/1042");
const load = await session.get("workers/w-7");
if (job.valueAsString() === "pending" && load.valueAsNumber() < 3) {
await session.set("jobs/1042", "w-7");
await session.set("workers/w-7", String(load.valueAsNumber() + 1));
}
await session.commit();
Disposing a still-pending session rolls it back. If your runtime doesn't support await using, call await session.rollback() or await session[Symbol.asyncDispose]() when abandoning the session.
Use withTransaction(...) when retryable conflicts should start a new attempt automatically.
await client.withTransaction(
{
locking: "pessimistic",
timeout: 5000
},
async (session) => {
const job = await session.get("jobs/1042");
const load = await session.get("workers/w-7");
if (job.valueAsString() === "pending" && load.valueAsNumber() < 3) {
await session.set("jobs/1042", "w-7");
await session.set("workers/w-7", String(load.valueAsNumber() + 1));
}
await session.commit();
}
);
Durable commit decisions can be requested when all modified keys are persistent.
await using session = await client.beginTransaction({
locking: "pessimistic",
timeout: 10_000,
readValidation: "trackAndValidate",
decisionDurability: "durable"
});
await session.set("jobs/1042", "w-7", { durability: "persistent" });
await session.set("workers/w-7", "3", { durability: "persistent" });
const committed = await session.commit();
if (!committed) {
throw new Error("Commit must be retried");
}
A coordinator leadership change does not migrate an active session. Requests can find its original owner while that process remains reachable, including when another node forwards the request. The session isn't replicated. Participant lock loss can also abort it. See session ownership after leader changes.
Transactional Set-Many
A transactional set-many checks a group of writes before staging them, which helps prevent a failed conditional item from leaving unrelated rows staged in the session. Staging means holding an uncommitted value. The transaction must commit before other clients see it. Non-transactional batches remain independent writes, and delete-many does not use this set-many protocol.
All items must name the same transaction. Mixing transaction IDs, mixing transactional and non-transactional items, or repeating a (key, durability) pair in a transactional batch returns InvalidInput.
| Situation | Result |
|---|---|
| All items belong to one actor | Check and stage run in one actor turn. Any refusal leaves the complete batch unstaged. |
| Items span actors or partition leaders | All groups run a check round before any group starts staging. A refusal in that round leaves the complete batch unstaged. |
| A concurrent writer intervenes between rounds under optimistic locking | One group can stage while another group gets a refusal. Inspect all results, and roll back the transaction if any items staged. |
A failed condition returns NotSet. A conflict returns a separate transient type and holder information. Items that passed but weren't staged return NotApplied. This result is different from Set. These items didn't change the working set of the transaction. After a transient refusal, if no items are staged, resend the complete batch. Don't resend only the conflicting item. A registered batch that is refused completely doesn't fold effects. This means that you can use the same operation ID when you resend it. With pessimistic locking, hold exclusive locks on all keys before the batch. This prevents the cross-round writer race. A transport failure can leave the result uncertain. Resolve or roll back the session. Don't assume that no items staged.
Kahuna Script preserves its statement-by-statement behavior when it internally batches leading set statements. If one conditional statement returns NotSet, the engine resends its NotApplied siblings, but it doesn't resend the refused statement. A failed condition therefore does not itself stop other successful script writes from committing. Transient failures stop that execution.
Interactive Transactions vs Kahuna Scripts
Interactive transactions integrate more easily with application code, at the cost of more network round trips and more care when a failure leaves the outcome unresolved. Kahuna Scripts run entirely on the server, with fewer round trips and automatic lock management, but you write the logic in Kahuna Script. Choose based on how complex the logic is and how much latency you can accept.
Interactive Transactions
Advantages
- Familiarity and Easier Debugging: You write the logic in your primary programming language, such as C# or JavaScript. It is then easier to debug and maintain the logic, and to integrate it with your development tools.
- Better Integration: Interactive transactions work directly with application-level logic and error handling, and with native data structures.
Disadvantages
- Increased Latency: Requires multiple round-trips between the client and server, which can introduce additional delays.
- More Retry Handling: Network interruptions can leave commit or rollback unresolved. Retry that finalization with the same session handle; starting a fresh transaction is not a substitute for resolving an unknown commit.
- Graceful Degradation Challenges: In the event of partial failures (e.g., network partitions), locks can be held until the transaction times out. This can be mitigated by setting short transaction timeouts.
Kahuna Scripts
Advantages
- Atomic Execution: The entire script executes atomically on the server (transaction coordinator). Writes to persistent keys stay atomic through node failures; writes to ephemeral keys are atomic only as long as there are no node failures or abnormal inter-node network conditions.
- Automatic Lock Management: Kahuna Scripts automatically release acquired locks in the presence of conflicts, reducing complexity and avoiding unwanted delays or retries.
- Supports Complex Logic: Scripts can include conditionals (
if,switch) andforloops, and function calls, directly on the server. - Shared and Portable Logic: The same Kahuna Script can be executed from multiple programming languages, and it doesn't need changes or extra maintenance.
- Reduced Round-Trips: Operations are fully executed server-side, minimizing network latency between client and server.
Disadvantages
- Potentially Harder to Maintain: Kahuna Script syntax may be less familiar and harder to debug or test compared to your main programming language.
- Script Size Limitations: Large or complex business logic may be difficult to express and maintain within Kahuna Scripts.