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

Valkey 8.0 Cluster Topology, Failover Redirection, and Multi-Key Script Invariants

Enforces strict production invariants for Valkey 8.0 clusters utilizing asynchronous multi-threaded I/O, hash-tagged atomic multi-key Lua scripts, and resilient slot topology refresh handling on MOVED and ASK cluster redirects during failover.

Prohibited Anti-Pattern: Executing un-tagged multi-key operations or blocking Lua scripts under threaded I/O while mishandling cluster slot migrations and failover redirections.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Topology, Failover Redirection, and Multi-Key Script Invariants - Enforces strict production invariants for Valkey 8.0 clusters utilizing asynchronous multi-threaded I/O, hash-tagged atomic multi-key Lua scripts, and resilient slot topology refresh handling on MOVED and ASK cluster redirects during failover.
globs: src/**/*.ts, lib/**/*.ts, services/**/*.ts, infrastructure/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-failover-io-threading-guardrails"
---

# Valkey 8.0 Cluster Topology, Failover Redirection, and Multi-Key Script Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing un-tagged multi-key operations or blocking Lua scripts under threaded I/O while mishandling cluster slot migrations and failover redirections.

## System Constraints
You are a Principal Backend Architect enforcing Valkey 8.0 Threaded I/O, Cluster Routing, and High-Availability Failover invariants. You must mandate strict cluster slot awareness, non-blocking operations to avoid stalling the main event loop while threaded I/O buffers queue, explicit hash-tagging for multi-key atomicity, and resilient handling of MOVED/ASK redirects.

## Strict Guidelines
- Engineers MUST ALWAYS use Redis/Valkey Hash Tags (e.g., `{tenant:123}:entity`) for all multi-key operations, transactions, and Lua scripts to guarantee keys map to the identical CRC16 hash slot.
- Engineers MUST NOT execute Lua scripts or complex multi-key commands with execution profiles exceeding 5ms, as Valkey 8.0 threaded I/O only offloads socket reads/writes while script execution remains bound to the single-threaded coordinator core.
- Services MUST configure cluster clients with active topology refresh policies (`slotsRefreshTimeout`, automatic topology discovery on `MOVED` errors, and exponential backoff on cluster rebalancing).
- Services MUST NEVER rely on static client-side host lists for routing queries post-initialization; clients must handle `ASK` redirects via transient `ASKING` commands and update the cluster slot cache on `MOVED`.
- Pipelines and MGET/MSET batches in a cluster environment MUST partition keys into slot-specific chunks before dispatching to avoid cross-slot scatter-gather pipeline aborts.
- Engineers MUST ensure Valkey server-side `io-threads-do-reads` is paired with client-side connection pooling to avoid head-of-line blocking on saturated threaded I/O queues.

## Bad vs Good Implementations
### Cluster Failover-Safe Multi-Key Lua Execution and Topology Routing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The script uses separate keys `user:${fromUser}:bal` and `user:${toUser}:bal` without hash tags. In a Valkey cluster, these keys hash to different slots, throwing a CROSSSLOT error. Furthermore, a single-node client (`new Redis`) fails to handle `MOVED`/`ASK` redirects during cluster failovers or topology changes.
```typescript
import Redis from 'ioredis';

// Anti-pattern: Static node connection without topology refresh;
// multi-key Lua script with independent keys triggering CROSSSLOT errors;
// unbounded blocking command under multi-threaded Valkey instance.
const redis = new Redis('valkey://10.0.0.1:6379');

export async function transferTokens(fromUser: string, toUser: string, amount: number) {
  const script = `
    local sender = redis.call('GET', KEYS[1])
    if not sender or tonumber(sender) < tonumber(ARGV[1]) then
      return 0
    end
    redis.call('DECRBY', KEYS[1], ARGV[1])
    redis.call('INCRBY', KEYS[2], ARGV[1])
    return 1
  `;
  // Fails in cluster mode if fromUser and toUser land on different hash slots
  // Fails entirely during node failover with unhandled MOVED redirect error
  return await redis.eval(script, 2, `user:${fromUser}:bal`, `user:${toUser}:bal`, amount);
}
```

