This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: valkey-8-cluster-slot-redirect-and-lua-atomicity

Valkey 8.0 Cluster Slot Routing, Failover Redirects, and Lua Atomicity Guardrails

Enforces strict hash-tag slot pinning for all multi-key operations and Lua scripts, paired with robust MOVED/ASK redirect handling and dynamic topology refreshes during Valkey 8.0 cluster failovers. Prevents CROSSSLOT runtime exceptions, socket stalls during threaded I/O parallel processing, and cascading failover dropouts.

Prohibited Anti-Pattern: Executing unpinned multi-key Lua scripts without hash tags and omitting cluster redirect/topology refresh logic during failover.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Slot Routing, Failover Redirects, and Lua Atomicity Guardrails - Enforces strict hash-tag slot pinning for all multi-key operations and Lua scripts, paired with robust MOVED/ASK redirect handling and dynamic topology refreshes during Valkey 8.0 cluster failovers. Prevents CROSSSLOT runtime exceptions, socket stalls during threaded I/O parallel processing, and cascading failover dropouts.
globs: src/**/*.{ts,js}, lib/**/*.{ts,js}, src/cache/**/*.{ts,js}, src/services/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-slot-redirect-and-lua-atomicity"
---

# Valkey 8.0 Cluster Slot Routing, Failover Redirects, and Lua Atomicity Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing unpinned multi-key Lua scripts without hash tags and omitting cluster redirect/topology refresh logic during failover.

## System Constraints
You are a Principal Engineer enforcing Valkey 8.0 Threaded I/O & Cluster Failover standards. In Valkey 8.0, Threaded I/O parallelizes socket read/write processing while maintaining single-threaded command execution. In cluster topologies, operations spanning multiple keys or executed via Lua scripts (EVAL/EVALSHA) or atomic functions MUST resolve to the exact same hash slot via bracketed hash tags (e.g., `{entityId}:suffix`). You must enforce automated topology discovery, dynamic MOVED/ASK redirect recovery, and bounded jittered retry policies during primary-to-replica failover.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate shared shard identifiers in curly brackets (`{entityId}`) for any multi-key command, MGET, MSET, transaction, or Lua script.
- Engineers MUST NOT issue multi-key commands or Lua scripts without hash tags in a Valkey 8.0 Cluster environment, as this triggers unrecoverable `CROSSSLOT Keys in request don't hash to the same slot` errors.
- Cluster client configurations MUST specify explicit topology refresh intervals (`slotsRefreshTimeout`, `dnsLookup`, periodic refresh) and listen to `MOVED` and `ASK` redirects with automatic routing cache invalidation.
- Services MUST implement bounded exponential backoff with full jitter for cluster redirection retries to accommodate replica promotion latency during automated failovers.
- Engineers MUST NEVER execute blocking commands (e.g., `BLPOP`, `BRPOP`, `BUSY` loops) inside Lua scripts or high-throughput threaded I/O pipelines, as thread contention stalls network write buffers.

## Bad vs Good Implementations
### Cluster-Aware Atomic Lua Script with Slot Pinning and Failover Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The script specifies keys without hash tags (`{...}`), causing Valkey Cluster to map them to different hash slots and terminate with a CROSSSLOT error. Additionally, the cluster client lacks topology refresh on failover (`slotsRefreshTimeout`, retry strategies), causing dropped operations during primary promotion.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Disparate hash slots trigger CROSSSLOT errors in cluster mode.
// Missing failover configuration causes connection dropouts during node promotion.
export const valkey = new Redis.Cluster([
  { host: 'valkey-node-1.internal', port: 6379 }
]);

export async function transferBalance(senderId: string, recipientId: string, amount: number) {
  const script = `
    local senderBal = redis.call('GET', KEYS[1])
    if not senderBal or tonumber(senderBal) < tonumber(ARGV[1]) then
      return -1
    end
    redis.call('DECRBY', KEYS[1], ARGV[1])
    redis.call('INCRBY', KEYS[2], ARGV[1])
    return 0
  `;

  // BUG: KEYS[1] and KEYS[2] map to completely different hash slots across nodes.
  // This throws CROSSSLOT and cannot execute atomically in Valkey Cluster.
  return await valkey.eval(
    script,
    2,
    `user:${senderId}:balance`,
    `user:${recipientId}:balance`,
    amount
  );
}
```

#### Production Standard (Correct)
> **Standard**: Keys enforce bracketed hash tags (`{tenant:${tenantId}:wallet:${walletId}}`), guaranteeing placement within identical slots and safe atomic execution. The cluster is configured with dynamic topology discovery, replica read offloading, and bounded jitter retries to handle node migrations and master failovers without dropping traffic.
```typescript
import { Cluster, ClusterNode, ClusterOptions } 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 }
];

