Skip to Content

Rust Client SDK

Installing Rust client SDK

[dependencies] oxia-client = "0.3" compio = { version = "0.19", features = ["macros"] }

The crate is oxia-client; the import root is oxia. The client is asynchronous and runs on a compio  runtime, which the application supplies — see Runtime. It needs Rust 1.99 or later (edition 2024). API documentation is available at https://docs.rs/oxia-client .

Optional Cargo features (all off by default):

FeatureDescription
tlsTLS connections, including custom CA and mutual TLS — see TLS.
otelReport client metrics through OpenTelemetry — see Metrics.

Token authentication needs no feature; it is always available.

Runtime

The client is single-threaded, for a thread-per-core design: it runs on a compio  runtime (io_uring on Linux, falling back to polling where io_uring is unavailable, as in most containers) and lives on the thread that built it. Building a client outside a compio runtime fails.

The client, its request builders and its subscriptions are neither Send nor Sync. The tasks of the client’s thread share it by cloning it; a clone cannot be moved to another thread.

  • To use more cores, run one client per thread, each in its own runtime. An OxiaClientBuilder is Send and Clone, so clone it into each thread. Each client has its own connections, sessions and batches.
  • Never block the client’s thread — all of the client’s work runs on it. Run blocking work with compio::runtime::spawn_blocking.
  • An application on another runtime, such as Tokio, runs the client on a thread of its own with a compio runtime, and sends it work over channels.
  • Dropping the runtime without calling close tears the client down abruptly, as dropping the client does: queued operations are not flushed, and ephemeral records linger until their session times out.

Client API

Initializing the client

To use the Oxia client, create a client instance. It is cheap to clone (all clones share one set of connections, batchers and sessions), shared by the tasks of its thread by cloning it, and valid until it is explicitly closed. Every operation returns a request builder: chain options onto it and .await it directly.

use oxia::OxiaClient; #[compio::main] async fn main() -> Result<(), oxia::OxiaError> { let client = OxiaClient::connect("localhost:6648").await?; // ... use the client ... client.close().await?; Ok(()) }

When creating the client it is possible to pass several options through the builder:

use std::time::Duration; let client = OxiaClient::builder() .service_address("localhost:6648") .namespace("my-namespace") .identity("my-client-identity") .request_timeout(Duration::from_secs(30)) .build() .await?;

Available client options (see OxiaClientBuilder):