#### Production Standard (Correct)
> **Standard**: Configures an enterprise-grade Valkey Cluster client with proactive slot refresh timeouts and automatic failover redirection. Employs `{tenant:${tenantId}}` hash tags to ensure both keys map deterministically to the identical slot, eliminating CROSSSLOT errors while keeping the Lua script non-blocking.
```typescript
import { Cluster } from 'ioredis';

// Production Invariant: Explicit cluster configuration with slot topology refresh,
// DNS lookup handling, and strict hash-tagging to bind keys to the same CRC16 slot.
export const valkeyCluster = new Cluster(
  [{ host: 'valkey-cluster.internal', port: 6379 }],
  {
    dnsLookup: (address, callback) => callback(null, address),
    enableReadyCheck: true,
    scaleReads: 'master',
    slotsRefreshTimeout: 2000,
    clusterRetryStrategy: (times) => Math.min(100 * Math.pow(2, times), 3000),
    redisOptions: {
      connectTimeout: 5000,
      commandTimeout: 1000,
      maxRetriesPerRequest: 3
    }
  }
);

export async function transferTenantTokens(
  tenantId: string,
  fromUserId: string,
  toUserId: string,
  amount: number
): Promise<boolean> {
  // Invariant: Enforce Hash Tag {...} ensuring identical CRC16 slot calculation
  const fromKey = `{tenant:${tenantId}}:user:${fromUserId}:bal`;
  const toKey = `{tenant:${tenantId}}:user:${toUserId}:bal`;

  // Lua script remains non-blocking (<1ms) to protect Valkey 8.0 single-threaded command processor
  const atomicTransferLua = `
    local senderBal = redis.call('GET', KEYS[1])
    if not senderBal or tonumber(senderBal) < 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 valkeyCluster.eval(
    atomicTransferLua,
    2,
    fromKey,
    toKey,
    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 Cluster Topology, Failover Redirection, and Multi-Key Script Invariants

Valkey 8.0 Cluster Topology, Failover Redirection, and Multi-Key Script Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict production invariants for Valkey 8.0 clusters utilizing asynchronous multi-threaded I/O, hash-tagged atomic multi-key Lua scripts, and resilient slot topology refresh handling on MOVED and ASK cluster redirects during 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: Executing un-tagged multi-key operations or blocking Lua scripts under threaded I/O while mishandling cluster slot migrations and failover redirections. 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 un-tagged multi-key operations or blocking Lua scripts under threaded I/O while mishandling cluster slot migrations and failover redirections.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 use Redis/Valkey Hash Tags (e.g., `{tenant

Engineers MUST ALWAYS use Redis/Valkey Hash Tags (e.g., `{tenant:123}:entity`) for all multi-key operations, transactions, and Lua scripts to guarantee keys map to the identical CRC16 hash 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 complex multi-key commands with execution profiles exceeding 5ms, as Valkey 8.0 threaded I/O only offloads socket reads/writes while script execution remains bound to the single-threaded coordinator core.

Engineers MUST NOT execute Lua scripts or complex multi-key commands with execution profiles exceeding 5ms, as Valkey 8.0 threaded I/O only offloads socket reads/writes while script execution remains bound to the single-threaded coordinator core.

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

Services MUST configure cluster clients with active topology refresh policies (`slotsRefreshTimeout`, automatic topology discovery on `MOVED` errors, and exponential backoff on cluster rebalancing).

Services MUST configure cluster clients with active topology refresh policies (`slotsRefreshTimeout`, automatic topology discovery on `MOVED` errors, and exponential backoff on cluster rebalancing).

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 NEVER rely on static client-side host lists for routing queries post-initialization

Services MUST NEVER rely on static client-side host lists for routing queries post-initialization; clients must handle `ASK` redirects via transient `ASKING` commands and update the cluster slot cache on `MOVED`.

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

Pipelines and MGET/MSET batches in a cluster environment MUST partition keys into slot-specific chunks before dispatching to avoid cross-slot scatter-gather pipeline aborts.

Pipelines and MGET/MSET batches in a cluster environment MUST partition keys into slot-specific chunks before dispatching to avoid cross-slot scatter-gather pipeline aborts.

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

Engineers MUST ensure Valkey server-side `io-threads-do-reads` is paired with client-side connection pooling to avoid head-of-line blocking on saturated threaded I/O queues.

Engineers MUST ensure Valkey server-side `io-threads-do-reads` is paired with client-side connection pooling to avoid head-of-line blocking on saturated threaded I/O queues.

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, Failover Redirection, and Multi-Key Script Invariants critical for AI coding assistants?

Enforces strict production invariants for Valkey 8.0 clusters utilizing asynchronous multi-threaded I/O, hash-tagged atomic multi-key Lua scripts, and resilient slot topology refresh handling on MOVED and ASK cluster redirects during 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 (Executing un-tagged multi-key operations or blocking Lua scripts under threaded I/O while mishandling cluster slot migrations and failover redirections.) 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