Skip to main content

.NET Client

The .NET client (Kahuna.Client) gives a C# application one typed API for the coordination work you would otherwise build yourself on Redis or a SQL table: distributed locks, the key/value store, Kahuna Script and multi-key transactions, and the distributed sequencer. It also covers cluster administration, including backups and point-in-time restore.

The client talks to the cluster over gRPC by default, packs waiting key/value requests together under load, and can route point operations straight to the node that owns them. It hides most routing and coordination details, but it exposes the controls that you need for consistency and durability, and for retries. It works with ASP.NET Core. The distributed rate limiters plug into its rate-limiting middleware and share their budgets across application replicas. Documentation and samples are in the docs/ folder and the GitHub repository.

For change notifications on persistent keys, see Watch Persistent Key Changes. For Node.js applications, see the TypeScript Client.

Client Installation​

Install the NuGet package with the .NET CLI.

dotnet add package Kahuna.Client

You can also use the NuGet Package Manager.

Install-Package Kahuna.Client

Connect​

Create one client and reuse it. It can be a global instance.

using Kahuna.Client;

var client = new KahunaClient("https://localhost:8082");

To configure a pool of Kahuna endpoints that belong to the same cluster, pass several URLs.

var client = new KahunaClient([
"https://localhost:8082",
"https://localhost:8084",
"https://localhost:8086"
]);

Using a pool of reachable endpoints lets the client avoid a load balancer and also enables leader-aware routing. With the default KahunaRoutingMode.Auto, a client configured with several endpoints learns route hints from responses. It then sends later point operations directly to the node that owns the resource, for example key/value and lock operations.

Route hints are advisory. If leadership or placement changes, the receiving server re-resolves the resource and forwards or returns retryable state as needed.

For routing modes and endpoint mapping, see Client Leader-Aware Routing. That page also covers server advertisement flags and the routing counters of the Kahuna.Client.Routing meter.

Dependency Injection​

Kahuna.Client includes AddKahunaClient extensions for IServiceCollection. Register one singleton per cluster so requests share pooled connections and the routing cache. The client uses the container's ILogger<KahunaClient> when it is available.

using Kahuna.Client;
using Microsoft.Extensions.DependencyInjection;

builder.Services.AddKahunaClient(
["https://kahuna-1:8082", "https://kahuna-2:8082"],
options => options.DefaultOperationTimeout = TimeSpan.FromSeconds(10));

// In an application service, receive KahunaClient through constructor injection.

A single URL is also accepted. For several clusters, register each with AddKeyedKahunaClient("orders", ["https://orders-kahuna:8082"]) and resolve it with GetRequiredKeyedService<KahunaClient>("orders"). Registration copies the endpoint list, and empty lists or blank entries aren't allowed. The client is created when the container first resolves it.

.NET Aspire​

Kahuna.Aspire.Client connects a service to a standalone Kahuna node or cluster declared in an Aspire AppHost. The same builder.AddKahunaClient("kahuna") call consumes a single URL or the cluster's comma-separated node URLs. It reads the supplied connection string and registers a singleton KahunaClient. It also adds health checks and telemetry sources. See Aspire setup for NuGet installation and AppHost configuration.

In the consuming service, use the same connection name as the AppHost resource.

using Kahuna.Client;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.AddKahunaClient("kahuna",
configureSettings: settings => settings.HealthCheckTimeout = TimeSpan.FromSeconds(5),
configureOptions: options => options.DefaultOperationTimeout = TimeSpan.FromSeconds(10));

var app = builder.Build();
app.MapGet("/config", async (KahunaClient client) =>
{
var value = await client.GetKeyValue("my-config");
return value.Success ? Results.Ok(value.ValueAsString()) : Results.NotFound();
});
app.MapDefaultEndpoints();
app.Run();

AddServiceDefaults and MapDefaultEndpoints come from the application's Aspire service-defaults project, as in the integration sample. They configure exporters and expose health endpoints; the Kahuna integration registers its sources and checks but does not install an OTLP exporter or map HTTP health routes itself. This host-builder method reads configuration, unlike builder.Services.AddKahunaClient(urls), which takes explicit endpoints.

Aspire Configuration​

Settings bind from Kahuna:Client. ConnectionStrings:kahuna overrides that section's ConnectionString, and configureSettings is applied after that. Client transport/routing options are set through configureOptions.

