Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

aerospike-client-rust

> 数据库
Open source

Rust client for the Aerospike database

99 stars0 likes1 views
WebsiteGitHub

About

Rust client for the Aerospike database

Aerospike Rust Client

Welcome to Aerospike's official Rust client.

Feature highlights

Execution models:

  • Async-First: Built for non-blocking IO, powered by Tokio by default, with optional support for async-std.
  • Sync Support: Blocking APIs are available using a sync sub-crate for flexibility in legacy or mixed environments.

Advanced data operations:

  • Batch protocol: full support for read, write, delete, and udf operations through the new BatchOperationAPI.
  • New query wire protocols: implements updated query protocols for improved consistency and performance.

Policy and expression enhancements:

  • Replica policies: includes support for Replica, including PreferRack placement.
  • Policy additions: new fields such as allow_inline_ssd, respond_all_keys in BatchPolicy, read_touch_ttl, and QueryDuration in QueryPolicy.
  • Rate limiting: supports records_per_second for query throttling.

Data model improvements:

  • Type support: adds support for boolean particle type.
  • New data constructs: returns types such as Exists, OrderedMap, UnorderedMap now supported for CDT reads.
  • Value conversions: implements TryFromaerospike::Value for seamless type interoperability.
  • Infinity and wildcard: supports Infinity, Wildcard, and corresponding expression builders expressions::infinity() and expressions::wildcard().
  • Size expressions: adds expressions::record_size() and expressions::memory_size() for granular control.

Take a look at the changelog for more details.

What’s coming next?

We are working toward full functional parity with our other officially supported clients. Features on the roadmap include:

  • Partition queries
  • Distributed ACID transactions
  • Strong consistency

Getting started

Prerequisites:

  • Aerospike Database 6.4 or later.
  • Rust version 1.87 or later
  • Tokio runtime or async-std

Installation

Build from source

  1. Clone the repository and change into the project directory:

    bash
    git clone --single-branch --branch v2 https://github.com/aerospike/aerospike-client-rust.git
    cd aerospike-client-rust
  2. Build the project:

    cargo build

Use as a dependency

To use the client in your own project, add one of the following to your Cargo.toml:

…

Then run cargo build in your project.

Core feature examples

The following code examples demonstrate some of the Rust client's new features.

Client connection

The examples below use the async client (default). For a blocking API with no .await, see Sync client below.

Standard connection

Connect to an Aerospike cluster without TLS:

rust
use std::env;
use aerospike::{Client, ClientPolicy};

let policy = ClientPolicy::default();
let hosts = env::var("AEROSPIKE_HOSTS")
    .unwrap_or_else(|_| "127.0.0.1:3000".to_string());
let client = Client::new(&policy, &hosts)
    .await
    .expect("Failed to connect to cluster");

Sync client

The sync feature exposes blocking APIs — no async/.await at call sites. However, the client still uses Tokio internally for cluster management, so a Tokio runtime must be running for the duration of your program.

Cargo.toml

toml
[dependencies]
aerospike = { version = "", default-features = false, features = ["rt-tokio", "sync"] }
tokio = { version = "1", features = ["full"] }  # required even for sync usage

Swap rt-tokio for rt-async-std if your project uses async-std instead.

Example:

…

Why does sync need a Tokio runtime? The sync feature wraps the async client and provides blocking call sites — it does not replace the underlying async runtime. Cluster tending (node discovery, connection pooling) runs as a background Tokio task regardless of which API surface you use. Calling Client::new outside of a runtime context will panic with there is no reactor running.

TLS connection without client authentication

Connect to an Aerospike cluster with TLS but without client certificate authentication:

…

TLS connection with client authentication

Connect to an Aerospike cluster with TLS and mutual authentication using client certificates:

…

Note: To use TLS features, enable the tls feature in your Cargo.toml:

toml
[dependencies]
aerospike = { version = "...", features = ["tls"] }

CRUD operations

…

Batch operations

…

A complete working example can be found in examples/batch_operations.rs.

Query operations

The Rust client supports various query patterns for retrieving data from Aerospike. Below are examples demonstrating different query capabilities.

Simple equality query

Query records where a bin equals a specific value:

rust
use aerospike::{QueryPolicy, Statement, Bins};
use aerospike::query::PartitionFilter;

let policy = QueryPolicy::default();
let mut stmt = Statement::new(namespace, set_name, Bins::All);
stmt.add_filter(as_eq!("bin_name", 5));

let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();

while let Some(r) = rs.next().await {
    println!("Record: {:?}", r.unwrap());
}

Range query

Query records where a bin value falls within a range:

rust
let policy = QueryPolicy::default();
let mut stmt = Statement::new(namespace, set_name, Bins::All);
stmt.add_filter(as_range!("bin_name", 0, 100));

let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();

while let Some(r) = rs.next().await {
    println!("Record: {:?}", r.unwrap());
}

Metadata-only query

Query records but only retrieve metadata (no bin data):

rust
let policy = QueryPolicy::default();
let mut stmt = Statement::new(namespace, set_name, Bins::None);
stmt.add_filter(as_range!("bin_name", 0, 100));

