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

Valkey 8.0 Cluster Failover, Hash Slot Routing & Lua Atomicity Standard

Enforces strict cluster hash tagging, automated MOVED/ASK redirect handling, and non-blocking Lua scripts on Valkey 8.0. Guarantees atomic cross-command execution across multi-threaded I/O boundaries while preventing cluster routing failures and main-thread execution stalls during primary node failover.

Prohibited Anti-Pattern: Un-tagged Multi-Key Lua Execution and Unhandled Cluster Redirects Causing CROSSSLOT Exceptions and Write Starvation During Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Failover, Hash Slot Routing & Lua Atomicity Standard - Enforces strict cluster hash tagging, automated MOVED/ASK redirect handling, and non-blocking Lua scripts on Valkey 8.0. Guarantees atomic cross-command execution across multi-threaded I/O boundaries while preventing cluster routing failures and main-thread execution stalls during primary node failover.
globs: src/lib/cache/**/*.{ts,js}, src/services/valkey/**/*.{ts,js}, src/infrastructure/redis/**/*.{ts,js}, src/infrastructure/valkey/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-io-atomicity-guardrails"
---

# Valkey 8.0 Cluster Failover, Hash Slot Routing & Lua Atomicity Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Un-tagged Multi-Key Lua Execution and Unhandled Cluster Redirects Causing CROSSSLOT Exceptions and Write Starvation During Failover

## System Constraints
You are a Principal Backend Architect enforcing Valkey 8.0 Cluster invariants. Multi-threaded I/O in Valkey parallelizes socket read/write processing across worker threads, but the command execution engine remains strictly single-threaded per shard. You must mandate cluster hash tagging for all multi-key operations and Lua scripts, enforce adaptive topology refreshes on MOVED/ASK redirects, and prohibit long-running scripts that block worker thread pipeline dispatch.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate co-dependent keys with explicit hash tags (e.g., `{tenant:123}:session`, `{tenant:123}:profile`) when using multi-key commands or Lua scripts in Valkey Cluster mode to prevent CROSSSLOT errors.
- Engineers MUST NOT execute Lua scripts that access keys spanning multiple cluster hash slots or dynamic keys calculated at runtime outside the caller's explicit KEYS array.
- Code SHOULD configure Valkey Cluster clients with automatic cluster topology refresh enabled on both interval and redirect error thresholds (e.g., `enableAutoPipelining`, `autoResubscribe: true`, and adaptive refresh on MOVED redirects).
- Services MUST bound Lua script execution times using atomic micro-transactions and MUST NOT execute compute-heavy loops or blocking functions (`redis.call('KEYS', ...)` or unbounded iteration) inside Lua scripts.
- Components NEVER hardcode raw socket reconnection routines without handling `ASK` redirection (issuing `ASKING` before retrying the slot target) versus `MOVED` redirection (updating the client routing table to the new master).

## Bad vs Good Implementations
### Multi-Key Atomic Operation in Valkey Cluster with Hash Tags & Failover Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The standalone client configuration fails to adapt to Valkey 8.0 cluster failovers. Furthermore, passing two untagged keys (`user:${sourceUserId}:balance` and `user:${targetUserId}:balance`) into a Lua script causes deterministic runtime `CROSSSLOT` failures because they resolve to different hash slots across the cluster.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Client connects as standalone without cluster routing.
// Keys hash to arbitrary slots, triggering CROSSSLOT errors in Lua scripts.
// Fails silently or crashes upon master failover.
export class CacheService {
  private client = new Redis('redis://valkey-node-1:6379');

  async transferTokens(sourceUserId: string, targetUserId: string, amount: number): Promise<boolean> {
    // Anti-pattern: keys are not tagged to the same slot
    const script = `
      local src = redis.call('GET', KEYS[1])
      if tonumber(src) >= tonumber(ARGV[1]) then
        redis.call('DECRBY', KEYS[1], ARGV[1])
        redis.call('INCRBY', KEYS[2], ARGV[1])
        return 1
      end
      return 0
    `;
    
    // CRITICAL BUG: Throws 'CROSSSLOT Keys in request don\'t hash to the same slot'
    const result = await this.client.eval(
      script,
      2,
      `user:${sourceUserId}:balance`,
      `user:${targetUserId}:balance`,
      amount
    );
    return result === 1;
  }
}
```

#### Production Standard (Correct)
> **Standard**: By using `{tenant:${tenantId}}` as a hash tag, both keys guarantee identical slot calculation (CRC16 mod 16384). The Cluster client is configured with auto-refresh and retry policies that transparently handle Valkey node failovers, slot migration, and `MOVED`/`ASK` redirects without dropping pipeline traffic.
```typescript
import { Cluster, ClusterNode, ClusterOptions } from 'ioredis';