SettingDefaultMeaning
ConnectionStringnoneOne HTTP or HTTPS URL, or comma-separated URLs. The form Endpoints=http://node1:8083,http://node2:8083 also works, and so does Endpoint=. Missing or invalid endpoints fail registration.
DisableHealthChecksfalseSkip the integration's health check.
HealthCheckTimeoutnullNo overall check deadline. With multiple endpoints, each membership attempt has a separate 2-second limit. Set this option to bound the complete check.
DisableTracingfalseSkip registration of the Kahuna.Client activity source.
DisableMetricsfalseSkip registration of the Kahuna.Client and Kahuna.Client.Routing meters.

These telemetry switches control this integration's registrations. They don't control listeners registered elsewhere. Use normal service defaults or another exporter to send data to the Aspire dashboard.

For several clusters, call builder.AddKeyedKahunaClient("orders") for each connection name. It registers a keyed singleton, uses Kahuna:Client:orders settings with ConnectionStrings:orders taking precedence, and registers the health check as Kahuna_orders. Resolve it with [FromKeyedServices("orders")] or GetRequiredKeyedService<KahunaClient>("orders"); no unkeyed client is added by this call.

Health-Check Scope​

The updated service check uses the client's rotating endpoint selection for up to N GetClusterMembership calls, where N is the configured endpoint count. It returns healthy as soon as one answers with Initialized = true. With multiple endpoints, each attempt is limited to 2 seconds so a stopped container's proxy cannot block checks of the remaining nodes. If none is initialized, or none answers, the check is unhealthy. A single-endpoint check doesn't have an extra per-attempt limit. HealthCheckTimeout bounds the complete check; the unary gRPC membership call does not use DefaultOperationTimeout. The default registration name is Kahuna.

Membership initialization does not prove quorum or storage health, or successful data reads and writes. One running node in a three-node cluster can therefore make the application's health check pass while the AppHost cluster resource is unhealthy and data operations fail. Use the cluster readiness rules to interpret the dashboard. This multi-endpoint check is part of the latest source; the published 1.15.0 integration checks just one endpoint per probe.

The generated connection string uses the node's cleartext gRPC endpoint, or a comma-separated list of those endpoints for a cluster; HTTP dashboard URLs are separate. For applications outside Aspire that supply their own connection string, select an endpoint compatible with the configured client transport.

Client Telemetry​

The client publishes operation spans through the Kahuna.Client activity source and kahuna.client.operation.duration through the Kahuna.Client meter, for both REST and gRPC. This makes individual operations visible even when gRPC carries them on one long-lived batch stream. Duration samples are in seconds. Kahuna.Client doesn't install an exporter. If no listeners are registered, calls pass directly to the transport.

For an application that uses OpenTelemetry, install OpenTelemetry.Extensions.Hosting and OpenTelemetry.Exporter.OpenTelemetryProtocol. Then register the sources.

using Kahuna.Client.Diagnostics;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing
.AddSource(KahunaClientTelemetry.ActivitySourceName)
.AddOtlpExporter())
.WithMetrics(metrics => metrics
.AddMeter(KahunaClientTelemetry.MeterName,
KahunaClientTelemetry.RoutingMeterName)
.AddOtlpExporter());

Configure the collector with standard OTEL_* environment variables. The routing meter is Kahuna.Client.Routing; its counters complement operation timing.

Spans identify the operation and db.system.name=kahuna, with the address and port of the contacted server. Duration samples identify the system and operation. Exceptions add error.type, mark the span as failed, and are recorded as span events; a conditional write returning an unsuccessful result does not by itself mark a span as failed. Keys and values aren't metric labels or built-in span tags, and scripts aren't either. A sample measures one transport call. An interactive transaction or application retry loop can produce several samples.

OpenWatch measures the opening of a watch. It doesn't measure the event stream after that. Streaming ScanByRange doesn't get a scan-lifetime span or duration sample. This means that consumer processing time isn't reported as database latency. To also collect the node's metrics and logs, see server OTLP export.

Client Options​

Pass KahunaOptions when you need to tune transport behavior.

using Kahuna.Client;
using Kahuna.Client.Routing;