let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();

while let Some(r) = rs.next().await {
    let rec = r.unwrap();
    println!("Generation: {}, TTL: {}", rec.generation, rec.expiration);
}

Cursor-based pagination

Query records in batches using partition cursors for pagination:

rust
let policy = QueryPolicy::default();
let mut pf = PartitionFilter::all();

while !pf.done() {
    let stmt = Statement::new(namespace, set_name, Bins::All);
    let rs = client.query(&policy, pf, stmt).await.unwrap();
    let mut rs = rs.into_stream();
    
    while let Some(r) = rs.next().await {
        println!("Record: {:?}", r.unwrap());
    }
    
    // Get the next partition filter to continue pagination
    pf = rs.partition_filter().await.unwrap();
}

Parallel query with multiple consumers

Process query results in parallel using multiple async tasks:

…

Query with expression filter

Use filter expressions for more complex filtering logic:

rust
use aerospike_core::expressions::{eq, int_bin, int_val};

let mut policy = QueryPolicy::default();
policy.base_policy.filter_expression.replace(
    eq(int_bin("bin_name".to_string()), int_val(42))
);

let stmt = Statement::new(namespace, set_name, Bins::All);
let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();

while let Some(r) = rs.next().await {
    println!("Record: {:?}", r.unwrap());
}

Rate-limited query

Control query throughput by limiting records per second:

rust
let mut policy = QueryPolicy::default();
policy.records_per_second = 100;  // Limit to 100 records/second

let mut stmt = Statement::new(namespace, set_name, Bins::All);
stmt.add_filter(as_range!("bin_name", 0, 1000));

let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();

while let Some(r) = rs.next().await {
    match r {
        Ok(rec) => println!("Record: {:?}", rec),
        Err(err) => eprintln!("Error: {:?}", err),
    }
}

Prerequisites for queries

Before running queries, you need to create a secondary index on the bin you want to query:

rust
use aerospike_core::{AdminPolicy, IndexType, CollectionIndexType};

let policy = AdminPolicy::default();
let task = client
    .create_index_on_bin(
        &policy,
        namespace,
        set_name,
        "bin_name",
        "idx_bin_name",
        IndexType::Numeric,
        CollectionIndexType::Default,
        None,
    )
    .await
    .expect("Failed to create index");

// Wait for index creation to complete
task.wait_till_complete(None).await.unwrap();

For a complete working example with all query patterns, see examples/query.rs.

Timeout configuration

The Rust client provides flexible timeout configuration through socket_timeout and total_timeout parameters in policies. Understanding how these interact is crucial for handling network issues and controlling command execution time.

Timeout parameters

  • socket_timeout: Socket idle timeout when processing a database command (in milliseconds). Default value 5000 (5 seconds).
  • total_timeout: Total command timeout, including retries (in milliseconds). Default value 0.

Timeout behavior rules

  1. Both zero (0, 0): No timeout limits - commands wait indefinitely
  2. Socket zero, total non-zero (0, N): socket_timeout inherits total_timeout value
  3. Socket non-zero, total zero (N, 0): Socket idle timeout of N ms, no total limit
  4. Both non-zero, socket > total (N, M where N > M): socket_timeout capped at total_timeout
  5. Both non-zero, socket ≤ total (N, M where N ≤ M): Both timeouts enforced independently

When a socket timeout occurs, the client checks max_retries and total_timeout. If neither is exceeded, the command is automatically retried.

Rust client exposes these parameters through the Read/Write policy, and can be tuned as below:

rust
use aerospike::{ReadPolicy, Bins};

let mut policy = ReadPolicy::default();
policy.base_policy.socket_timeout = 0;
policy.base_policy.total_timeout = 0;

let rec = client.get(&policy, &key, Bins::All).await;

Socket recovery with timeout_delay

The timeout_delay parameter controls how the client handles sockets after a read timeout. This is particularly important for cloud deployments.

rust
let mut policy = ReadPolicy::default();
policy.base_policy.socket_timeout = 2000;  // 2 second socket timeout
policy.base_policy.total_timeout = 10000;  // 10 second total timeout
policy.base_policy.timeout_delay = 3000;   // 3 second delay for socket recovery

let rec = client.get(&policy, &key, Bins::All).await;

How timeout_delay works:

  1. When timeout_delay = 0 (default): Socket is immediately closed on timeout
  2. When timeout_delay > 0: After a socket read timeout, the client attempts to drain remaining data from the socket in the background for up to timeout_delay milliseconds
    • If all data is drained within the delay: Socket returned to connection pool (reusable)
    • If delay expires before draining completes: Socket is closed

Why use timeout_delay?

Many cloud providers experience performance issues when clients close sockets while the server still has data to write (results in TCP RST packets). Draining the socket before closing avoids this penalty.

Trade-offs:

  • ✓ Avoids TCP RST performance penalties on cloud platforms
  • ✓ Allows socket reuse when recovery is successful
  • ✗ Requires extra processing to d

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustaerospikedatabase-drivernosqlrust

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库