// PRODUCTION INVARIANT: Use Cluster client with topology refresh and slot hash tags
export class ValkeyClusterService {
  private cluster: Cluster;

  constructor(nodes: ClusterNode[], options?: ClusterOptions) {
    this.cluster = new Cluster(nodes, {
      ...options,
      enableReadyCheck: true,
      scaleReads: 'master',
      slotsRefreshTimeout: 2000,
      // Adaptive topology refresh on MOVED/ASK and failovers
      dnsLookup: (address, callback) => callback(null, address, 4),
      redisOptions: {
        connectTimeout: 5000,
        maxRetriesPerRequest: 3,
      }
    });
  }

  async updateTenantBalances(
    tenantId: string,
    sourceWallet: string,
    targetWallet: string,
    amount: number
  ): Promise<boolean> {
    // Enforce hash tag {tenantId} so both keys deterministically map to the same slot (0-16383)
    const sourceKey = `balance:{tenant:${tenantId}}:${sourceWallet}`;
    const targetKey = `balance:{tenant:${tenantId}}:${targetWallet}`;

    // Lua script executes atomically within the assigned single thread execution phase
    const script = `
      local current = redis.call('GET', KEYS[1])
      if not current or tonumber(current) < tonumber(ARGV[1]) then
        return 0
      end
      redis.call('DECRBY', KEYS[1], ARGV[1])
      redis.call('INCRBY', KEYS[2], ARGV[1])
      return 1
    `;

    const result = await this.cluster.eval(script, 2, sourceKey, targetKey, amount);
    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 Cluster Failover, Hash Slot Routing & Lua Atomicity Standard

Valkey 8.0 Cluster Failover, Hash Slot Routing & Lua Atomicity Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict cluster hash tagging, automated MOVED/ASK redirect handling, and non-blocking Lua scripts on Valkey 8.0. Guarantees atomic cross-command execution across multi-threaded I/O boundaries while preventing cluster routing failures and main-thread execution stalls during primary node failover. 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: Un-tagged Multi-Key Lua Execution and Unhandled Cluster Redirects Causing CROSSSLOT Exceptions and Write Starvation 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 DriftUn-tagged Multi-Key Lua Execution and Unhandled Cluster Redirects Causing CROSSSLOT Exceptions and Write Starvation During FailoverCritical
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 co-dependent keys with explicit hash tags (e.g., `{tenant

Engineers MUST ALWAYS encapsulate co-dependent keys with explicit hash tags (e.g., `{tenant:123}:session`, `{tenant:123}:profile`) when using multi-key commands or Lua scripts in Valkey Cluster mode to prevent CROSSSLOT 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.
2

Engineers MUST NOT execute Lua scripts that access keys spanning multiple cluster hash slots or dynamic keys calculated at runtime outside the caller's explicit KEYS array.

Engineers MUST NOT execute Lua scripts that access keys spanning multiple cluster hash slots or dynamic keys calculated at runtime outside the caller's explicit KEYS array.

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

Code SHOULD configure Valkey Cluster clients with automatic cluster topology refresh enabled on both interval and redirect error thresholds (e.g., `enableAutoPipelining`, `autoResubscribe

Code SHOULD configure Valkey Cluster clients with automatic cluster topology refresh enabled on both interval and redirect error thresholds (e.g., `enableAutoPipelining`, `autoResubscribe: true`, and adaptive refresh on MOVED redirects).

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 bound Lua script execution times using atomic micro-transactions and MUST NOT execute compute-heavy loops or blocking functions (`redis.call('KEYS', ...)` or unbounded iteration) inside Lua scripts.

Services MUST bound Lua script execution times using atomic micro-transactions and MUST NOT execute compute-heavy loops or blocking functions (`redis.call('KEYS', ...)` or unbounded iteration) inside Lua scripts.

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

Components NEVER hardcode raw socket reconnection routines without handling `ASK` redirection (issuing `ASKING` before retrying the slot target) versus `MOVED` redirection (updating the client routing table to the new master).

Components NEVER hardcode raw socket reconnection routines without handling `ASK` redirection (issuing `ASKING` before retrying the slot target) versus `MOVED` redirection (updating the client routing table to the new master).

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 Failover, Hash Slot Routing & Lua Atomicity Standard critical for AI coding assistants?

Enforces strict cluster hash tagging, automated MOVED/ASK redirect handling, and non-blocking Lua scripts on Valkey 8.0. Guarantees atomic cross-command execution across multi-threaded I/O boundaries while preventing cluster routing failures and main-thread execution stalls during primary node failover. 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 (Un-tagged Multi-Key Lua Execution and Unhandled Cluster Redirects Causing CROSSSLOT Exceptions and Write Starvation 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