var client = new KahunaClient(
[
"https://localhost:8082",
"https://localhost:8084",
"https://localhost:8086"
],
options: new KahunaOptions
{
GrpcChannelPoolSize = 4,
DefaultOperationTimeout = TimeSpan.FromSeconds(10),
GrpcRequestFrames = true,
BatchCoalescingThreshold = 10,
BatchCoalescingDelayMs = 2,
Routing = KahunaRoutingMode.Metadata,
RouteCacheCapacity = 8192,
RoutingEndpointMap = new Dictionary<string, string>
{
["https://172.30.0.2:8082"] = "https://localhost:8082"
}
}
);

GrpcChannelPoolSize controls how many HTTP/2 channels the client opens per endpoint. The default is 2. Raise it when one client process is driving high concurrency and a single endpoint needs more parallel streams. Each extra channel is an additional connection. Keep the value small unless measurement shows that the client is the bottleneck.

GrpcRequestFrames is enabled by default. Under load, the client can send several already-waiting key/value requests in one gRPC stream message to nodes that announce support for request frames. A single quiet request travels alone. This means that the option doesn't add a coalescing delay. Leave it enabled unless you are doing an A/B benchmark or diagnosing transport behavior during a rolling upgrade.

Routing options control how the client chooses the first node for an operation. Learned reuses route hints from previous responses. Metadata also reads the cluster routing map so new resources can go directly to their owner. RoutingEndpointMap is needed when servers advertise internal addresses but the application dials mapped or public addresses.

For local HTTPS endpoints with a development certificate, set AllowInsecureCertificateValidation = true. For production certificate pinning, set TrustedServerCertificateThumbprints instead.

The table lists the key KahunaOptions fields.

OptionDefaultPurpose
UpgradeUrlsfalseLet the client update lock-handle affinity from the server endpoint that served a lock response.
RoutingAutoSelect the endpoint routing mode. See Client Leader-Aware Routing.
RouteCacheCapacity4096Maximum learned routes kept by the client.
RouteHintLifetime60 secondsHow long a learned route can be reused before it must be observed again.
RoutingEndpointCooldown5 secondsHow long an endpoint is skipped after a transport failure.
RoutingMetadataLifetime60 secondsHow long metadata-mode routing maps are cached.
RoutingEndpointMapnullMaps server-advertised endpoints to URLs this client actually dials.
AllowUnlistedRoutingEndpointsfalseAllows dialing advertised endpoints that were not configured or mapped.
MinConnections1Currently unused: the client does not read this option.
MaxConnections1Currently unused: the client does not read this option.
DefaultOperationTimeout30 secondsTimeout used when a call doesn't have a cancellation token deadline.
GrpcChannelPoolSize2gRPC channels opened per configured endpoint.
GrpcRequestFramestruePack already-waiting key/value requests into one gRPC stream message when the server supports it.
BatchCoalescingThreshold10Minimum batch size before immediate dispatch; smaller batches may wait briefly.
BatchCoalescingDelayMs2Maximum batch coalescing wait in milliseconds.
AllowInsecureCertificateValidationfalseSkip TLS server certificate validation for local or test environments.
AdminApiKeynullCredential sent only with admin operations, over REST or gRPC.
TrustedServerCertificateThumbprintsemptySHA-256 certificate thumbprints accepted for production pinning.

Transport​

The client uses gRPC by default. To use the REST API, pass a RestCommunication instance.

using Kahuna.Client;
using Kahuna.Client.Communication;

KahunaOptions options = new();
ILogger<KahunaClient>? logger = null; // or a logger from your DI container

var client = new KahunaClient(
"https://localhost:8082",
logger,
communication: new RestCommunication(logger, options),
options: options
);

RestCommunication reads the TLS options (AllowInsecureCertificateValidation, TrustedServerCertificateThumbprints) from the options you pass to it. Those REST TLS settings are process-wide: the first non-default configuration wins.

Both transports support all operations that this page describes, and they return the same per-value script result shape. They have a few differences.

  • GetManyKeyValues(...) and ExistsManyKeyValues(...) work over both REST and gRPC. Over REST, a batch read that carries a transaction ID returns InvalidInput. That transport can't register the batch in the transaction's read set.
  • REST encodes the difference between a null payload and a zero-byte payload as JSON null versus an empty base64 string. gRPC uses bytes-field presence.
  • These options apply only to the gRPC transport: GrpcChannelPoolSize, GrpcRequestFrames, DefaultOperationTimeout, the batch coalescing options.

