This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: valkey-8-cluster-threaded-io-failover-invariants

Valkey 8.0 Multi-Threaded I/O, Hash Slot Affinity, and Failover Topology Invariants

Enforces strict hash-tag slot affinity for Lua scripts and multi-key transactions in Valkey 8.0, preventing CROSSSLOT errors across cluster shards. Mandates automated cluster topology refresh and backoff strategies during failovers and slot migrations (handling MOVED and ASK redirects), while guaranteeing compatibility with Valkey 8.0 multi-threaded I/O bounds.

Prohibited Anti-Pattern: Executing Untagged Multi-Key Operations and Failing to Refresh Topology on Failover Slot Redirects

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Multi-Threaded I/O, Hash Slot Affinity, and Failover Topology Invariants - Enforces strict hash-tag slot affinity for Lua scripts and multi-key transactions in Valkey 8.0, preventing CROSSSLOT errors across cluster shards. Mandates automated cluster topology refresh and backoff strategies during failovers and slot migrations (handling MOVED and ASK redirects), while guaranteeing compatibility with Valkey 8.0 multi-threaded I/O bounds.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts, services/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-threaded-io-failover-invariants"
---

# Valkey 8.0 Multi-Threaded I/O, Hash Slot Affinity, and Failover Topology Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing Untagged Multi-Key Operations and Failing to Refresh Topology on Failover Slot Redirects

## System Constraints
You are a Principal Software Architect enforcing Valkey 8.0 Threaded I/O and Cluster Failover standards. You must mandate strict hash-tag affinity for all multi-key operations and atomic Lua scripts to prevent CROSSSLOT runtime aborts. You must enforce production-grade cluster topology discovery, backoff, and redirect handling (MOVED/ASK/TRYAGAIN) to guarantee zero-downtime failover resilience. Disallow direct single-node client instantiations when connecting to clustered Valkey topologies.

## Strict Guidelines
- Engineers MUST ALWAYS enclose common routing identifiers in hash tags (e.g., `{tenant:123}:entity`) for any multi-key commands or Lua script keys to guarantee co-location within the exact same hash slot (0-16383).
- Engineers MUST NOT execute Lua scripts or transactions (`MULTI`/`EXEC`) with dynamically computed keys that span different hash slots, which immediately aborts with `CROSSSLOT Keys in request don't hash to the same slot`.
- Cluster clients MUST be configured with explicit topology refresh triggers on `MOVED` and `CLUSTERDOWN` events, bounded by exponential backoff and jitter, to handle primary node promotions and failover transitions seamlessly.
- Code SHOULD pass all key arguments to Lua scripts explicitly via the `KEYS` array rather than hardcoding or interpolating keys inside script bodies, maintaining determinism under Valkey 8.0 threaded I/O pipelines.
- Services MUST differentiate between `MOVED` redirects (updating internal slot-to-node routing tables) and `ASK` redirects (querying the target node once via an `ASKING` pipeline without mutating the routing cache).
- Components NEVER rely on standalone connection pooling libraries when connecting to Valkey Cluster instances; they must utilize cluster-aware drivers (e.g., Valkey GLIDE or IORedis Cluster mode).

