Connect to Aerospike
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
Learn how to connect to an Aerospike cluster, configure connection options, and create sessions for database operations.
Basic connection
The simplest way to connect to Aerospike:
import com.aerospike.client.sdk.policy.Behavior;import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.Session;
try (Cluster cluster = new ClusterDefinition("localhost", 3000).connect()) { Session session = cluster.createSession(Behavior.DEFAULT); // Use the session...}📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|Cluster.createSession(Behavior)|Cluster.close()
import asyncio
from aerospike_sdk import Behavior, ClusterDefinition
async def main(): async with await ClusterDefinition("localhost", 3000).connect() as cluster: session = cluster.create_session(Behavior.DEFAULT) # Use the session...
asyncio.run(main())📖 API reference:
Behavior.DEFAULT|ClusterDefinition|cluster.create_session
Connection concepts
Cluster vs. session
| Concept | Purpose | Lifecycle |
|---|---|---|
| Cluster | Manages node discovery and pooled network resources | One per application, long-lived |
| Session | Executes operations using a chosen behavior | Created from a cluster, lightweight |
Pattern: Create one Cluster at startup, then create one or more Session objects from it.
Behaviors
A Behavior defines operation semantics (timeouts, retries, and consistency). Most applications start with Behavior.DEFAULT.
| Behavior | Best For |
|---|---|
DEFAULT | General use, balanced defaults |
| Derived behavior | Targeted tuning for a specific workload |
See Behaviors for details.
Connect to multiple hosts
For production clusters, specify multiple seed nodes:
import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.Host;
Cluster cluster = new ClusterDefinition( new Host("node1.example.com", 3000), new Host("node2.example.com", 3000), new Host("node3.example.com", 3000)).connect();📖 API reference:
ClusterDefinition(Host...)|Host(String,int)|Host(String,String,int)|ClusterDefinition.connect()
from aerospike_sdk import ClusterDefinition, Host
cluster = await ClusterDefinition( hosts=[ Host.of("node1.example.com", 3000), Host.of("node2.example.com", 3000), Host.of("node3.example.com", 3000), ]).connect()📖 API reference:
ClusterDefinition|Host
The client discovers cluster topology from seed hosts. You do not need to list every node.
Connect with authentication
For clusters with authentication enabled:
Cluster cluster = new ClusterDefinition("localhost", 3000) .withNativeCredentials("username", "password") .connect();📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|ClusterDefinition.withNativeCredentials(...)
cluster = await ( ClusterDefinition("localhost", 3000) .with_native_credentials("username", "password") .connect())📖 API reference:
ClusterDefinition
String user = System.getenv("AEROSPIKE_USER");String pass = System.getenv("AEROSPIKE_PASSWORD");
Cluster cluster = new ClusterDefinition("localhost", 3000) .withNativeCredentials(user, pass) .connect();📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|ClusterDefinition.withNativeCredentials(...)
import os
user = os.environ.get("AEROSPIKE_USER")password = os.environ.get("AEROSPIKE_PASSWORD")
cluster = await ( ClusterDefinition("localhost", 3000) .with_native_credentials(user, password) .connect())📖 API reference:
ClusterDefinition
Connect with TLS
For TLS-encrypted connections:
Cluster cluster = new ClusterDefinition("secure.example.com", 4333) .withTlsConfig(tls -> tls .tlsName("aerospike-server") // Using PEM files .caFile("/path/to/ca.pem") .clientCertFile("/path/to/client-cert.pem") .clientKeyFile("/path/to/client-key.pem") // Or, to use JKS // .trustStore("/path/to/truststore.jks", "truststorePassword", "JKS") // .keyStore("/path/to/keystore.jks", "keystorePassword", "JKS") ) .connect();📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|ClusterDefinition.withTlsConfig(...)
cluster = await ( ClusterDefinition("secure.example.com", 4333) .with_tls_config_of() .tls_name("aerospike-server") .ca_file("/path/to/ca.pem") .done() .connect())📖 API reference:
TlsBuilder
Connection options
Configure advanced connection settings:
import java.time.Duration;import com.aerospike.client.sdk.ClusterDefinition;
Cluster cluster = new ClusterDefinition("localhost", 3000) .tendTimeout(1000) // milliseconds .loginTimeout(3000) // milliseconds .withSystemSettings(builder -> builder .connections(ops -> ops .minimumConnectionsPerNode(10) .maximumConnectionsPerNode(100) ) .refresh(ops -> ops .tendInterval(Duration.ofSeconds(1)) ) ) .connect();📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|ClusterDefinition.withSystemSettings(...)
from datetime import timedelta
from aerospike_sdk import ClusterDefinitionfrom aerospike_sdk.policy.system_settings import SystemSettings
cluster = await ( ClusterDefinition("localhost", 3000) .with_system_settings( SystemSettings( min_connections_per_node=10, max_connections_per_node=100, conn_pools_per_node=1, tend_interval=timedelta(seconds=1), ) ) .connect())📖 API reference:
SystemSettings
Creating multiple sessions
Create different sessions for different application workflows:
import com.aerospike.client.sdk.policy.Behavior;import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.Session;
Cluster cluster = new ClusterDefinition("localhost", 3000).connect();Behavior reportingBehavior = Behavior.DEFAULT.deriveWithChanges("reporting", builder -> builder .on(Selectors.all(), ops -> ops .abandonCallAfter(Duration.ofSeconds(60)) ));
Session defaultSession = cluster.createSession(Behavior.DEFAULT);Session reportingSession = cluster.createSession(reportingBehavior);📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|Cluster.createSession(Behavior)
from datetime import timedelta
from aerospike_sdk import Behavior, ClusterDefinition
cluster = await ClusterDefinition("localhost", 3000).connect()
reporting_behavior = Behavior.DEFAULT.derive_with_changes( "reporting", total_timeout=timedelta(seconds=60),)
default_session = cluster.create_session(Behavior.DEFAULT)reporting_session = cluster.create_session(reporting_behavior)📖 API reference:
Behavior.DEFAULT|cluster.create_session
Using context managers (Python)
Python supports async context managers for automatic cleanup:
import asynciofrom aerospike_sdk import Behavior, ClusterDefinition
async def main(): async with await ClusterDefinition("localhost", 3000).connect() as cluster: session = cluster.create_session(Behavior.DEFAULT) # Do work...
asyncio.run(main())📖 API reference:
Behavior.DEFAULT|cluster.create_session
Connection lifecycle
Recommended pattern
import com.aerospike.client.sdk.policy.Behavior;import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.Session;
public class App { public static void main(String[] args) { try (Cluster cluster = new ClusterDefinition("localhost", 3000).connect()) { Session session = cluster.createSession(Behavior.DEFAULT); // Do work... } }}📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|Cluster.createSession(Behavior)|Cluster.close()
import asynciofrom aerospike_sdk import Behavior, ClusterDefinition
async def run_app(): async with await ClusterDefinition("localhost", 3000).connect() as cluster: session = cluster.create_session(Behavior.DEFAULT) # Do work...
if __name__ == "__main__": asyncio.run(run_app())📖 API reference:
Behavior.DEFAULT
Complete example
import com.aerospike.client.sdk.policy.Behavior;import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.DataSet;import com.aerospike.client.sdk.Record;import com.aerospike.client.sdk.RecordResult;import com.aerospike.client.sdk.RecordStream;import com.aerospike.client.sdk.Session;import java.util.Optional;
public class ConnectExample { public static void main(String[] args) { DataSet users = DataSet.of("test", "users");
try (Cluster cluster = new ClusterDefinition("localhost", 3000).connect()) { Session session = cluster.createSession(Behavior.DEFAULT);
// Write a record. session.upsert(users) .bins("name", "status", "age") .id("connect-example-user").values("Alice", "active", 28) .execute();
// Read it back. Optional<RecordResult> readBack = session .query(users.id("connect-example-user")) .execute() .getFirst(); readBack.ifPresent(rr -> System.out.println( "Read user: " + rr.recordOrThrow().bins));
// Query active users. RecordStream queryStream = session.query(users) .where("$.status == 'active'") .execute();
queryStream.forEach(recResult -> { Record record = recResult.recordOrThrow(); if (record != null) { System.out.println("Active user: " + record.getString("name")); } });
// Cleanup for repeatable runs. session.delete(users.id("connect-example-user")).execute(); } }}📖 API reference:
ClusterDefinition(String,int)|ClusterDefinition.connect()|Cluster.createSession(Behavior)|Cluster.close()|DataSet.of(...)|DataSet.id(...)|Session.upsert(DataSet)|Session.delete(Key)|Session.query(DataSet)|OperationObjectBuilder.bins(...)|IdValuesBuilder.id(...)|IdValuesRowBuilder.values(...)|ChainableQueryBuilder.where(...)|ChainableQueryBuilder.execute()|RecordStream.getFirst()|RecordStream.forEach(...)|RecordResult.recordOrThrow()|Record.getString(...)
import asyncio
from aerospike_sdk import Behavior, ClusterDefinition, DataSet
async def main(): users = DataSet.of("test", "users")
async with await ClusterDefinition("localhost", 3000).connect() as cluster: session = cluster.create_session(Behavior.DEFAULT)
# Write a record. await session.upsert(key=users.id("connect-example-user")).put( {"name": "Alice", "status": "active", "age": 28} ).execute()
# Read it back. stream = await session.query(users.id("connect-example-user")).execute() row = await stream.first_or_raise() print(f"Read user: {row.record_or_raise().bins}") stream.close()
# Query active users. stream = await session.query(users).where("$.status == 'active'").execute() async for row in stream: if row.is_ok: print(f"Active user: {row.record_or_raise().bins.get('name')}") stream.close()
# Cleanup for repeatable runs. await session.delete(key=users.id("connect-example-user")).execute()
if __name__ == "__main__": asyncio.run(main())📖 API reference:
DataSet.of()|DataSet.id()|Behavior.DEFAULT|Session.query()|Session.upsert()|Session.delete()|QueryBuilder.where()|WriteSegmentBuilder.put()|RecordResult.record_or_raise()|RecordStream.first_or_raise()|RecordStream.close()|QueryBuilder.execute()|WriteSegmentBuilder.execute()
Troubleshooting
Connection refused
Error: Connection refused to localhost:3000Causes:
- Aerospike is not running
- Wrong host or port
- Firewall blocking the connection
Solutions:
- Verify Aerospike is running:
systemctl status aerospikeordocker ps - Check the port: default is
3000for client connections - Test connectivity:
nc -zv localhost 3000
Authentication failed
Error: Authentication failedSolutions:
- Verify credentials are correct
- Check the user has appropriate permissions
- Ensure authentication is enabled on the cluster
TLS handshake failed
Error: SSL handshake failedSolutions:
- Verify certificate paths are correct
- Check certificate expiration:
openssl x509 -enddate -noout -in cert.pem - Ensure CA certificate matches the server’s certificate chain
Next steps
Quickstart
Build your first app in 5 minutes.
Behaviors
Learn about timeouts, retries, and consistency.
Create Records
Start writing data to Aerospike.