Errors and Cancellation​

Protocol failures throw KahunaException. Read ErrorDomain before the code for that domain, for example LockErrorCode or KeyValueErrorCode. ErrorCodeName gives the code's name for logs. Inspect the codes. Don't match exception text.

using Kahuna.Client;
using Kahuna.Shared.KeyValue;

try
{
await using KahunaTransactionSession session = await client.StartTransactionSession(
new KahunaTransactionOptions { AdmissionWaitMs = 2_000 }
);
// ...
}
catch (KahunaException ex) when (ex.ErrorDomain == KahunaErrorDomain.KeyValue
&& ex.KeyValueErrorCode == KeyValueResponseType.AdmissionRefused)
{
// No transaction was started: back off and retry.
}

Client methods accept a CancellationToken. On the gRPC transport, a batched call that doesn't have a token deadline uses DefaultOperationTimeout and surfaces an OperationCanceledException when it expires. A timeout does not tell you whether the server applied the operation.

Locks​

GetOrCreateLock acquires a lease on a resource name and returns a KahunaLock. Dispose it with await using to release the lock when the method ends. Pass wait and retry to continue to try while another owner has the lock. Frequent retries suit short critical sections under heavy contention, where the lock changes hands quickly.

using Kahuna.Client;

public async Task UpdateBalance(KahunaClient client, string userId)
{
// hold the lease for 5 seconds (unless extended),
// retry every 150 milliseconds for up to 10 seconds if the lock is not available

await using KahunaLock myLock = await client.GetOrCreateLock(
"balance-" + userId,
expiry: TimeSpan.FromSeconds(5),
wait: TimeSpan.FromSeconds(10),
retry: TimeSpan.FromMilliseconds(150),
durability: LockDurability.Persistent
);

if (myLock.IsAcquired)
{
// implement exclusive logic here
}
else
{
Console.WriteLine("Someone else has the lock!");
}

// myLock is automatically released after leaving the method
}

If you don't pass wait and retry, the call makes a single attempt and gives up immediately. durability defaults to LockDurability.Persistent. The lock state is committed by a quorum (a majority) of the partition's replicas. This means that it survives the loss of a minority of those replicas. See durability levels.

Use myLock.FencingToken so that a client that lost its lease cannot overwrite newer work. The protected record stores the highest token it accepted, and the check and the write must happen in one step: reading the stored token in application code and saving afterwards leaves a gap in which another holder can write. When the protected record is stored in Kahuna, pass the token to a Kahuna Script that compares and writes in one transaction.

KahunaTransactionScript fencedWrite = client.LoadTransactionScript("""
begin
let fence = get @fence_key
if fence != null then
if to_int(@token) < to_int(fence) then
throw "stale token"
end
end
set @fence_key @token
set @data_key @value
commit
end
""");

await fencedWrite.Run([
new() { Key = "@fence_key", Value = $"balance-{userId}/fence" },
new() { Key = "@data_key", Value = $"balance-{userId}" },
new() { Key = "@token", Value = myLock.FencingToken.ToString() },
new() { Key = "@value", Value = newBalance.ToString() }
]);

A stale token makes Run throw a KahunaException (KeyValueErrorCode == KeyValueResponseType.Errored, message stale token at line 5), and neither key changes. See Fencing Tokens for when a resource outside Kahuna must do this check itself.

myLock.TryExtend(TimeSpan) returns (true, fencingToken) when the lease was extended. The server extends only for the current owner, and the token doesn't change. This means that a lost lock shows up as a failed extend: a KahunaException with a LockErrorCode such as InvalidOwner or LockDoesNotExist. Stop the protected work when it happens. myLock.GetInfo() returns the current owner and expiry. See Distributed Locks for the full API and the leader election recipe for a renewal loop.

Key/Value​

Snapshot Reads​

Top-level read methods take a snapshotMs parameter for as-of snapshot reads.

using Kahuna.Client;
using Kahuna.Shared.KeyValue;

KahunaKeyValue latest = await client.GetKeyValue("users/000100", KeyValueDurability.Persistent);

KahunaKeyValue sameSnapshot = await client.GetKeyValue(
"users/000100",
KeyValueDurability.Persistent,
snapshotMs: latest.LastModified
);