## Bad vs Good Implementations
### Valkey Cluster Multi-Key Lua Execution & Topology Failover Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: 1. Uses a standalone client that cannot handle `MOVED` or `ASK` redirects during primary-to-replica failover.
2. Keys `wallet:src:balance` and `wallet:dst:balance` calculate different CRC16 hashes, resulting in distinct cluster slots. Valkey aborts multi-key operations with a `CROSSSLOT` error.
3. Hardcodes connections to a single cluster node rather than establishing cluster topology discovery.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Using a standalone client against a Valkey cluster node,
// generating keys that violate hash-slot affinity, and ignoring failover redirects.
export async function transferBalanceBad(
  sourceId: string,
  destId: string,
  amount: number
): Promise<boolean> {
  // Standalone client will fail to follow MOVED/ASK redirects on replica promotion
  const client = new Redis('valkey://valkey-node-1.internal:6379');

  // DANGER: Keys do not use hash tags; will hash to different slots -> CROSSSLOT error
  const script = `
    local source_bal = tonumber(redis.call('get', KEYS[1]) or 0)
    if source_bal < tonumber(ARGV[1]) then return 0 end
    redis.call('decrby', KEYS[1], ARGV[1])
    redis.call('incrby', KEYS[2], ARGV[1])
    return 1
  `;

  // This will throw CROSSSLOT error in Valkey Cluster
  const result = await client.eval(
    script,
    2,
    `wallet:${sourceId}:balance`,
    `wallet:${destId}:balance`,
    amount
  );

  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: 1. Uses a true Valkey Cluster client configured with seed nodes, slot refresh, and exponential backoff retry strategies for seamless handling of failovers and `MOVED`/`ASK` redirects.
2. Employs `{tenant:ID}` hash-tag syntax, forcing Valkey to calculate CRC16 exclusively on the tagged partition, guaranteeing both keys reside on the identical hash slot.
3. Disables the offline queue to avoid accumulating stale writes during cluster resharding or node elections.
```typescript
import { Cluster, ClusterNode } from 'ioredis';

const clusterNodes: ClusterNode[] = [
  { host: 'valkey-node-1.internal', port: 6379 },
  { host: 'valkey-node-2.internal', port: 6379 },
  { host: 'valkey-node-3.internal', port: 6379 },
];

// Cluster-aware client with automatic topology discovery and failover recovery
export const valkeyCluster = new Cluster(clusterNodes, {
  clusterRetryStrategy(times: number) {
    // Exponential backoff with jitter on failover / cluster topology changes
    const delay = Math.min(100 * Math.pow(2, times), 2000);
    return delay + Math.random() * 200;
  },
  enableOfflineQueue: false, // Fail-fast on disconnected slots to prevent stale operations
  slotsRefreshTimeout: 2000,
  scaleReads: 'master',      // Valkey 8.0 threaded I/O on primary provides maximum consistency
});

export async function transferTenantBalance(
  tenantId: string,
  sourceAccount: string,
  destAccount: string,
  amount: number
): Promise<boolean> {
  // Invariant: Use {hash-tag} to guarantee slot co-location for both keys
  const sourceKey = `balance:{tenant:${tenantId}}:${sourceAccount}`;
  const destKey = `balance:{tenant:${tenantId}}:${destAccount}`;

  const atomicTransferScript = `
    local src = KEYS[1]
    local dst = KEYS[2]
    local transfer_val = tonumber(ARGV[1])

    local current = tonumber(redis.call('GET', src) or '0')
    if current < transfer_val then
      return 0
    end

    redis.call('DECRBY', src, transfer_val)
    redis.call('INCRBY', dst, transfer_val)
    return 1
  `;

  // Cluster client transparently routes to the exact hash slot calculated by {tenant:ID}
  const result = await valkeyCluster.eval(
    atomicTransferScript,
    2,
    sourceKey,
    destKey,
    amount.toString()
  );

  return result === 1;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Valkey 8.0 Multi-Threaded I/O, Hash Slot Affinity, and Failover Topology Invariants

Valkey 8.0 Multi-Threaded I/O, Hash Slot Affinity, and Failover Topology Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict hash-tag slot affinity for Lua scripts and multi-key transactions in Valkey 8.0, preventing CROSSSLOT errors across cluster shards. Mandates automated cluster topology refresh and backoff strategies during failovers and slot migrations (handling MOVED and ASK redirects), while guaranteeing compatibility with Valkey 8.0 multi-threaded I/O bounds. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Executing Untagged Multi-Key Operations and Failing to Refresh Topology on Failover Slot Redirects Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftExecuting Untagged Multi-Key Operations and Failing to Refresh Topology on Failover Slot RedirectsCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enclose common routing identifiers in hash tags (e.g., `{tenant

Engineers MUST ALWAYS enclose common routing identifiers in hash tags (e.g., `{tenant:123}:entity`) for any multi-key commands or Lua script keys to guarantee co-location within the exact same hash slot (0-16383).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT execute Lua scripts or transactions (`MULTI`/`EXEC`) with dynamically computed keys that span different hash slots, which immediately aborts with `CROSSSLOT Keys in request don't hash to the same slot`.

Engineers MUST NOT execute Lua scripts or transactions (`MULTI`/`EXEC`) with dynamically computed keys that span different hash slots, which immediately aborts with `CROSSSLOT Keys in request don't hash to the same slot`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Cluster clients MUST be configured with explicit topology refresh triggers on `MOVED` and `CLUSTERDOWN` events, bounded by exponential backoff and jitter, to handle primary node promotions and failover transitions seamlessly.

Cluster clients MUST be configured with explicit topology refresh triggers on `MOVED` and `CLUSTERDOWN` events, bounded by exponential backoff and jitter, to handle primary node promotions and failover transitions seamlessly.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD pass all key arguments to Lua scripts explicitly via the `KEYS` array rather than hardcoding or interpolating keys inside script bodies, maintaining determinism under Valkey 8.0 threaded I/O pipelines.

Code SHOULD pass all key arguments to Lua scripts explicitly via the `KEYS` array rather than hardcoding or interpolating keys inside script bodies, maintaining determinism under Valkey 8.0 threaded I/O pipelines.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST differentiate between `MOVED` redirects (updating internal slot-to-node routing tables) and `ASK` redirects (querying the target node once via an `ASKING` pipeline without mutating the routing cache).

Services MUST differentiate between `MOVED` redirects (updating internal slot-to-node routing tables) and `ASK` redirects (querying the target node once via an `ASKING` pipeline without mutating the routing cache).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER rely on standalone connection pooling libraries when connecting to Valkey Cluster instances

Components NEVER rely on standalone connection pooling libraries when connecting to Valkey Cluster instances; they must utilize cluster-aware drivers (e.g., Valkey GLIDE or IORedis Cluster mode).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Valkey 8.0 Multi-Threaded I/O, Hash Slot Affinity, and Failover Topology Invariants critical for AI coding assistants?

Enforces strict hash-tag slot affinity for Lua scripts and multi-key transactions in Valkey 8.0, preventing CROSSSLOT errors across cluster shards. Mandates automated cluster topology refresh and backoff strategies during failovers and slot migrations (handling MOVED and ASK redirects), while guaranteeing compatibility with Valkey 8.0 multi-threaded I/O bounds. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Executing Untagged Multi-Key Operations and Failing to Refresh Topology on Failover Slot Redirects) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Valkey