OptionDescriptionDefault
namespaceOxia namespace to use.default
request_timeoutDeadline for each unary RPC. Long-lived streams are unbounded.30s
session_timeoutSession timeout for ephemeral records.15s
session_keep_aliveHow often the session is heartbeated.session_timeout / 10
identityStable client identity attached to ephemeral records.Random UUID
batch_max_sizeMaximum size of a batched request.128 KiB
max_requests_per_batchMaximum number of operations in a batch.1000
max_in_flight_bytesBytes the client holds for the writes in flight (their keys and values). While the budget is used up a put waits, rather than the client growing without limit; 0 disables it. Reads are not accounted for.64 MiB
max_write_batches_in_flightWrite batches a shard may have outstanding before further operations accumulate in the open batch.4
max_read_batches_in_flightThe same, for a shard’s read RPCs.4
auth_token / auth_token_providerToken authentication.No credentials
tlsTLS settings: custom CA, mutual TLS, domain-name override. Requires the tls Cargo feature.Plaintext (or TLS with system roots for an https:// address)
meter_providerOpenTelemetry meter provider to report metrics through. Requires the otel Cargo feature.Global provider

Errors surface as OxiaError; a record that does not exist is reported as Err(OxiaError::KeyNotFound) rather than a null value.

Writing records

// Write a record with the expectation that it does not already exist. let res1 = client .put("my-key", "value-1") .expected_record_not_exists() .await?; // Write with the expectation that it has not changed since the previous write. // If it has, the operation fails with OxiaError::UnexpectedVersionId. let res2 = client .put("my-key", "value-2") .expected_version_id(res1.version.version_id) .await?; // Ephemeral record: deleted automatically when the client session ends. client.put("/workers/worker-1", "host:port").ephemeral().await?; // Atomic sequence key: the server appends a monotonic suffix; requires a partition key. let seq = client .put("/events/", "event-data") .partition_key("/events/") .sequence_key_deltas([1]) .await?; // Attach a secondary index entry at write time. client .put("/offset/12345", "...") .secondary_index("partition", "p-17") .await?;

put options:

OptionDescription
partition_keyRoute to a specific shard (co-locate related keys).
expected_version_id / expected_record_not_existsConditional write (compare-and-swap, or assert the record is absent).
ephemeralBind the record to the client session — see ephemerals.
sequence_key_deltasServer-assigned monotonic suffixes — see sequence keys. Requires a partition key.
secondary_indexIndex the record under (index_name, secondary_key) — see secondary indexes.

Reading records

use oxia::ComparisonType; let record = client.get("my-key").await?; println!("{} = {:?}", record.key, record.value); // Metadata-only read (skips the value payload). let meta = client.get("my-key").include_value(false).await?; // Range-style get: returns the closest key ≤ the lookup key. let floor = client.get("/users/50").comparison(ComparisonType::Floor).await?;

get options:

OptionDescription
comparisonEqual (default), Floor, Ceiling, Lower, Higher. Non-equal modes scan all shards unless partition_key is set.
include_valueSet to false for a metadata-only read.
partition_keyRoute to a specific shard.
use_indexLook up via a named secondary index.

Deleting records

// Unconditional delete. client.delete("my-key").await?; // Conditional delete: only succeeds if the version matches. client .delete("my-key") .expected_version_id(res2.version.version_id) .await?;

delete also accepts partition_key, which must match the one the record was written with.

Deleting a range of records

Delete all records whose keys fall within [min, max):

client.delete_range("/users/", "/users//").await?;

Without a partition key, the call fans out to every shard. Pass partition_key to scope the delete to a single shard.

Listing keys

List keys in [min, max) without fetching values:

let keys = client.list("/users/", "/users//").await?; for key in keys { println!("{key}"); } // Narrow to a single shard via partition_key, or query a secondary index via use_index. let keys = client.list("/users/", "/users//").partition_key("/users/").await?; let by_email = client.list("", "\u{ffff}").use_index("email").await?;

Keys come back in the key sorting of their namespace: hierarchical by default (the keys with fewer / first, then by their bytes), or natural (by their bytes) — see key sorting. For a very large range, use .stream().await? to obtain an ordered async Stream instead of collecting a Vec.

list also accepts end_inclusive, which makes the range [min, max], and include_internal_keys, which stops Oxia’s own internal keys from being filtered out of the result.

Scanning records

Scan records in a key range, returning keys and values:

for record in client.range_scan("/users/", "/users//").await? { println!("key: {}, value: {:?}", record.key, record.value); } // With a secondary index. let by_email = client.range_scan("", "\u{ffff}").use_index("email").await?;

Like list, range_scan accepts partition_key, use_index, end_inclusive and include_internal_keys, and offers .stream().await? for an ordered, memory-bounded async stream.

Sessions and ephemerals

Sessions are managed transparently: the first put(...).ephemeral() creates a per-shard session, the client heartbeats it, and ephemerals are cleaned up when the client closes or the session expires. See ephemerals for the lifecycle details.

Notifications and sequence updates

Both are subscription handles you consume with recv() (or as a Stream):

// Change feed for the namespace. let mut notifications = client.notifications().await?; while let Some(notification) = notifications.recv().await { println!("{notification}"); } // Updates for a specific sequence prefix (pass the sequence's partition key). let mut updates = client.sequence_updates("/events/", "/events/").await?; while let Some(key) = updates.recv().await { println!("New sequence key: {key}"); }

Both builders accept buffer_size, the subscription’s channel capacity (default 100); when the buffer is full, delivery applies backpressure to the per-shard listeners.

See notifications and sequence keys for semantics.

Authentication

The client can present a bearer token on every request. This needs no Cargo feature. Pass a fixed token:

let client = OxiaClient::builder() .service_address("localhost:6648") .auth_token("my-token") .build() .await?;

For tokens that expire, implement TokenProvider and pass it instead, so the client fetches a current token for each request:

let client = OxiaClient::builder() .service_address("localhost:6648") .auth_token_provider(my_provider) .build() .await?;

TLS

TLS support is compiled in only when the tls Cargo feature is enabled:

cargo add oxia-client --features tls

An https:// service address (or tls://, the scheme the Go client uses) enables TLS with default settings, verifying the server certificate against the operating system’s trusted roots:

let client = OxiaClient::connect("https://oxia.example.com:6648").await?;

For a custom CA, a client certificate (mutual TLS), or a domain-name override, pass TlsOptions to the builder:

use oxia::TlsOptions; let ca_pem = std::fs::read("ca.crt")?; let cert_pem = std::fs::read("client.crt")?; let key_pem = std::fs::read("client.key")?; let client = OxiaClient::builder() .service_address("https://oxia.example.com:6648") .tls( TlsOptions::new() .trusted_ca_pem(ca_pem) .identity_pem(cert_pem, key_pem), ) .build() .await?;

All of the client’s connections — including the per-shard connections it opens from the cluster’s shard assignments — use the same TLS configuration.

Metrics

The client can report per-operation metrics through OpenTelemetry . Metrics support is compiled in only when the otel Cargo feature is enabled; without it, metric recording compiles to a no-op with zero overhead.

cargo add oxia-client --features otel

Attach a meter provider when building the client, or omit it to use the global OpenTelemetry meter provider:

let client = OxiaClient::builder() .service_address("localhost:6648") .meter_provider(&provider) .build() .await?;

The instruments are nanometer  histograms, which are exported through a nanometer::Producer rather than through the meter provider. The application must register one with its metric reader, once, using nanometer’s sdk feature — without it no histogram is exported. Until an OpenTelemetry SDK release carries MetricProducer again, that takes an SDK with it re-added; see nanometer’s README, “Exporting histograms”. The first client built in a process calibrates nanometer’s clock, which takes 10 to 200 ms.

Instruments are reported under the oxia_client meter — the same names as the Go client. The operation instruments carry type (put, get, delete, delete_range) and result (success, failure) attributes; the batch instruments carry type (write, read) and the same result:

InstrumentUnitDescription
oxia_client_opsecondsLatency of client operations, measured submit-to-complete (includes internal retries).
oxia_client_op_valuebytesValue size of operations that carry a value (the value written by a put, or returned by a get).
oxia_client_batch_totalsecondsBatch latency from when the batch was created, including the time it spent filling up.
oxia_client_batch_execsecondsBatch latency from when the batch was first sent, excluding the time it spent filling up.
oxia_client_batch_valuebytesTotal size of the values carried by a batch.
oxia_client_batch_request{request}Number of operations in a batch.

For the complete reference see the docs.rs API documentation .

Last updated on