LastModified is the Unix-epoch millisecond timestamp at which that revision was committed. It can be reused as a snapshot anchor for later reads. The same parameter is available on the other read methods, for example ExistsKeyValue(...) and ScanByRange(...).

For exact archived revisions, use GetKeyValueRevision(...) when you know the precise revision number; use snapshotMs when you want the value visible at a specific historical time. When a historical view needs to stay readable for a long time, acquire a snapshot hold.

No-Revision Writes​

For cache-style keys that need only the latest value, set a key and skip the historical revision entry.

KahunaKeyValue result = await client.SetKeyValueNoRevision(
"cache/user/1001",
System.Text.Encoding.UTF8.GetBytes("""{"name":"Ada"}"""),
expiryTime: 60000,
durability: KeyValueDurability.Persistent
);

To compose it with other options, pass flags: KeyValueFlags.SetIfNotExists | KeyValueFlags.SetNoRevision to SetKeyValue(...).

The current revision advances as usual, and latest reads work as usual. However, the revision created by this write isn't available through GetKeyValueRevision(...) or snapshot reads that need that archived version. Use no-revision writes to reduce memory and disk write amplification when Kahuna is acting as a pure distributed key/value cache. Use normal writes for audit history and point-in-time reads, and for GetKeyValueRevision(...).

Null and Empty Values​

Kahuna preserves the difference between a key that doesn't have a payload and a key whose payload is zero bytes. In .NET, pass null for no payload and Array.Empty<byte>() for an empty byte array.

await client.SetKeyValue("profile/empty-payload", (byte[]?)null);
await client.SetKeyValue("profile/zero-bytes", Array.Empty<byte>());

Compare-value operations treat the two as different values, and an application can use a present-but-empty payload as a meaningful value.

Ordered Range Reads​

For ordered key spaces such as users/000001 through users/999999, GetByRange(...) reads one bounded page and ScanByRange(...) streams a larger range.

List<KahunaKeyValue> page = await client.GetByRange(
prefix: "users",
startKey: "users/000100",
startInclusive: true,
endKey: "users/000200",
endInclusive: false,
limit: 100,
durability: KeyValueDurability.Persistent
);

await foreach (KahunaKeyValue item in client.ScanByRange(
prefix: "users",
startKey: "users/000100",
startInclusive: true,
endKey: "users/001000",
endInclusive: false,
pageSize: 128,
durability: KeyValueDurability.Persistent,
snapshotMs: 1718392012345
))
{
Console.WriteLine($"{item.Key} -> {item.ValueAsString()}");
}

ScanByRange(...) continues to fetch server-side pages behind the async sequence. When snapshotMs isn't zero, it preserves one historical snapshot. Large range scans can read keys that are only on disk, and the scanned keys aren't forced back into the in-memory cache. A page can return retryable state again and again, for example during a range move or for an undecided transaction write intent. The scan then returns a retryable error. It doesn't scan forever. Back off briefly and retry.

A transaction session also exposes GetByRange(...), which returns a KeyValueGetByRangePageResult and can take a range lock; see ordered range reads in a transaction and Key-Range Sharding.

Batch Operations​

The client has four batch methods: SetManyKeyValues(...), DeleteManyKeyValues(...), GetManyKeyValues(...), ExistsManyKeyValues(...).

List<KahunaKeyValue> setResults = await client.SetManyKeyValues([
new()
{
Key = "services/auth",
Value = System.Text.Encoding.UTF8.GetBytes("node1"),
ExpiresMs = 30000,
Flags = KeyValueFlags.SetNoRevision,
Durability = KeyValueDurability.Persistent
}
]);
  • KahunaSetKeyValueRequestItem has these properties: Key, Value, ExpiresMs, Flags, CompareValue, CompareRevision, Durability.
  • KahunaDeleteKeyValueRequestItem has Key and Durability.
  • KahunaGetManyKeyValuesRequestItem has Key and Durability, with an optional Revision.

DeleteKeyValue(...) and DeleteManyKeyValues(...) return the revision of the tombstone (delete marker) created by the delete. For a key at revision 0, a successful delete returns revision 1, and a later set returns revision 2.

Set Flags = KeyValueFlags.SetNoRevision for batch cache writes where old values are not needed. You can combine it with conditional flags, for example an existence check or a revision check.

