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

Valkey 8.0 Cluster Topology, Slot Redirects, and Lua Atomicity Guardrails

Enforces strict cluster slot affinity using hash tags across multi-key operations and Lua scripts in Valkey 8.0, paired with topology-aware connection lifecycle management. Prevents runtime CROSSSLOT errors, stale replica reads during cluster failover elections, and pipeline starvation under multi-threaded I/O loads.

Prohibited Anti-Pattern: Cross-Slot Lua Execution and Unhandled MOVED/ASK Redirects During Valkey Cluster Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Topology, Slot Redirects, and Lua Atomicity Guardrails - Enforces strict cluster slot affinity using hash tags across multi-key operations and Lua scripts in Valkey 8.0, paired with topology-aware connection lifecycle management. Prevents runtime CROSSSLOT errors, stale replica reads during cluster failover elections, and pipeline starvation under multi-threaded I/O loads.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-cluster-failover-multithread-io-standard"
---

# Valkey 8.0 Cluster Topology, Slot Redirects, and Lua Atomicity Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Cross-Slot Lua Execution and Unhandled MOVED/ASK Redirects During Valkey Cluster Failover

## System Constraints
You are a Principal Backend Architect enforcing strict Valkey 8.0 cluster standards. Mandate hash tags for multi-key operations, atomic Lua execution routing, and resilient cluster failover policies handling MOVED/ASK redirects.

## Strict Guidelines
- Engineers MUST ALWAYS enforce uniform hash tags `{...}` across all keys touched by a transaction, pipeline, or Lua script to ensure evaluation within an identical cluster slot.
- Engineers MUST NOT execute Lua scripts or multi-key commands where keys are dynamically constructed inside Lua without being declared in the top-level KEYS array.
- Cluster clients MUST configure automatic topology refresh hooks on MOVED redirects with rate-limited exponential backoff during primary node failover elections.
- Code MUST handle ASK redirects by sending an ASKING pre-command strictly to the target redirected node without invalidating the global cluster slot cache.
- Workloads utilizing Valkey 8.0 multi-threaded I/O MUST maintain client-side pipeline bounds to prevent TCP socket buffer saturation and head-of-line blocking.

## Bad vs Good Implementations
### Cluster-Aware Atomic Token Bucket Rate Limiter with Hash Tagging

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The script accesses an implicit, dynamic key ('audit:' .. ARGV[2]) not in KEYS, breaking Valkey 8.0 cluster routing and atomic validation. Furthermore, bucketKey and auditKey lack hash tags ('{...}'), triggering fatal CROSSSLOT exceptions, and the single-node client does not handle cluster failover or slot migrations.
```typescript
import { Redis } from 'ioredis';

// ANTI-PATTERN: Keys lack cluster hash tags and topology refreshes are disabled.
// This will throw CROSSSLOT errors in Valkey Cluster and fail during replica promotion.
export class RateLimiter {
  private client: Redis;

  constructor() {
    this.client = new Redis('valkey://10.0.0.1:6379');
  }

  async checkRateLimit(userId: string, cost: number): Promise<boolean> {
    // Keys do not guarantee the same cluster slot (no hash tags)
    const bucketKey = `rate:bucket:${userId}`;
    const auditKey = `rate:audit:${userId}`;

    const script = `
      local current = redis.call('GET', KEYS[1]) or 0
      if tonumber(current) >= tonumber(ARGV[1]) then
        redis.call('DECRBY', KEYS[1], ARGV[1])
        -- Dynamically writing to key not declared in KEYS[2]
        redis.call('LPUSH', 'audit:' .. ARGV[2], ARGV[1])
        return 1
      end
      return 0
    `;

    const allowed = await this.client.eval(script, 1, bucketKey, cost, userId);
    return allowed === 1;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Hash tags `{user:${userId}}` force both keys into the same Valkey 8.0 slot, avoiding CROSSSLOT failures. All keys are explicitly listed in KEYS, and the Cluster client configuration handles cluster slot recalculation, MOVED/ASK redirects, and primary election failovers safely.
```typescript
import { Cluster, ClusterNode } from 'ioredis';

