Behaviors
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
Learn how Behaviors decouple operational configuration from business logic, letting you tune performance and reliability without changing your code.
What are behaviors?
A Behavior is a reusable configuration object that defines how operations execute:
- Timeouts — How long to wait for a response
- Retries — How many times to retry on transient failures
- Consistency — Read from master or allow replicas
- Durability — Wait for commits to complete
Instead of scattering timeout and retry settings throughout your code, you define Behaviors once and apply them where needed.
import com.aerospike.client.sdk.RecordStream;
// Create a session with a pre-built behaviorSession session = cluster.createSession(Behavior.DEFAULT);
// All operations use DEFAULT settings by defaultRecordStream stream = session.query(users.id("user-1")).execute();stream.getFirst().ifPresent(r -> { /* ... */ });session.insert(users) .bins("name") .id("user-2").values("Bob") .execute();📖 API reference:
Cluster.createSession(Behavior)|DataSet.id(...)|Session.insert(DataSet)|Session.query(Key)|OperationObjectBuilder.bins(...)|IdValuesBuilder.id(...)|IdValuesRowBuilder.values(...)|ChainableQueryBuilder.execute()|RecordStream.getFirst()
# Create a session with a pre-built behaviorsession = cluster.create_session(Behavior.DEFAULT)
# All operations use DEFAULT settings by defaultrow = await session.query(users.id("user-1")).first()if row is not None: # ... handle the record ... passawait session.insert(users.id("user-2")).put({"name": "Bob"}).execute()📖 API reference:
DataSet.id()|Behavior.DEFAULT|Session.query()|Session.insert()|WriteSegmentBuilder.put()|RecordStream.first()|RecordStream.close()|QueryBuilder.execute()|WriteSegmentBuilder.execute()
Behavior profiles
Use these common behavior profiles as starting points:
| Behavior | Best For | Characteristics |
|---|---|---|
DEFAULT | General purpose | Built-in baseline behavior |
READ_FAST (derived) | Read-heavy workloads | Lower latency with much shorter timeouts, with retries packed into a far smaller time budget |
STRICT_READS (Java derived) / STRICTLY_CONSISTENT (Python built-in) | SC workloads | Linearizable reads for SC namespaces |
DEFAULT
The default choice for most applications. Provides reasonable timeouts and retry behavior for mixed workloads.
Session session = cluster.createSession(Behavior.DEFAULT);
// Typical settings:// - Socket timeout: 30s// - Total timeout: 1000ms// - Max retries: 2// - Read mode: Involve all duplicates (ReadModeAP.ALL; only affects behavior during migrations)📖 API reference:
Cluster.createSession(Behavior)
session = cluster.create_session(Behavior.DEFAULT)
# Built-in Behavior.DEFAULT:# - Socket timeout: 30s# - Total timeout: 1s# - Max retries: 2# - send_key: False# - Read mode: Single copy (ReadModeAP.ONE)📖 API reference:
Behavior.DEFAULT
Use DEFAULT when:
- You’re not sure which behavior to choose
- Your workload is a mix of reads and writes
- You want sensible defaults without fine-tuning
READ_FAST
Optimized for read-heavy applications where speed matters more than perfect consistency.
import java.time.Duration;import com.aerospike.client.sdk.policy.Behavior.Selectors;
Behavior readFast = Behavior.DEFAULT.deriveWithChanges("READ_FAST", builder -> builder .on(Selectors.reads(), ops -> ops .waitForCallToComplete(Duration.ofMillis(50)) .abandonCallAfter(Duration.ofMillis(200)) .maximumNumberOfCallAttempts(4)));Session session = cluster.createSession(readFast);
// Typical settings:// - Socket timeout: 50ms// - Total timeout: 200ms// - Max retries: 3 (4 attempts)// - Read mode: unchanged from DEFAULT (ReadModeAP.ALL; only affects behavior// during migrations). READ_FAST's speed comes from its much shorter// timeouts, not from fewer retries or a different read mode — it actually// allows more retry attempts than DEFAULT, packed into a far smaller// total time budget.📖 API reference:
Cluster.createSession(Behavior)
session = cluster.create_session(Behavior.READ_FAST)
# Built-in Behavior.READ_FAST:# - Socket timeout: 50ms# - Total timeout: 200ms# - Max retries: 3# - Read mode: unchanged from DEFAULT (ReadModeAP.ONE). READ_FAST's speed# comes from its shorter timeouts and higher retry count, not from a# different read mode.📖 API reference:
Behavior
Use READ_FAST when:
- Reading cached or frequently-accessed data
- Milliseconds matter (real-time bidding, gaming)
- You can tolerate an occasional failed read under load, in exchange for lower typical latency
- The cluster is healthy and well-provisioned for the tighter timeouts
CRITICAL_WRITES (custom)
Prioritizes data safety over speed. Use for financial transactions, audit logs, and other critical writes.
import java.time.Duration;import com.aerospike.client.sdk.policy.CommitLevel;import com.aerospike.client.sdk.policy.Behavior.Selectors;
Behavior criticalWrites = Behavior.DEFAULT.deriveWithChanges("CRITICAL_WRITES", builder -> builder .on(Selectors.writes().retryable().point().ap(), ops -> ops .abandonCallAfter(Duration.ofSeconds(5)) .maximumNumberOfCallAttempts(5) .delayBetweenRetries(Duration.ofMillis(50)) .commitLevel(CommitLevel.COMMIT_ALL)) .on(Selectors.writes().nonRetryable().point().ap(), ops -> ops .abandonCallAfter(Duration.ofSeconds(5)) .maximumNumberOfCallAttempts(1) .delayBetweenRetries(Duration.ofMillis(50)) .commitLevel(CommitLevel.COMMIT_ALL)));Session session = cluster.createSession(criticalWrites);
// Typical settings:// - Call timeout: 5000ms per attempt// - Max attempts: 5 (retryable writes), 1 (non-retryable writes)// - Delay between retries: 50ms// - Commit level: All replicas📖 API reference:
Cluster.createSession(Behavior)
from datetime import timedelta
from aerospike_native import CommitLevelfrom aerospike_sdk.policy import Settings
critical_writes = Behavior.DEFAULT.derive_with_changes( "CRITICAL_WRITES", writes_ap=Settings( total_timeout=timedelta(seconds=5), retry_delay=timedelta(milliseconds=50), commit_level=CommitLevel.COMMIT_ALL, ), writes_retryable=Settings(max_retries=4),)session = cluster.create_session(critical_writes)
# Typical settings:# - Total timeout: 5000ms# - Max attempts: 5 (retryable writes), 1 (non-retryable writes keep max_retries=0)# - Delay between retries: 50ms# - Commit level: All replicas📖 API reference:
Behavior.DEFAULT
Use a critical-write custom behavior when:
- Writing financial transactions
- Storing audit logs or compliance data
- You need confirmation that data is safely persisted
- Losing a write would cause business impact
Custom behaviors
Create custom Behaviors when the pre-built options don’t fit your needs:
import java.time.Duration;import com.aerospike.client.sdk.policy.ReadModeAP;import com.aerospike.client.sdk.policy.Behavior.Selectors;
// Build a custom read behavior with explicit Java APIs.Behavior fastReads = Behavior.DEFAULT.deriveWithChanges("READ_FAST_CUSTOM", builder -> builder .on(Selectors.reads().get().ap(), ops -> ops .abandonCallAfter(Duration.ofMillis(100)) .maximumNumberOfCallAttempts(2) .delayBetweenRetries(Duration.ofMillis(5)) .readMode(ReadModeAP.ALL)) .on(Selectors.reads().batch().ap(), ops -> ops .abandonCallAfter(Duration.ofMillis(200)) .maximumNumberOfCallAttempts(3)));
// Use itSession session = cluster.createSession(fastReads);📖 API reference:
Cluster.createSession(Behavior)
from datetime import timedelta
from aerospike_native import ReadModeAPfrom aerospike_sdk import Behaviorfrom aerospike_sdk.policy import Settings
# Build a custom behavior with explicit scope settings.fast_reads = Behavior.DEFAULT.derive_with_changes( "READ_FAST_CUSTOM", reads_point=Settings( total_timeout=timedelta(milliseconds=100), max_retries=1, retry_delay=timedelta(milliseconds=5), read_mode_ap=ReadModeAP.ALL, ), reads_batch=Settings( total_timeout=timedelta(milliseconds=200), max_retries=2, ),)
# Use itsession = cluster.create_session(fast_reads)📖 API reference:
Behavior.DEFAULT
Available configuration options (Java)
| Setting goal | Java behavior method |
|---|---|
| End-to-end call timeout | abandonCallAfter(Duration) |
| Retry count | maximumNumberOfCallAttempts(int) |
| Delay between retries | delayBetweenRetries(Duration) |
| AP read mode | readMode(ReadModeAP) |
| SC read mode | consistency(ReadModeSC) |
| AP write durability | commitLevel(CommitLevel) |
Available configuration options (Python)
Use Settings(...) values with Behavior.derive_with_changes(...) scope kwargs:
Python does not expose a Selectors class. Use scope keyword arguments such as
reads_point=..., reads_ap=..., writes=..., and all=... on derive_with_changes(...).
derive_with_changes(...) scopes reads and writes along independent dimensions, and the scopes
layer rather than intersect. A setting is resolved from the least specific scope to the most
specific one, and a later scope overrides an earlier one wherever both apply:
- All operations:
all, thenreads/writes. - Consistency mode:
reads_ap/reads_sc/writes_ap/writes_scfor Availability (AP) vs. Strong Consistency (SC) namespaces. - Retryability (writes only):
writes_retryable/writes_non_retryable. - Operation shape:
reads_point/reads_batch/reads_query/writes_point/writes_batch/writes_queryfor single-key vs. batch vs. query operations.
There is no single kwarg that means “point AP reads” the way Java’s Selectors.reads().get().ap()
selector chain does. reads_point=... applies to point reads in every mode, reads_ap=... applies
to AP reads of every shape, and setting both covers the union of the two, with the shape scope
winning for point AP reads where they overlap.
| Setting goal | Python behavior fields |
|---|---|
| End-to-end call timeout | Settings(total_timeout=timedelta(...)) |
| Retry count (attempts minus one) | Settings(max_retries=int) |
| Delay between retries | Settings(retry_delay=timedelta(...)) |
| AP read mode | Settings(read_mode_ap=ReadModeAP) |
| SC read mode | Settings(read_mode_sc=ReadModeSC) |
| AP write durability | Settings(commit_level=CommitLevel) |
| All reads | reads=Settings(...) |
| Single-key (point) read scope | reads_point=Settings(...) |
| Batch read scope | reads_batch=Settings(...) |
| Query read scope | reads_query=Settings(...) |
| AP read scope | reads_ap=Settings(...) |
| SC read scope | reads_sc=Settings(...) |
| All writes | writes=Settings(...) |
| Retryable write scope | writes_retryable=Settings(...) |
| Non-retryable write scope | writes_non_retryable=Settings(...) |
| Single-key (point) write scope | writes_point=Settings(...) |
| Batch write scope | writes_batch=Settings(...) |
| Query write scope | writes_query=Settings(...) |
| AP write scope | writes_ap=Settings(...) |
| SC write scope | writes_sc=Settings(...) |
| Transaction verify commands | system_txn_verify=Settings(...) |
| Transaction roll forward/back commands | system_txn_roll=Settings(...) |
| All operations scope | all=Settings(...) |
Python recipes for common behavior tasks
Use these patterns directly when deriving behaviors in Python:
from datetime import timedelta
from aerospike_sdk import Behaviorfrom aerospike_sdk.policy import Settings
# TC-1: 100ms total timeout for single-key (point) reads in every mode.# reads_point scopes by operation shape; reads_ap/reads_sc scope by# consistency mode. Scopes layer, so setting both widens the coverage# rather than narrowing it to point AP reads.tc1_behavior = Behavior.DEFAULT.derive_with_changes( "TC1_READ_100MS", reads_point=Settings(total_timeout=timedelta(milliseconds=100)),)
# TC-2: 3-second retry delay for all operations.tc2_behavior = Behavior.DEFAULT.derive_with_changes( "TC2_ALL_DELAY_3S", all=Settings(retry_delay=timedelta(seconds=3)),)
# TC-3: up to 7 attempts for batch reads.tc3_behavior = Behavior.DEFAULT.derive_with_changes( "TC3_BATCH_READ_RETRIES", reads_batch=Settings(max_retries=6),)📖 API reference:
Behavior.DEFAULT
Behavior derivation does not require running a record read/write. If you add a read to demonstrate usage, ensure your key exists before calling first_or_raise().
For Python batch reads, use query(data_set.ids(...)). For batch deletes, pass the same key list to delete(...).
Read a behavior’s name and settings (Python)
derive_with_changes(...) returns a new behavior and leaves the one you derived from unchanged, so two sessions with different behaviors don’t affect each other.
Use name to read a behavior’s name and parent to read the behavior it derives from.
Call get_settings(kind, shape, mode) to read the settings the SDK applies to one kind of operation:
kindis anOpKind:READ,WRITE_RETRYABLE, orWRITE_NON_RETRYABLE.shapeis anOpShape:POINT,BATCH, orQUERY.modeis aMode:APorSC. The default isAP.
The result is a Settings value with every layered scope already resolved:
from datetime import timedelta
from aerospike_sdk import Behaviorfrom aerospike_sdk.policy import OpKind, OpShape, Settings
read_100ms = Behavior.DEFAULT.derive_with_changes( "READ_100MS", reads_point=Settings(total_timeout=timedelta(milliseconds=100)),)
print(read_100ms.name) # READ_100MSprint(read_100ms.parent.name) # DEFAULT
# Settings that apply to single-key readsprint(Behavior.DEFAULT.get_settings(OpKind.READ, OpShape.POINT).total_timeout) # 0:00:01print(read_100ms.get_settings(OpKind.READ, OpShape.POINT).total_timeout) # 0:00:00.100000📖 API reference:
Behavior.name|Behavior.parent|Behavior.derive_with_changes()|Behavior.get_settings()
Read a behavior’s name and settings (Java)
deriveWithChanges(...) returns a new behavior and leaves the one you derived from unchanged, so two sessions with different behaviors don’t affect each other.
Use getName() to read a behavior’s name and getParent() to read the behavior it derives from.
Call getSettings(kind, shape, mode) to read the settings the SDK applies to one kind of operation:
kindis aBehavior.OpKind:READ,WRITE_RETRYABLE, orWRITE_NON_RETRYABLEfor application operations. The enum also hasSYSTEM_TXN_VERIFYandSYSTEM_TXN_ROLL, which cover the verify and roll operations of a transaction.shapeis aBehavior.OpShape:POINT,BATCH, orQUERYfor application operations. The enum also hasSYSTEM, which pairs with the two transaction kinds, andANY, a wildcard that behavior selectors use to match every shape.modeis aBehavior.Mode:APorCP.CPis the Java name for strong-consistency (SC) namespaces, which the Python SDK callsSC.Mode.ANYalso exists.
The result is a ResolvedSettings value with every layered scope already resolved. Its getters return values in the units shown in the name. For example, getAbandonCallAfterMs() returns the timeout in milliseconds:
import java.time.Duration;import com.aerospike.client.sdk.policy.Behavior;import com.aerospike.client.sdk.policy.Behavior.Mode;import com.aerospike.client.sdk.policy.Behavior.OpKind;import com.aerospike.client.sdk.policy.Behavior.OpShape;import com.aerospike.client.sdk.policy.Behavior.Selectors;
Behavior read100ms = Behavior.DEFAULT.deriveWithChanges("READ_100MS", builder -> builder .on(Selectors.reads().get().ap(), ops -> ops .abandonCallAfter(Duration.ofMillis(100))));
System.out.println(read100ms.getName()); // READ_100MSSystem.out.println(read100ms.getParent().getName()); // DEFAULT
// Settings that apply to single-key reads in an AP namespaceSystem.out.println(Behavior.DEFAULT.getSettings(OpKind.READ, OpShape.POINT, Mode.AP) .getAbandonCallAfterMs()); // 1000System.out.println(read100ms.getSettings(OpKind.READ, OpShape.POINT, Mode.AP) .getAbandonCallAfterMs()); // 100Timeout deep dive
Understanding the two timeout types is crucial:
┌─────────────────────────────────────────────────────────┐│ totalTimeout │├─────────────┬─────────────┬─────────────┬──────────────┤│ Attempt 1 │ Retry 1 │ Retry 2 │ Retry 3 ││ (socket TO) │ (socket TO) │ (socket TO) │ (socket TO) │└─────────────┴─────────────┴─────────────┴──────────────┘- abandonCallAfter(…) (
total_timeoutin Python): Max time for the whole call, across all attempts, before it is abandoned - waitForCallToComplete(…) (
socket_timeoutin Python): Max time for a single attempt - maximumNumberOfCallAttempts(…): Max attempts (initial attempt + retries). Python’s
max_retriescounts retries only, so 5 attempts ismax_retries=4
import java.time.Duration;import com.aerospike.client.sdk.policy.Behavior.Selectors;
// Example: Allow up to 5 attempts, with a 2-second call cap.Behavior patient = Behavior.DEFAULT.deriveWithChanges("PATIENT", builder -> builder .on(Selectors.reads().get().ap(), ops -> ops .abandonCallAfter(Duration.ofSeconds(2)) .maximumNumberOfCallAttempts(5) .delayBetweenRetries(Duration.ofMillis(25))));📖 API reference:
com.aerospike.client.sdk
from datetime import timedelta
from aerospike_sdk import Behaviorfrom aerospike_sdk.policy import Settings
# Example: Allow up to 5 attempts for single-key reads, with a 2-second total timeout.patient = Behavior.DEFAULT.derive_with_changes( "PATIENT", reads_point=Settings( total_timeout=timedelta(seconds=2), max_retries=4, retry_delay=timedelta(milliseconds=25), ),)📖 API reference:
Behavior.DEFAULT
Read consistency options
For clusters in AP mode (availability-prioritized), ReadModeAP controls how many
copies of a record are consulted — it only makes a difference while a migration is in
progress:
| ReadModeAP | Behavior |
|---|---|
ONE | Consult a single copy of the record (Python Behavior.DEFAULT; fastest) |
ALL | Consult all duplicate copies to get the most current value during a migration (Java Behavior.DEFAULT; slower) |
To spread read load across master and replica nodes instead — trading a small chance of
reading a slightly-behind replica for lower per-node load — use the Replica setting
(for example Replica.MASTER_PROLES or Replica.RANDOM), not ReadModeAP.
For clusters in SC mode (strong consistency):
| ReadModeSC | Behavior |
|---|---|
SESSION | Session consistency (your writes are visible to your reads; default) |
LINEARIZE | Linearizable reads (strongest guarantee, highest latency) |
import com.aerospike.client.sdk.policy.Replica;import com.aerospike.client.sdk.policy.ReadModeSC;import com.aerospike.client.sdk.policy.Behavior.Selectors;
// For AP mode cluster: spread reads across master and replica nodes.Behavior distributedReads = Behavior.DEFAULT.deriveWithChanges("DISTRIBUTED_READS", builder -> builder .on(Selectors.reads().ap(), ops -> ops.replicaOrder(Replica.MASTER_PROLES)));
// For SC mode cluster: linearizable reads.Behavior strictReads = Behavior.DEFAULT.deriveWithChanges("STRICT_READS", builder -> builder .on(Selectors.reads().cp(), ops -> ops.consistency(ReadModeSC.LINEARIZE)));📖 API reference:
com.aerospike.client.sdk
from aerospike_native import Replicafrom aerospike_sdk import Behaviorfrom aerospike_sdk.policy import Settings
# For AP mode cluster: spread reads across master and replica nodesdistributed_reads = Behavior.DEFAULT.derive_with_changes( "DISTRIBUTED_READS", reads_ap=Settings(replica=Replica.MASTER_PROLES))
# For SC mode cluster: linearizable readsstrict_reads = Behavior.STRICTLY_CONSISTENT📖 API reference:
Behavior
Session-level behavior selection
In both SDKs, behavior is selected at session creation time. Use multiple sessions when a subset of operations needs a different behavior:
Session-level (default for all operations)
Set a Behavior when creating the session. All operations inherit it:
import java.time.Duration;import com.aerospike.client.sdk.RecordStream;import com.aerospike.client.sdk.policy.CommitLevel;import com.aerospike.client.sdk.policy.Behavior.Selectors;
// All operations on this session use custom critical-write settingsBehavior criticalWrites = Behavior.DEFAULT.deriveWithChanges("CRITICAL_WRITES", builder -> builder .on(Selectors.writes().ap(), ops -> ops .abandonCallAfter(Duration.ofSeconds(5)) .delayBetweenRetries(Duration.ofMillis(50)) .commitLevel(CommitLevel.COMMIT_ALL)) .on(Selectors.writes().retryable(), ops -> ops .maximumNumberOfCallAttempts(5)));Session session = cluster.createSession(criticalWrites);
session.insert(users) .bins("name") .id("user-1").values("Alice") .execute(); // DurableRecordStream read = session.query(users.id("user-1")).execute(); // Durableread.getFirst().ifPresent(r -> { /* ... */ });read.close();session.delete(users.id("user-1")).execute().close(); // Durable📖 API reference:
Cluster.createSession(Behavior)|DataSet.id(...)|Session.insert(DataSet)|Session.delete(Key)|Session.query(Key)|OperationObjectBuilder.bins(...)|IdValuesBuilder.id(...)|IdValuesRowBuilder.values(...)|ChainableQueryBuilder.execute()|ChainableNoBinsBuilder.execute()|RecordStream.getFirst()|RecordStream.close()
from datetime import timedelta
from aerospike_native import CommitLevelfrom aerospike_sdk import Behaviorfrom aerospike_sdk.policy import Settings
# All operations on this session use custom critical-write settingscritical_writes = Behavior.DEFAULT.derive_with_changes( "CRITICAL_WRITES", writes_ap=Settings( total_timeout=timedelta(seconds=5), retry_delay=timedelta(milliseconds=50), commit_level=CommitLevel.COMMIT_ALL, ), writes_retryable=Settings(max_retries=4),)session = cluster.create_session(critical_writes)
await session.insert(users.id("user-1")).put({"name": "Alice"}).execute() # Durablestream = await session.query(users.id("user-1")).execute() # Durableawait stream.first_or_raise()stream.close()stream = await session.delete(users.id("user-1")).execute() # Durablestream.close()📖 API reference:
DataSet.id()|Behavior.DEFAULT|Session.query()|Session.insert()|Session.delete()|WriteSegmentBuilder.put()|RecordStream.first_or_raise()|RecordStream.close()|QueryBuilder.execute()|WriteSegmentBuilder.execute()
Per-operation behavior choice (dedicated sessions)
Use a dedicated session for operations that need different retry/consistency settings:
import com.aerospike.client.sdk.RecordStream;import com.aerospike.client.sdk.policy.Behavior.Selectors;
// Session uses DEFAULT by default.Session defaultSession = cluster.createSession(Behavior.DEFAULT);
// Most operations use DEFAULTRecordStream q1 = defaultSession.query(users.id("user-1")).execute();q1.getFirst().ifPresent(r -> { /* ... */ });q1.close();
// This specific write uses a dedicated critical-write session.Behavior criticalWrites = Behavior.DEFAULT.deriveWithChanges("CRITICAL_WRITES", builder -> builder .on(Selectors.writes().retryable().point().ap(), ops -> ops.maximumNumberOfCallAttempts(5)));Session criticalSession = cluster.createSession(criticalWrites);criticalSession.upsert(orders) .bins("total") .id("order-1").values(999.99) .execute();
// Back to DEFAULT session.RecordStream q2 = defaultSession.query(users.id("user-2")).execute();q2.getFirst().ifPresent(r -> { /* ... */ });q2.close();📖 API reference:
Cluster.createSession(Behavior)|DataSet.id(...)|OperationObjectBuilder.bins(...)|IdValuesBuilder.id(...)|IdValuesRowBuilder.values(...)|ChainableQueryBuilder.execute()|RecordStream.getFirst()|RecordStream.close()
from aerospike_sdk import Behaviorfrom aerospike_sdk.policy import Settings
# Session uses DEFAULT by defaultsession = cluster.create_session(Behavior.DEFAULT)
# Most operations use DEFAULTrow = await session.query(users.id("user-1")).first()# ... handle row if present ...
# This specific write uses a dedicated critical-write sessioncritical_writes = Behavior.DEFAULT.derive_with_changes( "CRITICAL_WRITES", writes_retryable=Settings(max_retries=4),)critical_session = cluster.create_session(critical_writes)await critical_session.upsert(orders.id("order-1")).put( {"total": 999.99}).execute()
# Back to DEFAULTrow = await session.query(users.id("user-2")).first()# ... handle row if present ...📖 API reference:
DataSet.id()|Behavior.DEFAULT|Session.query()|Session.upsert()|WriteSegmentBuilder.put()|RecordStream.first()|RecordStream.close()|QueryBuilder.execute()|WriteSegmentBuilder.execute()
Derive a session with a different behavior (Python)
session.session_for(behavior) returns a new session on the same cluster that uses behavior. It’s shorthand for cluster.create_session(behavior), and it leaves the original session as it is. Called on a transactional session, it returns a plain session that isn’t part of the transaction. Read the behavior a session uses from its behavior property:
from datetime import timedelta
from aerospike_sdk import Behaviorfrom aerospike_sdk.policy import OpKind, OpShape, Settings
default_session = cluster.create_session(Behavior.DEFAULT)
fast_reads = Behavior.DEFAULT.derive_with_changes( "FAST_READS", reads_point=Settings(total_timeout=timedelta(milliseconds=100)),)fast_session = default_session.session_for(fast_reads)
# Each session reads with its own behavior.for s in (default_session, fast_session): row = await s.query(users.id("user-1")).first() timeout = s.behavior.get_settings(OpKind.READ, OpShape.POINT).total_timeout print(s.behavior.name, timeout)# DEFAULT 0:00:01# FAST_READS 0:00:00.100000📖 API reference:
Session.session_for()|Session.behavior|Cluster.create_session()|Behavior.get_settings()
Derive a session with a different behavior (Java)
session.sessionFor(behavior) returns a new session on the same cluster that uses behavior, and it leaves the original session as it is. Called on a transactional session, it returns a plain session that isn’t part of the transaction. The Javadoc doesn’t state this behavior as a contract, so don’t rely on it across SDK releases. Read the behavior a session uses with getBehavior():
import java.time.Duration;import java.util.List;import com.aerospike.client.sdk.policy.Behavior;import com.aerospike.client.sdk.policy.Behavior.Mode;import com.aerospike.client.sdk.policy.Behavior.OpKind;import com.aerospike.client.sdk.policy.Behavior.OpShape;import com.aerospike.client.sdk.policy.Behavior.Selectors;
Session defaultSession = cluster.createSession(Behavior.DEFAULT);
Behavior fastReads = Behavior.DEFAULT.deriveWithChanges("FAST_READS", builder -> builder .on(Selectors.reads().get().ap(), ops -> ops .abandonCallAfter(Duration.ofMillis(100))));Session fastSession = defaultSession.sessionFor(fastReads);
// Each session reads with its own behavior.for (Session s : List.of(defaultSession, fastSession)) { Behavior behavior = s.getBehavior(); int timeoutMs = behavior.getSettings(OpKind.READ, OpShape.POINT, Mode.AP) .getAbandonCallAfterMs(); System.out.println(behavior.getName() + " " + timeoutMs);}// DEFAULT 1000// FAST_READS 100📖 API reference:
Session.sessionFor()|Session.getBehavior()
Retry strategies
Automatic retries
The Developer SDK automatically retries transient failures based on your Behavior configuration:
import com.aerospike.client.sdk.RecordStream;import com.aerospike.client.sdk.Session;
// DEFAULT behavior: automatic retries per policySession session = cluster.createSession(Behavior.DEFAULT);
// This operation will automatically retry on transient failures (per policy)RecordStream stream = session.query(users.id("user-1")).execute();stream.getFirst().ifPresent(r -> { /* ... */ });📖 API reference:
Cluster.createSession(Behavior)|DataSet.id(...)|Session.query(Key)|ChainableQueryBuilder.execute()|RecordStream.getFirst()
# DEFAULT behavior: automatic retries per policysession = cluster.create_session(Behavior.DEFAULT)
# This operation will automatically retry on transient failures (per policy)stream = await session.query(users.id("user-1")).execute()await stream.first_or_raise()stream.close()📖 API reference:
DataSet.id()|Behavior.DEFAULT|Session.query()|RecordStream.first_or_raise()|RecordStream.close()|QueryBuilder.execute()
Manual retry with backoff
For application-level retries with exponential backoff:
import java.time.Duration;import com.aerospike.client.sdk.Record;import com.aerospike.client.sdk.RecordResult;import com.aerospike.client.sdk.RecordStream;
public <T> T retryWithBackoff(Supplier<T> operation, int maxRetries) { int attempt = 0; long delayMs = 100;
while (true) { try { return operation.get(); } catch (AerospikeException.Timeout | AerospikeException.Connection e) { attempt++; if (attempt >= maxRetries) { throw e; // Exhausted retries }
System.out.println("Retry " + attempt + " after " + delayMs + "ms"); try { Thread.sleep(delayMs); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); }
// Exponential backoff with jitter delayMs = delayMs * 2 + ((long)(Math.random() * 100)); } }}
// UsageRecord user = retryWithBackoff( () -> { try (RecordStream stream = session.query(users.id("user-1")).execute()) { return stream.getFirstRecord(); } }, 5 // Max 5 retries);📖 API reference:
DataSet.id(...)|Session.query(Key)|ChainableQueryBuilder.execute()|RecordStream.getFirstRecord()|AerospikeException
import asyncioimport randomimport time
from aerospike_sdk import ConnectionError, TimeoutError
async def retry_with_backoff(operation, max_retries=5): attempt = 0 delay = 0.1 # 100ms
while True: try: return await operation() except (TimeoutError, ConnectionError): attempt += 1 if attempt >= max_retries: raise # Exhausted retries
print(f"Retry {attempt} after {delay * 1000:.0f}ms") await asyncio.sleep(delay)
# Exponential backoff with jitter delay = delay * 2 + random.uniform(0, 0.1)
# Usageasync def load_user(): stream = await session.query(users.id("user-1")).execute() try: row = await stream.first() return row.record_or_raise() if row is not None else None finally: stream.close()
user = await retry_with_backoff(load_user, max_retries=5)📖 API reference:
DataSet.id()|Session.query()|RecordResult.record_or_raise()|RecordStream.first()|RecordStream.close()|QueryBuilder.execute()
For more information on Aerospike exceptions, see Error handling.
Multiple sessions pattern
A common pattern is to create multiple sessions with different behaviors:
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.policy.Behavior.Selectors;
public class DatabaseService { private final DataSet users = DataSet.of("test", "users"); private final DataSet payments = DataSet.of("test", "payments"); private final Session readSession; private final Session writeSession; private final Session criticalSession;
public DatabaseService(Cluster cluster) { Behavior readFast = Behavior.DEFAULT.deriveWithChanges("READ_FAST", builder -> builder .on(Selectors.reads().get().ap(), ops -> ops.maximumNumberOfCallAttempts(2))); Behavior criticalWrites = Behavior.DEFAULT.deriveWithChanges("CRITICAL_WRITES", builder -> builder .on(Selectors.writes().retryable().point().ap(), ops -> ops.maximumNumberOfCallAttempts(5)));
// Fast reads for user-facing queries this.readSession = cluster.createSession(readFast);
// Standard writes this.writeSession = cluster.createSession(Behavior.DEFAULT);
// Critical operations (payments, audit logs) this.criticalSession = cluster.createSession(criticalWrites); }
public Optional<Record> getUser(String userId) { RecordStream stream = readSession.query(users.id(userId)).execute(); Optional<Record> out = stream.getFirst() .filter(RecordResult::isOk) .map(RecordResult::recordOrThrow); stream.close(); return out; }
public void updatePreferences(String userId, Map<String, Object> prefs) { writeSession.upsert(users) .bins("prefs") .id(userId).values(prefs) .execute(); }
public void recordPayment(String paymentId, double amount) { criticalSession.insert(payments) .bins("amount", "timestamp") .id(paymentId).values(amount, System.currentTimeMillis()) .execute(); }}📖 API reference:
Cluster.createSession(Behavior)|DataSet.of(...)|OperationObjectBuilder.bins(...)|IdValuesBuilder.id(...)|IdValuesRowBuilder.values(...)|ChainableQueryBuilder.execute()|RecordStream.getFirst()|RecordStream.close()|RecordResult.isOk()
import time
from aerospike_sdk import Behavior, DataSetfrom aerospike_sdk.policy import Settings
class DatabaseService: users = DataSet.of("test", "users") payments = DataSet.of("test", "payments")
def __init__(self, cluster): read_fast = Behavior.DEFAULT.derive_with_changes( "READ_FAST", reads_point=Settings(max_retries=1), ) critical_writes = Behavior.DEFAULT.derive_with_changes( "CRITICAL_WRITES", writes_retryable=Settings(max_retries=4), )
# Fast reads for user-facing queries self.read_session = cluster.create_session(read_fast)
# Standard writes self.write_session = cluster.create_session(Behavior.DEFAULT)
# Critical operations (payments, audit logs) self.critical_session = cluster.create_session(critical_writes)
async def get_user(self, user_id): stream = await self.read_session.query(self.users.id(user_id)).execute() row = await stream.first() return row.record if row is not None and row.is_ok else None
async def update_preferences(self, user_id, prefs): await self.write_session.upsert(self.users.id(user_id)).put( {"prefs": prefs} ).execute()
async def record_payment(self, payment_id, amount): await self.critical_session.insert(self.payments.id(payment_id)).put( {"amount": amount, "timestamp": int(time.time() * 1000)} ).execute()📖 API reference:
DataSet.of()|DataSet.id()|Behavior.DEFAULT|Session.query()|Session.upsert()|Session.insert()|WriteSegmentBuilder.put()|RecordStream.first()|RecordStream.close()|QueryBuilder.execute()|WriteSegmentBuilder.execute()
Choosing the right behavior
Use this decision tree:
What type of operation?├── Read operation│ ├── Need maximum resilience to transient errors? → DEFAULT│ └── Speed critical, occasional failed read OK? → READ_FAST│└── Write operation ├── Critical data (payments, audit)? → custom critical-write behavior └── Normal data? → DEFAULTQuick reference
| Scenario | Recommended Behavior |
|---|---|
| User profile lookups | READ_FAST |
| Shopping cart updates | DEFAULT |
| Payment processing | custom critical-write behavior |
| Real-time game state | READ_FAST |
| Audit logging | custom critical-write behavior |
| Session management | DEFAULT |
| Analytics writes | DEFAULT |
| Cache reads | READ_FAST |
Behavior anti-patterns
❌ Don’t: use critical-write settings for everything
import com.aerospike.client.sdk.RecordStream;import com.aerospike.client.sdk.policy.Behavior.Selectors;
// Too conservative—unnecessarily slowBehavior criticalWrites = Behavior.DEFAULT.deriveWithChanges("CRITICAL_WRITES", builder -> builder .on(Selectors.writes().retryable().point().ap(), ops -> ops.maximumNumberOfCallAttempts(5)));Session session = cluster.createSession(criticalWrites);RecordStream s = session.query(users.id("user-1")).execute(); // Reads don't need durable write settingss.getFirst().ifPresent(r -> { /* ... */ });s.close();📖 API reference:
Cluster.createSession(Behavior)|DataSet.id(...)|Session.query(Key)|ChainableQueryBuilder.execute()|RecordStream.getFirst()|RecordStream.close()
❌ Don’t: set zero timeouts
import java.time.Duration;import com.aerospike.client.sdk.policy.Behavior.Selectors;
// Will fail constantlyBehavior bad = Behavior.DEFAULT.deriveWithChanges("BAD_TIMEOUTS", builder -> builder .on(Selectors.all(), ops -> ops.abandonCallAfter(Duration.ZERO)));📖 API reference:
com.aerospike.client.sdk
❌ Don’t: ignore timeouts in production
import java.time.Duration;import com.aerospike.client.sdk.policy.Behavior.Selectors;
// Development might work, production will have network varianceBehavior risky = Behavior.DEFAULT.deriveWithChanges("RISKY_TIMEOUTS", builder -> builder .on(Selectors.all(), ops -> ops.abandonCallAfter(Duration.ofDays(1))));📖 API reference:
com.aerospike.client.sdk
✅ Do: match behavior to operation type
import com.aerospike.client.sdk.policy.Behavior.Selectors;
// Different behaviors for different needsBehavior readFast = Behavior.DEFAULT.deriveWithChanges("READ_FAST", builder -> builder .on(Selectors.reads().get().ap(), ops -> ops.maximumNumberOfCallAttempts(2)));Behavior criticalWrites = Behavior.DEFAULT.deriveWithChanges("CRITICAL_WRITES", builder -> builder .on(Selectors.writes().retryable().point().ap(), ops -> ops.maximumNumberOfCallAttempts(5)));Session reads = cluster.createSession(readFast);Session writes = cluster.createSession(Behavior.DEFAULT);Session critical = cluster.createSession(criticalWrites);📖 API reference:
Cluster.createSession(Behavior)
Next steps
Data Model
Understand namespaces, sets, and records.
Error Handling
Handle timeouts and retries gracefully.
Connect to Aerospike
Configure your cluster connection.
Async Operations
Scale with non-blocking operations.