const clusterOptions: ClusterOptions = {
  maxRedirections: 16,
  slotsRefreshTimeout: 2000,
  enableReadyCheck: true,
  scaleReads: 'slave',
  clusterRetryStrategy: (times: number) => {
    // Bounded exponential backoff with full jitter to handle failover transition
    const delay = Math.min(100 * Math.pow(2, times), 3000);
    return Math.floor(Math.random() * delay);
  },
  redisOptions: {
    connectTimeout: 5000,
    keepAlive: 30000,
    commandTimeout: 2500
  }
};

export const valkeyCluster = new Cluster(clusterNodes, clusterOptions);

export async function updateWalletAndLedger(
  tenantId: string,
  walletId: string,
  delta: number
): Promise<number> {
  // INVARIANT: Curly brackets guarantee {tenantId:walletId} hashes to the exact same slot
  const balanceKey = `{tenant:${tenantId}:wallet:${walletId}}:balance`;
  const journalKey = `{tenant:${tenantId}:wallet:${walletId}}:journal`;

  const atomicDebitScript = `
    local current = redis.call('GET', KEYS[1])
    local balance = current and tonumber(current) or 0
    local change = tonumber(ARGV[1])
    
    if change < 0 and (balance + change) < 0 then
      return -1
    end
    
    local newBal = redis.call('INCRBY', KEYS[1], change)
    redis.call('LPUSH', KEYS[2], ARGV[2])
    return newBal
  `;

  const payload = JSON.stringify({ delta, timestamp: Date.now() });
  
  return (await valkeyCluster.eval(
    atomicDebitScript,
    2,
    balanceKey,
    journalKey,
    delta,
    payload
  )) as number;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Valkey 8.0 Cluster Slot Routing, Failover Redirects, and Lua Atomicity Guardrails

Valkey 8.0 Cluster Slot Routing, Failover Redirects, and Lua Atomicity Guardrails defines an industrial-grade behavioral standard for backend engineering. Enforces strict hash-tag slot pinning for all multi-key operations and Lua scripts, paired with robust MOVED/ASK redirect handling and dynamic topology refreshes during Valkey 8.0 cluster failovers. Prevents CROSSSLOT runtime exceptions, socket stalls during threaded I/O parallel processing, and cascading failover dropouts. 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 unpinned multi-key Lua scripts without hash tags and omitting cluster redirect/topology refresh logic during failover. 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 unpinned multi-key Lua scripts without hash tags and omitting cluster redirect/topology refresh logic during failover.Critical
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 encapsulate shared shard identifiers in curly brackets (`{entityId}`) for any multi-key command, MGET, MSET, transaction, or Lua script.

Engineers MUST ALWAYS encapsulate shared shard identifiers in curly brackets (`{entityId}`) for any multi-key command, MGET, MSET, transaction, or Lua script.

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 issue multi-key commands or Lua scripts without hash tags in a Valkey 8.0 Cluster environment, as this triggers unrecoverable `CROSSSLOT Keys in request don't hash to the same slot` errors.

Engineers MUST NOT issue multi-key commands or Lua scripts without hash tags in a Valkey 8.0 Cluster environment, as this triggers unrecoverable `CROSSSLOT Keys in request don't hash to the same slot` errors.

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 client configurations MUST specify explicit topology refresh intervals (`slotsRefreshTimeout`, `dnsLookup`, periodic refresh) and listen to `MOVED` and `ASK` redirects with automatic routing cache invalidation.

Cluster client configurations MUST specify explicit topology refresh intervals (`slotsRefreshTimeout`, `dnsLookup`, periodic refresh) and listen to `MOVED` and `ASK` redirects with automatic routing cache invalidation.

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

Services MUST implement bounded exponential backoff with full jitter for cluster redirection retries to accommodate replica promotion latency during automated failovers.

Services MUST implement bounded exponential backoff with full jitter for cluster redirection retries to accommodate replica promotion latency during automated failovers.

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

Engineers MUST NEVER execute blocking commands (e.g., `BLPOP`, `BRPOP`, `BUSY` loops) inside Lua scripts or high-throughput threaded I/O pipelines, as thread contention stalls network write buffers.

Engineers MUST NEVER execute blocking commands (e.g., `BLPOP`, `BRPOP`, `BUSY` loops) inside Lua scripts or high-throughput threaded I/O pipelines, as thread contention stalls network write buffers.

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 Cluster Slot Routing, Failover Redirects, and Lua Atomicity Guardrails critical for AI coding assistants?

Enforces strict hash-tag slot pinning for all multi-key operations and Lua scripts, paired with robust MOVED/ASK redirect handling and dynamic topology refreshes during Valkey 8.0 cluster failovers. Prevents CROSSSLOT runtime exceptions, socket stalls during threaded I/O parallel processing, and cascading failover dropouts. 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 unpinned multi-key Lua scripts without hash tags and omitting cluster redirect/topology refresh logic during failover.) 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