Skip to content

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 behavior
Session session = cluster.createSession(Behavior.DEFAULT);
// All operations use DEFAULT settings by default
RecordStream 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()

Behavior profiles

Use these common behavior profiles as starting points:

BehaviorBest ForCharacteristics
DEFAULTGeneral purposeBuilt-in baseline behavior
READ_FAST (derived)Read-heavy workloadsLower latency with much shorter timeouts, with retries packed into a far smaller time budget
STRICT_READS (Java derived) / STRICTLY_CONSISTENT (Python built-in)SC workloadsLinearizable 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)

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)

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)

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 it
Session session = cluster.createSession(fastReads);

📖 API reference: Cluster.createSession(Behavior)

Available configuration options (Java)

Setting goalJava behavior method
End-to-end call timeoutabandonCallAfter(Duration)
Retry countmaximumNumberOfCallAttempts(int)
Delay between retriesdelayBetweenRetries(Duration)
AP read modereadMode(ReadModeAP)
SC read modeconsistency(ReadModeSC)
AP write durabilitycommitLevel(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, then reads / writes.
  • Consistency mode: reads_ap / reads_sc / writes_ap / writes_sc for 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_query for 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 goalPython behavior fields
End-to-end call timeoutSettings(total_timeout=timedelta(...))
Retry count (attempts minus one)Settings(max_retries=int)
Delay between retriesSettings(retry_delay=timedelta(...))
AP read modeSettings(read_mode_ap=ReadModeAP)
SC read modeSettings(read_mode_sc=ReadModeSC)
AP write durabilitySettings(commit_level=CommitLevel)
All readsreads=Settings(...)
Single-key (point) read scopereads_point=Settings(...)
Batch read scopereads_batch=Settings(...)
Query read scopereads_query=Settings(...)
AP read scopereads_ap=Settings(...)
SC read scopereads_sc=Settings(...)
All writeswrites=Settings(...)
Retryable write scopewrites_retryable=Settings(...)
Non-retryable write scopewrites_non_retryable=Settings(...)
Single-key (point) write scopewrites_point=Settings(...)
Batch write scopewrites_batch=Settings(...)
Query write scopewrites_query=Settings(...)
AP write scopewrites_ap=Settings(...)
SC write scopewrites_sc=Settings(...)
Transaction verify commandssystem_txn_verify=Settings(...)
Transaction roll forward/back commandssystem_txn_roll=Settings(...)
All operations scopeall=Settings(...)

Python recipes for common behavior tasks

Use these patterns directly when deriving behaviors in Python:

from datetime import timedelta
from aerospike_sdk import Behavior
from 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:

  • kind is an OpKind: READ, WRITE_RETRYABLE, or WRITE_NON_RETRYABLE.
  • shape is an OpShape: POINT, BATCH, or QUERY.
  • mode is a Mode: AP or SC. The default is AP.

The result is a Settings value with every layered scope already resolved:

from datetime import timedelta
from aerospike_sdk import Behavior
from 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_100MS
print(read_100ms.parent.name) # DEFAULT
# Settings that apply to single-key reads
print(Behavior.DEFAULT.get_settings(OpKind.READ, OpShape.POINT).total_timeout) # 0:00:01
print(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:

  • kind is a Behavior.OpKind: READ, WRITE_RETRYABLE, or WRITE_NON_RETRYABLE for application operations. The enum also has SYSTEM_TXN_VERIFY and SYSTEM_TXN_ROLL, which cover the verify and roll operations of a transaction.
  • shape is a Behavior.OpShape: POINT, BATCH, or QUERY for application operations. The enum also has SYSTEM, which pairs with the two transaction kinds, and ANY, a wildcard that behavior selectors use to match every shape.
  • mode is a Behavior.Mode: AP or CP. CP is the Java name for strong-consistency (SC) namespaces, which the Python SDK calls SC. Mode.ANY also 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_100MS
System.out.println(read100ms.getParent().getName()); // DEFAULT
// Settings that apply to single-key reads in an AP namespace
System.out.println(Behavior.DEFAULT.getSettings(OpKind.READ, OpShape.POINT, Mode.AP)
.getAbandonCallAfterMs()); // 1000
System.out.println(read100ms.getSettings(OpKind.READ, OpShape.POINT, Mode.AP)
.getAbandonCallAfterMs()); // 100

Timeout 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_timeout in Python): Max time for the whole call, across all attempts, before it is abandoned
  • waitForCallToComplete(…) (socket_timeout in Python): Max time for a single attempt
  • maximumNumberOfCallAttempts(…): Max attempts (initial attempt + retries). Python’s max_retries counts retries only, so 5 attempts is max_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

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:

ReadModeAPBehavior
ONEConsult a single copy of the record (Python Behavior.DEFAULT; fastest)
ALLConsult 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):

ReadModeSCBehavior
SESSIONSession consistency (your writes are visible to your reads; default)
LINEARIZELinearizable 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

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 settings
Behavior 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(); // Durable
RecordStream read = session.query(users.id("user-1")).execute(); // Durable
read.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()

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 DEFAULT
RecordStream 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()

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 Behavior
from 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 policy
Session 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()

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));
}
}
}
// Usage
Record 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

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()

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? → DEFAULT

Quick reference

ScenarioRecommended Behavior
User profile lookupsREAD_FAST
Shopping cart updatesDEFAULT
Payment processingcustom critical-write behavior
Real-time game stateREAD_FAST
Audit loggingcustom critical-write behavior
Session managementDEFAULT
Analytics writesDEFAULT
Cache readsREAD_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 slow
Behavior 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 settings
s.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 constantly
Behavior 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 variance
Behavior 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 needs
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)));
Session reads = cluster.createSession(readFast);
Session writes = cluster.createSession(Behavior.DEFAULT);
Session critical = cluster.createSession(criticalWrites);

📖 API reference: Cluster.createSession(Behavior)

Next steps

Connect to Aerospike

Configure your cluster connection.

Connect →