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

Valkey 8.0 Multi-Threaded I/O Hash Slot Integrity and Failover Invariants

Mandates strict hash-tag alignment for multi-key operations, atomic Lua key declarations, and proactive cluster topology reconciliation in Valkey 8.0. Prevents CROSSSLOT errors, pipeline corruption during node failovers, and latency degradation in multi-threaded I/O environments.

Prohibited Anti-Pattern: Cross-Slot Key Access, Undeclared Dynamic Lua Keys, and Unhandled Cluster Failover Reconnection Storms

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 Integrity and Failover Invariants - Mandates strict hash-tag alignment for multi-key operations, atomic Lua key declarations, and proactive cluster topology reconciliation in Valkey 8.0. Prevents CROSSSLOT errors, pipeline corruption during node failovers, and latency degradation in multi-threaded I/O environments.
globs: src/**/*.{ts,js}, lib/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-failover-threaded-io"
---

# Valkey 8.0 Multi-Threaded I/O Hash Slot Integrity and Failover Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Cross-Slot Key Access, Undeclared Dynamic Lua Keys, and Unhandled Cluster Failover Reconnection Storms

## System Constraints
You are a Principal Backend Architect enforcing Valkey 8.0 cluster standards. Valkey 8.0 introduces an advanced multi-threaded I/O engine and stringent slot management during automated failovers. You must mandate strict hash-tagging syntax ({tag}) for all multi-key transactions and pipelines, explicit key declarations for Lua scripts to preserve cluster atomicity, and resilient cluster client configurations with backoff-driven slot cache invalidation.

## Strict Guidelines
- Engineers MUST ALWAYS enclose common routing identifiers in curly braces (e.g., `{tenant:1042}:user:profile`) to guarantee that multi-key operations map to the exact same 16,384 cluster slot.
- Engineers MUST NOT execute multi-key commands, pipelines, or transactions across heterogeneous keys without identical hash tags in a clustered Valkey topology.
- Engineers MUST ALWAYS pass every key accessed within a Lua script via the `KEYS` array rather than constructing key strings dynamically inside the script from `ARGV`.
- Services MUST configure cluster clients with automated slot refresh policies (`slotsRefreshTimeout`, jittered reconnect backoff) to handle failover `MOVED` and `ASK` responses without dropped frames.
- Pipelines MUST NEVER bundle commands targeting different cluster slots into a single non-cluster-aware atomic batch.
- Code SHOULD verify cluster health after failover by ensuring read-from-replica configurations account for replication lag via `WAIT` or cluster routing preferences.

## Bad vs Good Implementations
### Cluster-Aware Atomic Multi-Key Operation and Failover Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The keys do not share a hash tag, triggering runtime CROSSSLOT errors in Valkey Cluster. Furthermore, keys are passed via ARGV instead of KEYS, preventing the Valkey 8.0 threaded routing layer from validating slot ownership prior to execution.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Default non-cluster client or naive cluster setup
// Accesses disjoint keys causing CROSSSLOT errors; dynamically creates keys in Lua
export const cluster = new Redis.Cluster(['127.0.0.1:7000', '127.0.0.1:7001']);

export async function transferBalance(senderId: string, receiverId: string, amount: number) {
  // FAILS in cluster: sender and receiver hash to different slots
  const senderKey = `user:${senderId}:balance`;
  const receiverKey = `user:${receiverId}:balance`;

  const luaScript = `
    local sender = redis.call('GET', ARGV[1])
    local receiver = redis.call('GET', ARGV[2])
    if tonumber(sender) < tonumber(ARGV[3]) then return 0 end
    redis.call('DECRBY', ARGV[1], ARGV[3])
    redis.call('INCRBY', ARGV[2], ARGV[3])
    return 1
  `;

  // Dynamic keys passed via ARGV bypass cluster slot routing validation
  return await cluster.eval(luaScript, 0, senderKey, receiverKey, amount.toString());
}
```

#### Production Standard (Correct)
> **Standard**: Keys use `{tenant:tenantId}` hash tags ensuring slot affinity on a single Valkey cluster shard. Keys are passed via the KEYS array so Valkey multi-threaded I/O correctly validates slot affinity before dispatching, and cluster options are tuned for zero-downtime failovers.
```typescript
import Redis, { ClusterOptions } from 'ioredis';

