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

Valkey 8.0 Threaded I/O, Cluster Redirection, and Hash-Tagged Lua Atomicity

Enforce strict hash-tag slot isolation for multi-key transactions and Lua scripts within Valkey 8.0 cluster topologies. Mandate resilient MOVED/ASK redirect handling with automatic slot cache invalidation and backoff to survive replica-to-primary failovers without stalling Valkey's event loop or causing CROSSSLOT exceptions.

Prohibited Anti-Pattern: Cross-Slot Execution Failures and Unhandled MOVED/ASK Redirect Storms During Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Threaded I/O, Cluster Redirection, and Hash-Tagged Lua Atomicity - Enforce strict hash-tag slot isolation for multi-key transactions and Lua scripts within Valkey 8.0 cluster topologies. Mandate resilient MOVED/ASK redirect handling with automatic slot cache invalidation and backoff to survive replica-to-primary failovers without stalling Valkey's event loop or causing CROSSSLOT exceptions.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-failover-multithreaded-io"
---

# Valkey 8.0 Threaded I/O, Cluster Redirection, and Hash-Tagged Lua Atomicity

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Cross-Slot Execution Failures and Unhandled MOVED/ASK Redirect Storms During Failover

## System Constraints
You are a Principal Backend Architect enforcing strict Valkey 8.0 cluster invariants. Valkey 8.0 offloads socket I/O to worker threads via asynchronous I/O threading, but command execution remains serialized on the main event loop. All multi-key operations and Lua script invocations MUST map to identical hash slots via explicit hash tags `{...}` to prevent CROSSSLOT errors. Client configurations MUST handle cluster failover states (MOVED and ASK redirects), refresh slot mappings dynamically with jittered backoff, and avoid executing blocking or computationally unbounded Lua scripts that starve the single execution thread.

## Strict Guidelines
- Engineers MUST ALWAYS enclose common routing identifiers in hash tags (e.g., `{tenant:123}:session` and `{tenant:123}:profile`) for any multi-key transaction or Lua script execution in Valkey Cluster.
- Engineers MUST NOT execute Lua scripts or multi-key commands across keys that resolve to different CRC16 hash slots.
- Cluster client connection pools MUST be configured with dynamic slot refreshing enabled (e.g., auto-reconnect on MOVED errors, periodic topology refresh intervals, and retry limit thresholds).
- Services MUST gracefully catch and handle transient cluster failover errors (such as `CLUSTERDOWN`, `TRYAGAIN`, and `ASK`) using bounded exponential backoff with full jitter.
- Components NEVER execute blocking operations (e.g., `KEYS`, `FLUSHALL`, or infinite Lua loops) inside Valkey scripts; time complexity per script execution MUST NOT exceed O(N) where N <= 1000 items.

## Bad vs Good Implementations
### Cluster-Aware Lua Script Execution with Hash Tagging and Resilient Client Setup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The script uses separate keys ('user:X:balance' and 'user:Y:balance') that hash to different CRC16 cluster slots, triggering a fatal Valkey CROSSSLOT error. Furthermore, a non-cluster client is used without slot cache management or handling for MOVED/ASK redirection during master failover.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Client lacks cluster topology awareness, fails on failover
const client = new Redis('redis://valkey-cluster-node:6379');