Persistent batch writes benefit from partition write coalescing: Kahuna can combine direct writes for the same Raft partition into fewer Raft proposals, even when they come from different client requests. A non-transactional batch is not atomic; use a transaction when all items must commit or roll back together. Transactional set-many adds check-before-stage behavior and the NotApplied item result; cross-actor optimistic batches can stage partially if a writer intervenes between rounds.

Watches​

WatchKeyValues streams the committed changes to a persistent key or prefix, or to a key range.

await using KahunaWatch watch = await client.WatchKeyValues(
new KeyValueWatchRequest(
KeyValueWatchScope.ForPrefix("config/prod/search/"),
KeysOnly: true),
cancellationToken);

await foreach (KeyValueWatchFrame frame in watch.ReadAllAsync(cancellationToken))
{
if (frame.Event is { } change)
Console.WriteLine($"Refresh {change.Key} ({change.Kind})");
else if (frame.IsTerminal)
Console.WriteLine($"Watch ended: {frame.Type}");
}

Open the watch before reading the initial state, and treat a terminal frame as a possible gap. WatchKeyValues(request, autoResume: true) can resume some interrupted streams from progress watermarks. All servers must use a positive --commit-admission-lag-ms. See Watch Persistent Key Changes for delivery rules and history holds, and the watch recipe for a refresh loop.

Scripts​

ExecuteKeyValueTransactionScript executes a Kahuna Script on the server. Pass dynamic values as parameters. Don't concatenate them into the script text. The server can then reuse the execution plan across calls, and the script is safe from injection.

const string script = """
let inventory = get @inventory_key
let available = to_int(inventory)
let requested = to_int(@requested_amount)
if available >= requested then
set @inventory_key available - requested
return 1
else
return 0
end
""";

var result = await client.ExecuteKeyValueTransactionScript(
script,
null,
[
new() { Key = "@inventory_key", Value = userInventoryKey },
new() { Key = "@requested_amount", Value = "100" }
]
);

Console.WriteLine("Result={0}", result.FirstValueAsString);

Avoid ExecuteKeyValueTransactionScript("SET " + key + " " + value); prefer "SET @key @value" with @key and @value parameters.

Script results expose Values. Each item carries the key and value that the script returned, with the revision and other metadata. For the first returned item, use the convenience accessors, for example FirstValue and FirstRevision.

For scripts that you execute often, load them once during initialization with client.LoadTransactionScript(script). Then call Run(parameters) on the returned KahunaTransactionScript. This avoids parsing and planning the script again on each call.

KahunaTransactionScript checkSession = client.LoadTransactionScript("""
let session = get @session_key
if not found then
return 0
end
set @session_key session ex to_int(@ttl_ms)
return 1
""");

var result = await checkSession.Run([
new() { Key = "@session_key", Value = sessionKey },
new() { Key = "@ttl_ms", Value = ttlMs }
]);

The script rewrites the session value to apply the new TTL. This means that the key's revision advances. To change only the expiry, use extend @session_key 1800000. extend takes an integer literal, and it doesn't take a placeholder.

Both ExecuteKeyValueTransactionScript(..., priority: TransactionPriority.Background) and Run(TransactionPriority.High, parameters) accept an admission priority. Priority matters only if the server enabled transaction admission ceilings. Otherwise, the priority is recorded for metrics, and the script starts immediately. See Transaction Priority Admission.

Interactive Transactions​

StartTransactionSession opens a KahunaTransactionSession for multi-key work written in C#, over gRPC or REST. RetryableTransaction starts a new transaction for each attempt. It retries the three retryable outcomes with a short jittered backoff: Aborted, MustRetry, AlreadyLocked.

KahunaTransactionOptions txOptions = new()
{
Locking = KeyValueTransactionLocking.Pessimistic,
Timeout = 5000
};

await client.RetryableTransaction(txOptions, async (session, cancellationToken) =>
{
KahunaKeyValue balance1 = await session.GetKeyValue(userA);
KahunaKeyValue balance2 = await session.GetKeyValue(userB);

if (balance1.ValueAsLong() >= 50)
{
await session.SetKeyValue(userA, (balance1.ValueAsLong() - 50).ToString());
await session.SetKeyValue(userB, (balance2.ValueAsLong() + 50).ToString());
}

await session.Commit();
});

Because MustRetry can represent an unknown commit outcome, use RetryableTransaction only for business operations safe to repeat. Retry an unresolved durable finalize with the same session identity.

