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

Valkey 8.0 Threaded I/O Configuration, Cluster Failover, and Lua Slot Invariants

Enforces strict cluster routing, hash-tag slot alignment, and resilient connection pooling under Valkey 8.0 multi-threaded I/O architectures. Guarantees atomic Lua script execution across cluster shards while preventing unhandled MOVED/ASK redirect storms and failover split-brain writes.

Prohibited Anti-Pattern: Executing untagged multi-key operations and unhandled MOVED/ASK redirects across Valkey cluster shards.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Threaded I/O Configuration, Cluster Failover, and Lua Slot Invariants - Enforces strict cluster routing, hash-tag slot alignment, and resilient connection pooling under Valkey 8.0 multi-threaded I/O architectures. Guarantees atomic Lua script execution across cluster shards while preventing unhandled MOVED/ASK redirect storms and failover split-brain writes.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts, src/infrastructure/cache/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-threaded-io-cluster-failover"
---

# Valkey 8.0 Threaded I/O Configuration, Cluster Failover, and Lua Slot Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing untagged multi-key operations and unhandled MOVED/ASK redirects across Valkey cluster shards.

## System Constraints
You are a Principal Backend Architect enforcing strict architectural guardrails for Valkey 8.0 deployments. Mandate hash-tag encapsulation for multi-key atomicity, automated cluster slot topology updates on MOVED/ASK redirects, and resilient connection lifecycle patterns compatible with multi-threaded I/O backends.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate shared keys in multi-key commands or Lua scripts with curly brace hash-tags (e.g., `{tenant:123}:entity`) to guarantee single-slot co-location and prevent CROSSSLOT runtime errors.
- Engineers MUST NOT bypass the cluster client routing tier by pinning execution of mutating Lua scripts or transactions to arbitrary replica or standalone nodes.
- Code SHOULD configure cluster client instances with automated slot refresh intervals, exponential backoff with jitter on ASK/MOVED redirects, and bounded retry limits to prevent cascade connection exhaustion during master node failover.
- Services MUST enable read-from-replica routing only for idempotent, latency-tolerant operations using the READONLY command handshake, ensuring mutating write operations target current shard primaries.
- Components NEVER execute non-deterministic commands (e.g., TIME, SRANDMEMBER without seed) inside Lua scripts that run against Valkey 8.0 cluster environments to maintain replication and failover consistency.

## Bad vs Good Implementations
### Cluster-Aware Lua Script Execution with Hash Tags and Failover Topology Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The keys do not share a hash tag, causing cluster shards to reject the multi-key Lua command with a CROSSSLOT error. Furthermore, using a standalone connection to a single cluster node fails to handle MOVED/ASK slot redirects when failovers or rebalancing occur.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Standalone client used in cluster context,
// disparate keys cause CROSSSLOT failure, unhandled failover redirects
const client = new Redis('valkey://cluster-node-1:6379');