// PRODUCTION FIX: Explicit hash tags, complete KEYS declaration, and resilient cluster retry.
export class RateLimiter {
  private cluster: Cluster;

  constructor(nodes: ClusterNode[]) {
    this.cluster = new Cluster(nodes, {
      // Enable automatic cluster slot discovery and dynamic failover recovery
      enableReadyCheck: true,
      scaleReads: 'master',
      slotsRefreshTimeout: 2000,
      redisOptions: {
        connectTimeout: 5000,
        maxRetriesPerRequest: 3,
      },
      retryDelayOnFailover: 100,
      retryDelayOnClusterDown: 250,
    });
  }

  async checkRateLimit(userId: string, cost: number): Promise<boolean> {
    // Enforce hash-tagging so both keys hash deterministically to the identical Valkey cluster slot
    const bucketKey = `{user:${userId}}:rate:bucket`;
    const auditKey = `{user:${userId}}:rate:audit`;

    const script = `
      local current = tonumber(redis.call('GET', KEYS[1]) or '0')
      local required = tonumber(ARGV[1])
      if current >= required then
        redis.call('DECRBY', KEYS[1], required)
        redis.call('LPUSH', KEYS[2], ARGV[1])
        return 1
      end
      return 0
    `;

    // All accessed keys MUST be passed strictly in the KEYS array
    const result = await this.cluster.eval(script, 2, bucketKey, auditKey, cost);
    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 Topology, Slot Redirects, and Lua Atomicity Guardrails

Valkey 8.0 Cluster Topology, Slot Redirects, and Lua Atomicity Guardrails defines an industrial-grade behavioral standard for backend engineering. Enforces strict cluster slot affinity using hash tags across multi-key operations and Lua scripts in Valkey 8.0, paired with topology-aware connection lifecycle management. Prevents runtime CROSSSLOT errors, stale replica reads during cluster failover elections, and pipeline starvation under multi-threaded I/O loads. 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: Cross-Slot Lua Execution and Unhandled MOVED/ASK Redirects During Valkey Cluster 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 DriftCross-Slot Lua Execution and Unhandled MOVED/ASK Redirects During Valkey Cluster 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 enforce uniform hash tags `{...}` across all keys touched by a transaction, pipeline, or Lua script to ensure evaluation within an identical cluster slot.

Engineers MUST ALWAYS enforce uniform hash tags `{...}` across all keys touched by a transaction, pipeline, or Lua script to ensure evaluation within an identical cluster 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.
2

Engineers MUST NOT execute Lua scripts or multi-key commands where keys are dynamically constructed inside Lua without being declared in the top-level KEYS array.

Engineers MUST NOT execute Lua scripts or multi-key commands where keys are dynamically constructed inside Lua without being declared in the top-level 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

Cluster clients MUST configure automatic topology refresh hooks on MOVED redirects with rate-limited exponential backoff during primary node failover elections.

Cluster clients MUST configure automatic topology refresh hooks on MOVED redirects with rate-limited exponential backoff during primary node failover elections.

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 MUST handle ASK redirects by sending an ASKING pre-command strictly to the target redirected node without invalidating the global cluster slot cache.

Code MUST handle ASK redirects by sending an ASKING pre-command strictly to the target redirected node without invalidating the global cluster slot 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.
5

Workloads utilizing Valkey 8.0 multi-threaded I/O MUST maintain client-side pipeline bounds to prevent TCP socket buffer saturation and head-of-line blocking.

Workloads utilizing Valkey 8.0 multi-threaded I/O MUST maintain client-side pipeline bounds to prevent TCP socket buffer saturation and head-of-line blocking.

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

Enforces strict cluster slot affinity using hash tags across multi-key operations and Lua scripts in Valkey 8.0, paired with topology-aware connection lifecycle management. Prevents runtime CROSSSLOT errors, stale replica reads during cluster failover elections, and pipeline starvation under multi-threaded I/O loads. 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 (Cross-Slot Lua Execution and Unhandled MOVED/ASK Redirects During Valkey Cluster 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