export async function transferTokens(fromUser: string, toUser: string, amount: number) {
  // FAILS: Multi-key operations on distinct keys without hash tags yield CROSSSLOT errors in cluster mode
  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
  `;
  
  // Unhandled MOVED/ASK redirect during cluster failover drops execution
  return await client.eval(
    script,
    2,
    `user:${fromUser}:balance`,
    `user:${toUser}:balance`,
    amount
  );
}
```

#### Production Standard (Correct)
> **Standard**: Hash tags `{tenant:${tenantId}}` force all balance keys in that partition to compute the identical CRC16 hash slot, safely enabling atomic Lua transactions in Valkey Cluster. The cluster client configuration automatically refreshes slots and handles MOVED/ASK redirects when nodes fail over.
```typescript
import { Cluster, ClusterNode } 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 }
];

// PRODUCTION FIX: Configured for automatic slot topology refresh during failovers
export const valkeyCluster = new Cluster(clusterNodes, {
  scaleReads: 'slave',
  clusterRetryStrategy: (times: number) => Math.min(100 * Math.pow(2, times) + Math.random() * 50, 2000),
  slotsRefreshTimeout: 2000,
  redisOptions: {
    connectTimeout: 5000,
    maxRetriesPerRequest: 3
  }
});

// Atomic token transfer within the same organizational scope using hash tags
const ATOMIC_TRANSFER_LUA = `
  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
`;

export async function transferTokensWithinTenant(
  tenantId: string,
  fromUser: string,
  toUser: string,
  amount: number
): Promise<boolean> {
  // Invariant: Both keys map to the same hash slot via the '{tenant:<id>}' prefix
  const senderKey = `{tenant:${tenantId}}:user:${fromUser}:balance`;
  const receiverKey = `{tenant:${tenantId}}:user:${toUser}:balance`;

  const result = await valkeyCluster.eval(
    ATOMIC_TRANSFER_LUA,
    2,
    senderKey,
    receiverKey,
    amount
  );

  return Number(result) === 1;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Valkey 8.0 Threaded I/O, Cluster Redirection, and Hash-Tagged Lua Atomicity

Valkey 8.0 Threaded I/O, Cluster Redirection, and Hash-Tagged Lua Atomicity defines an industrial-grade behavioral standard for backend engineering. Enforce strict hash-tag slot isolation for multi-key transactions and Lua scripts within Valkey 8.0 cluster topologies. Mandate resilient MOVED/ASK redirect handling with automatic slot cache invalidation and backoff to survive replica-to-primary failovers without stalling Valkey's event loop or causing CROSSSLOT exceptions. 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 Execution Failures and Unhandled MOVED/ASK Redirect Storms 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 DriftCross-Slot Execution Failures and Unhandled MOVED/ASK Redirect Storms 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 enclose common routing identifiers in hash tags (e.g., `{tenant

Engineers MUST ALWAYS enclose common routing identifiers in hash tags (e.g., `{tenant:123}:session` and `{tenant:123}:profile`) for any multi-key transaction or Lua script execution in Valkey Cluster.

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 across keys that resolve to different CRC16 hash slots.

Engineers MUST NOT execute Lua scripts or multi-key commands across keys that resolve to different CRC16 hash slots.

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 connection pools MUST be configured with dynamic slot refreshing enabled (e.g., auto-reconnect on MOVED errors, periodic topology refresh intervals, and retry limit thresholds).

Cluster client connection pools MUST be configured with dynamic slot refreshing enabled (e.g., auto-reconnect on MOVED errors, periodic topology refresh intervals, and retry limit thresholds).

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 gracefully catch and handle transient cluster failover errors (such as `CLUSTERDOWN`, `TRYAGAIN`, and `ASK`) using bounded exponential backoff with full jitter.

Services MUST gracefully catch and handle transient cluster failover errors (such as `CLUSTERDOWN`, `TRYAGAIN`, and `ASK`) using bounded exponential backoff with full jitter.

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 execute blocking operations (e.g., `KEYS`, `FLUSHALL`, or infinite Lua loops) inside Valkey scripts

Components NEVER execute blocking operations (e.g., `KEYS`, `FLUSHALL`, or infinite Lua loops) inside Valkey scripts; time complexity per script execution MUST NOT exceed O(N) where N <= 1000 items.

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 Threaded I/O, Cluster Redirection, and Hash-Tagged Lua Atomicity critical for AI coding assistants?

Enforce strict hash-tag slot isolation for multi-key transactions and Lua scripts within Valkey 8.0 cluster topologies. Mandate resilient MOVED/ASK redirect handling with automatic slot cache invalidation and backoff to survive replica-to-primary failovers without stalling Valkey's event loop or causing CROSSSLOT exceptions. 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 Execution Failures and Unhandled MOVED/ASK Redirect Storms 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