export async function deductQuotaUnsafe(
  userId: string,
  cost: number
): Promise<boolean> {
  const script = `
    local balance = redis.call('GET', KEYS[1])
    local history = KEYS[2]
    if tonumber(balance) >= tonumber(ARGV[1]) then
      redis.call('DECRBY', KEYS[1], ARGV[1])
      redis.call('LPUSH', history, ARGV[1])
      return 1
    end
    return 0
  `;
  // Keys hash to different slots -> CROSSSLOT Keys in request don't hash to same slot
  const balanceKey = `user:${userId}:balance`;
  const historyKey = `history:${userId}:ledger`;

  const result = await client.eval(script, 2, balanceKey, historyKey, cost);
  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: Uses hash tags ({user:${userId}}) to guarantee multi-key co-location on the same Valkey 8.0 cluster slot. Configures the cluster client with automatic slot refresh on MOVED/ASK redirects and exponential backoff retry strategies to smoothly survive shard failovers.
```typescript
import { Cluster, ClusterNode, ClusterOptions } from 'ioredis';

const clusterNodes: ClusterNode[] = [
  { host: 'valkey-cluster-node-1', port: 6379 },
  { host: 'valkey-cluster-node-2', port: 6379 },
  { host: 'valkey-cluster-node-3', port: 6379 },
];

const clusterOptions: ClusterOptions = {
  maxRedirections: 16,
  slotsRefreshTimeout: 2000,
  retryDelayOnFailover: 100,
  enableReadyCheck: true,
  scaleReads: 'slave',
  clusterRetryStrategy: (times: number) => Math.min(100 * Math.pow(2, times), 2000),
};

export const valkeyCluster = new Cluster(clusterNodes, clusterOptions);

export async function deductQuota(
  userId: string,
  cost: number
): Promise<boolean> {
  // Invariant: Enforce hash tags {...} to guarantee all keys map to the exact same hash slot
  const balanceKey = `{user:${userId}}:balance`;
  const historyKey = `{user:${userId}}:ledger`;

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

  const result = await valkeyCluster.eval(
    atomicDeductScript,
    2,
    balanceKey,
    historyKey,
    cost.toString()
  );

  return Number(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 Threaded I/O Configuration, Cluster Failover, and Lua Slot Invariants

Valkey 8.0 Threaded I/O Configuration, Cluster Failover, and Lua Slot Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict cluster routing, hash-tag slot alignment, and resilient connection pooling under Valkey 8.0 multi-threaded I/O architectures. Guarantees atomic Lua script execution across cluster shards while preventing unhandled MOVED/ASK redirect storms and failover split-brain writes. 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 untagged multi-key operations and unhandled MOVED/ASK redirects across Valkey cluster shards. 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 untagged multi-key operations and unhandled MOVED/ASK redirects across Valkey cluster shards.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 encapsulate shared keys in multi-key commands or Lua scripts with curly brace hash-tags (e.g., `{tenant

Engineers MUST ALWAYS encapsulate shared keys in multi-key commands or Lua scripts with curly brace hash-tags (e.g., `{tenant:123}:entity`) to guarantee single-slot co-location and prevent CROSSSLOT runtime 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 bypass the cluster client routing tier by pinning execution of mutating Lua scripts or transactions to arbitrary replica or standalone nodes.

Engineers MUST NOT bypass the cluster client routing tier by pinning execution of mutating Lua scripts or transactions to arbitrary replica or standalone nodes.

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 cluster client instances with automated slot refresh intervals, exponential backoff with jitter on ASK/MOVED redirects, and bounded retry limits to prevent cascade connection exhaustion during master node failover.

Code SHOULD configure cluster client instances with automated slot refresh intervals, exponential backoff with jitter on ASK/MOVED redirects, and bounded retry limits to prevent cascade connection exhaustion during master node failover.

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 enable read-from-replica routing only for idempotent, latency-tolerant operations using the READONLY command handshake, ensuring mutating write operations target current shard primaries.

Services MUST enable read-from-replica routing only for idempotent, latency-tolerant operations using the READONLY command handshake, ensuring mutating write operations target current shard primaries.

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 non-deterministic commands (e.g., TIME, SRANDMEMBER without seed) inside Lua scripts that run against Valkey 8.0 cluster environments to maintain replication and failover consistency.

Components NEVER execute non-deterministic commands (e.g., TIME, SRANDMEMBER without seed) inside Lua scripts that run against Valkey 8.0 cluster environments to maintain replication and failover consistency.

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 Configuration, Cluster Failover, and Lua Slot Invariants critical for AI coding assistants?

Enforces strict cluster routing, hash-tag slot alignment, and resilient connection pooling under Valkey 8.0 multi-threaded I/O architectures. Guarantees atomic Lua script execution across cluster shards while preventing unhandled MOVED/ASK redirect storms and failover split-brain writes. 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 untagged multi-key operations and unhandled MOVED/ASK redirects across Valkey cluster shards.) 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