// PRODUCTION INVARIANT: Resilient cluster config with slot refresh on failover
const clusterOptions: ClusterOptions = {
  enableReadyCheck: true,
  maxRedirections: 16,
  slotsRefreshTimeout: 2000,
  scaleReads: 'slave',
  clusterRetryStrategy: (times: number) => {
    const delay = Math.min(100 * Math.pow(2, times), 3000);
    return delay + Math.floor(Math.random() * 200); // Backoff with jitter
  }
};

export const valkeyCluster = new Redis.Cluster(
  [{ host: '127.0.0.1', port: 7000 }, { host: '127.0.0.1', port: 7001 }],
  clusterOptions
);

export async function transferBalance(tenantId: string, senderId: string, receiverId: string, amount: number) {
  // Invariant: Enforce hash tags to guarantee identical slot mapping in Valkey 8.0
  const senderKey = `{tenant:${tenantId}}:user:${senderId}:balance`;
  const receiverKey = `{tenant:${tenantId}}:user:${receiverId}:balance`;

  const luaScript = `
    local senderBal = tonumber(redis.call('GET', KEYS[1]) or '0')
    local transferAmt = tonumber(ARGV[1])
    if senderBal < transferAmt then return 0 end
    redis.call('DECRBY', KEYS[1], transferAmt)
    redis.call('INCRBY', KEYS[2], transferAmt)
    return 1
  `;

  // Invariant: All accessed keys are explicitly passed into KEYS array
  return await valkeyCluster.eval(luaScript, 2, senderKey, receiverKey, amount.toString());
}
```

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 Integrity and Failover Invariants

Valkey 8.0 Multi-Threaded I/O Hash Slot Integrity and Failover Invariants defines an industrial-grade behavioral standard for backend engineering. Mandates strict hash-tag alignment for multi-key operations, atomic Lua key declarations, and proactive cluster topology reconciliation in Valkey 8.0. Prevents CROSSSLOT errors, pipeline corruption during node failovers, and latency degradation in multi-threaded I/O environments. 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 Key Access, Undeclared Dynamic Lua Keys, and Unhandled Cluster Failover Reconnection Storms 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 Key Access, Undeclared Dynamic Lua Keys, and Unhandled Cluster Failover Reconnection StormsCritical
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 curly braces (e.g., `{tenant

Engineers MUST ALWAYS enclose common routing identifiers in curly braces (e.g., `{tenant:1042}:user:profile`) to guarantee that multi-key operations map to the exact same 16,384 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 multi-key commands, pipelines, or transactions across heterogeneous keys without identical hash tags in a clustered Valkey topology.

Engineers MUST NOT execute multi-key commands, pipelines, or transactions across heterogeneous keys without identical hash tags in a clustered Valkey topology.

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

Engineers MUST ALWAYS pass every key accessed within a Lua script via the `KEYS` array rather than constructing key strings dynamically inside the script from `ARGV`.

Engineers MUST ALWAYS pass every key accessed within a Lua script via the `KEYS` array rather than constructing key strings dynamically inside the script from `ARGV`.

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 configure cluster clients with automated slot refresh policies (`slotsRefreshTimeout`, jittered reconnect backoff) to handle failover `MOVED` and `ASK` responses without dropped frames.

Services MUST configure cluster clients with automated slot refresh policies (`slotsRefreshTimeout`, jittered reconnect backoff) to handle failover `MOVED` and `ASK` responses without dropped frames.

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 MUST NEVER bundle commands targeting different cluster slots into a single non-cluster-aware atomic batch.

Pipelines MUST NEVER bundle commands targeting different cluster slots into a single non-cluster-aware atomic batch.

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

Code SHOULD verify cluster health after failover by ensuring read-from-replica configurations account for replication lag via `WAIT` or cluster routing preferences.

Code SHOULD verify cluster health after failover by ensuring read-from-replica configurations account for replication lag via `WAIT` or cluster routing preferences.

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 Integrity and Failover Invariants critical for AI coding assistants?

Mandates strict hash-tag alignment for multi-key operations, atomic Lua key declarations, and proactive cluster topology reconciliation in Valkey 8.0. Prevents CROSSSLOT errors, pipeline corruption during node failovers, and latency degradation in multi-threaded I/O environments. 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 Key Access, Undeclared Dynamic Lua Keys, and Unhandled Cluster Failover Reconnection Storms) 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