Call Commit explicitly. Disposing a still-pending session rolls it back. This means that await using is a safety net for exceptions and early returns. After Commit or Rollback starts, don't send more reads or writes through the same session. The session exposes these properties for diagnostics: Status, TransactionId, Handle, RecordAnchorKey.

The table lists the KahunaTransactionOptions fields.

OptionDefaultDescription
LockingPessimisticChooses pessimistic or optimistic concurrency behavior. Pessimistic sessions acquire locks before or during operations. Optimistic sessions validate reads and write intents at commit.
Timeoutserver default when 0Maximum transaction duration in milliseconds. Use short timeouts for interactive work so abandoned sessions are cleaned up quickly.
AdmissionWaitMsserver default when 0Maximum time to wait for an admission slot before the transaction starts. The server clamps it to MaxAdmissionWaitMs.
AsyncReleasefalseAllows eligible post-commit cleanup to continue in the background. Leave it off when prompt lock cleanup matters.
AutoCommittrueCarried in the protocol options. However, interactive sessions require an explicit Commit. Disposal of a pending session rolls back.
ReadValidationNoneSet to TrackAndValidate to record latest reads and validate them against revision or write-intent changes at commit. Optimistic locking validates its read set at commit even when this value is None.
ReadTimestampHLCTimestamp.ZeroUses a fixed historical HLC timestamp for transaction reads. It is a snapshot view, and it isn't read-your-own-writes. It can't be combined with TrackAndValidate.
DecisionDurabilityBestEffortUnder either policy, persistent modifications use a canonical transaction record (the authoritative commit or abort decision) and durable prepared intents. With an explicit Durable, ephemeral modified keys aren't allowed.
PriorityNormalAdmission priority used when the server has enabled MaxConcurrentSessions. It affects when the session starts. It doesn't change how the session commits.
ConflictPolicyNormalSet to Yield for retryable maintenance work. Foreground writers can then take over its point-key intents, and they don't fail.

Commit(...) and Rollback(...) return true when the server reaches the requested terminal outcome. A false result means the final outcome is not known yet: retry the same finalize action with the same session handle. Treat the result as uncertainty. It isn't a conflict. Other terminal outcomes are thrown as KahunaException. Inspect KeyValueErrorCode.

ResultMeaning
CommittedThe transaction committed and the session is complete.
RolledBackRollback cleanup was acknowledged and the session is complete.
MustRetryRetry commit or rollback with the same session. Do not add more operations.
AbortedStart a new transaction if the business operation should be retried.
AlreadyLockedAnother transaction has a conflicting lock. Retry through RetryableTransaction(...) or back off manually.
ErroredThe handle is unknown or expired, or the outcome isn't available. Treat it as an application-level uncertainty.

The SDK assigns a stable operation ID to each transaction-scoped call. This means that a retried operation isn't applied twice. Pessimistic point-key operations retry transient lock-acquire refusals in the session for a short bounded window before returning MustRetry. The active interactive session is memory-resident: if it disappears before a canonical record is installed, retry the business operation from a new transaction.

These pages have more information about transactions.

Sequences​

The client exposes Kahuna's distributed sequencer for named, monotonically increasing values.

using Kahuna.Shared.Sequences;

KahunaSequence sequence = await client.CreateSequence(
"orders",
initialValue: 0,
increment: 1,
durability: SequenceDurability.Persistent
);

long orderId = await client.NextSequenceValue(
"orders",
idempotencyKey: "create-order-123"
);

KahunaSequenceRange range = await client.ReserveSequenceRange(
"orders",
count: 100,
idempotencyKey: "import-batch-456"
);

Use idempotency keys when retrying allocation requests after a timeout: a committed request retried with the same key returns the original allocation. The API also has methods to update, read, and delete a sequence. An update waits about one server SequencerBlockLease before it returns. For all methods, see Sequencer Clients. For update and retry behavior, see Sequence Model.

Snapshot Holds​

The snapshot hold methods prevent the pruning of the revisions that a historical timestamp needs while you read them. Examples are AcquireSnapshotHold and GetSnapshotFloor. These calls take no nodeUrl and rotate through the configured endpoints. See Snapshot Holds for a full .NET example.

Cluster Administration​

Administration operations, such as cluster membership and backups, have a separate page: .NET Client: Cluster Administration.