Skip to content

Use Isolated Execution Scopes

An Isolated Execution Scope provides a dedicated, per-connection state for running WATCH/MULTI/EXEC transactions. GLIDE clients normally multiplex commands over shared connections, which means per-connection state like WATCH cannot be held safely for a single caller. A scope gives you an exclusive connection where your WATCH keys remain valid until you call EXEC.

Use isolated scopes when you need optimistic concurrency control (OCC) — for example, incrementing a counter only if no other client modified it, or implementing compare-and-swap patterns.

Creating a separate client for each transaction isolates WATCH state, but each client opens its own connections (to every node in cluster mode) and repeats connection setup and authentication. A scope gives you the isolation without that cost:

  • Correct optimistic locking: Your WATCH keys stay valid until you call EXEC, because no other caller uses the connection.
  • Lighter and faster than a new client: In cluster mode a scope connects only to the node that owns its key’s slot, not to every node. Released scope connections are reused, so later scopes skip the cost of a new connection.
  • Other callers aren’t held up: Blocking commands, large values, and slow transactions run on the scope’s own connection, so the shared client is unaffected.

If you need an atomic MULTI/EXEC without WATCH, use an atomic batch instead.

import glide.api.GlideClient;
import glide.api.models.scope.IsolatedScope;
GlideClient client = GlideClient.createClient(config).get();
try (IsolatedScope scope = client.scopedConnection(
Duration.ofSeconds(5), "my-key").get()) {
// Use scope for WATCH/MULTI/EXEC
}

The classic optimistic concurrency control pattern works as follows:

  1. Acquire a scope
  2. WATCH the key(s) you intend to modify
  3. Read the current value
  4. Begin a MULTI transaction
  5. Write the new value
  6. EXEC — returns null if any watched key was modified by another client
  7. Retry if EXEC returned null
import glide.api.GlideClient;
import glide.api.models.scope.IsolatedScope;
GlideClient client = GlideClient.createClient(config).get();
for (int attempt = 0; attempt < 10; attempt++) {
try (IsolatedScope scope = client.scopedConnection(
Duration.ofSeconds(5), "counter").get()) {
scope.watch("counter").get();
String val = scope.get("counter").get();
int newVal = (val != null ? Integer.parseInt(val) : 0) + 1;
scope.multi().get();
scope.set("counter", String.valueOf(newVal)).get();
Object result = scope.exec().get();
if (result != null) break; // Success
}
}

Blocking commands honor their own blocking timeout rather than the client’s request timeout, so BLPOP key 0 blocks until an element arrives instead of failing when the request timeout elapses.

If a blocking command times out or its caller cancels it, the scope’s connection is discarded instead of being returned to the pool. Releasing the scope or closing its parent client closes that socket, so a blocked server-side waiter cannot consume a later push.

Java scopes expose command(String command, String... args) for commands without a dedicated scope method. The returned object is decoded using the same response model as ordinary GLIDE commands, including strings, arrays, and maps. Responses larger than 16 KiB are decoded normally.

Object reply = scope.command("COMMAND", "DOCS", "GET").get();

Each client keeps its own pool of scope connections, holding up to 64 concurrent scopes. Acquiring beyond that limit waits for one to be released rather than failing immediately, so release each scope as soon as its transaction completes — a context manager or try/finally is the safest way to guarantee that. The wait ends at the acquire timeout (default 5 s) with a timeout error; causes that waiting cannot fix, such as a closed parent client or an invalid configuration, fail immediately instead of waiting.

When the parent client is configured for IAM authentication, a scope authenticates as the same IAM identity, and re-authenticates on its next command after the token rotates.

Re-authentication is deferred while it cannot be sent — inside an open MULTI (where it would be queued and corrupt the EXEC reply) — and resumes afterwards. If re-authentication fails, the connection is discarded rather than reused, so a scope never continues on a connection that can no longer authenticate.

When using isolated scopes with a cluster client, keep the following in mind:

Pass a routing_key when acquiring the scope. The key is used to determine which cluster node (via CRC16 slot hashing) the scope’s dedicated connection targets. If you omit it, the scope connects to the primary that owns slot 0 and is pinned to the slot of its first keyed command — which is not the same as passing a key that hashes to slot 0, since that constrains the scope to slot 0 from the start.

try (IsolatedScope scope = client.scopedConnection(
Duration.ofSeconds(5), "user:123").get()) {
scope.watch("user:123").get();
// ...
}

All keys used within a scope must hash to the same slot. If you attempt a cross-slot operation, the command will be rejected. Use hash tags (e.g., {user:123}:name and {user:123}:email) to ensure related keys land in the same slot.

A scope’s connection is pinned to the node that owned its slot when the scope was acquired. If the slot moves afterwards (for example during a rebalance), commands return a MOVED error rather than being redirected: a scope carries per-connection state such as WATCH keys and queued MULTI commands, and that state cannot follow a redirect to another node.

Treat it like any other scope failure — release the scope and acquire a new one, which connects to the slot’s current owner. The retry loop shown above handles this without special-casing.

The following apply to the preview release.

These are intentional constraints for this release. Design your application around them.

  • No Pub/Sub: Scoped connections do not support SUBSCRIBE, PSUBSCRIBE, or SSUBSCRIBE. Entering subscribed mode requires a dedicated message handler that a scope does not set up, so messages could never be delivered. Use the main client for Pub/Sub.
  • No MOVED/ASK redirects: By design, as described above — the error surfaces to the caller and the scope must be replaced.
  • Single slot per scope in cluster mode: A scope is pinned to the slot of its routing key, or, when none was passed, to the slot of its first keyed command. Later commands that route to a different slot are rejected with CROSSSLOT, matching the server’s requirement that WATCH and its MULTI/EXEC target the same slot.
  • A scope does not outlive its client: Closing the client, or the pool the client was borrowed from, invalidates any scope still open on it. Further commands on that scope fail.
  • No automatic reconnection: If the connection drops mid-scope, the command fails and the scope becomes unusable. Reconnecting silently would return a connection without the WATCH keys, queued MULTI commands, or tracking registrations the caller is relying on, so an EXEC could commit where it should have aborted. Acquire a new scope instead.
  • Single caller per scope: Only one coroutine or thread should use a scope at a time. Commands on one scope are serialized, but a scope has a single WATCH/MULTI state, so two callers sharing it will see each other’s queued commands and conflicts. Use one scope per caller.

These are being tracked and are expected to be resolved in a future release.

  • Cluster scopes without a routing key can fail with MOVED: In Go and Node.js, a scope acquired without a routing key is not pinned by its first keyed command. If that key’s slot is not on the slot-0 primary, the command fails with MOVED. Always pass a routing key in cluster mode.
  • Scope replies don’t fully match the parent client: Binary values are corrupted or raise, and binary arguments are not supported in Java and Python. Java decodes string, array, and map replies from command(), including responses larger than 16 KiB. In Go and Python, exec() can’t distinguish a WATCH abort from an empty transaction. Server errors are not raised as the binding’s GLIDE error type. Scope connections use RESP2 even when the parent client uses RESP3. Use scopes with string data, and don’t rely on GLIDE error types for errors raised by scope commands.
  • Some connection state carries over to the next scope: Release does not reset AUTH identity, HELLO/RESET protocol changes, CLIENT NO-EVICT, or CLIENT NO-TOUCH. Don’t change connection-level state inside a scope.
  • Go cluster pool clients can’t open a scope: A client borrowed from a Go cluster pool is a standalone client, so ClusterClient.ScopedConnection() is not available on it. Open scopes from a cluster client that is not pool-borrowed.