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

Valkey 8.0 Multi-Threaded I/O, Cluster Slot Pinning, and Failover Resilience

Enforces strict hash-tag pinning for multi-key operations and Lua scripts, explicit topology refresh intervals during cluster failover (MOVED/ASK redirects), and non-blocking multi-threaded I/O client integration in Valkey 8.0. Prevents runtime CROSSSLOT errors, split-brain command execution, and thread-pool exhaustion during primary-replica promotions.

Prohibited Anti-Pattern: Unpinned Cross-Slot Lua Scripts and Static Node Connections Causing Failover Deadlocks and CROSSSLOT Exceptions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Multi-Threaded I/O, Cluster Slot Pinning, and Failover Resilience - Enforces strict hash-tag pinning for multi-key operations and Lua scripts, explicit topology refresh intervals during cluster failover (MOVED/ASK redirects), and non-blocking multi-threaded I/O client integration in Valkey 8.0. Prevents runtime CROSSSLOT errors, split-brain command execution, and thread-pool exhaustion during primary-replica promotions.
globs: src/**/*.{ts,js,py,go}, config/**/*.{conf,yaml,json}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-threaded-io-failover-guardrails"
---

# Valkey 8.0 Multi-Threaded I/O, Cluster Slot Pinning, and Failover Resilience

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unpinned Cross-Slot Lua Scripts and Static Node Connections Causing Failover Deadlocks and CROSSSLOT Exceptions

## System Constraints
You are a Principal Backend Systems Architect specializing in Valkey 8.0 internals, distributed cluster topologies, and threaded I/O pipelines. Enforce strict key hashing policies ({hash_tag}) across all transactions and Lua script evaluations. Mandate resilient cluster redirection handling (MOVED, ASK) with dynamic topology refreshes, exponential backoff, and non-blocking connection pool semantics matching Valkey 8.0's multi-threaded I/O concurrency model.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate co-dependent keys in curly brace hash tags (e.g., `{tenant:123}:session`, `{tenant:123}:profile`) when executing multi-key transactions, MGET/MSET, or Lua scripts across a Valkey cluster to guarantee execution within the same 16384 slot.
- Engineers MUST NOT execute Lua scripts or Valkey functions with keys that span distinct hash slots, as Valkey 8.0 cluster nodes will abort with an unrecoverable `CROSSSLOT Keys in request don't hash to the same slot` error.
- Cluster clients MUST configure dynamic slot refresh strategies (`enableReadyCheck: true`, explicit handling of `MOVED` and `ASK` redirects, and periodic background slot refreshes) to prevent stale socket writes during primary node failover or replica promotions.
- Services MUST enable Valkey 8.0 threaded I/O optimizations on clients (auto-pipelining, batching, non-blocking asynchronous multiplexing) while ensuring client-side connection pooling scales cleanly with Valkey server `io-threads` and `io-threads-do-reads`.
- Components NEVER execute raw single-node fallback queries inside failover retry blocks without handling `READONLY` redirects when routing read traffic to read-replicas during topology transitions.

## Bad vs Good Implementations
### Cross-Slot Lua Script vs. Hash-Tagged Slot-Pinned Atomic Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Valkey Cluster 8.0, evaluating keys without explicit hash tags ({...}) hashes each key independently across the 16,384 cluster slots. When KEYS[1] and KEYS[2] map to different nodes or slots, Valkey immediately throws a CROSSSLOT error, breaking atomicity and bringing down transactional pathways.
```typescript
import { Cluster } from 'ioredis';

// Anti-pattern: Keys cross slots without hash-tagging; static configuration without failover recovery
const cluster = new Cluster([
  { host: 'valkey-node-1.internal', port: 6379 }
]);

export async function transferBalance(senderId: string, recipientId: string, amount: number): Promise<boolean> {
  const script = `
    local sender_bal = tonumber(redis.call('GET', KEYS[1]) or 0)
    if sender_bal < tonumber(ARGV[1]) then return 0 end
    redis.call('DECRBY', KEYS[1], ARGV[1])
    redis.call('INCRBY', KEYS[2], ARGV[1])
    return 1
  `;

  // FAILS: senderId and recipientId will hash to different cluster slots
  // Throws: 'CROSSSLOT Keys in request don't hash to the same slot'
  const result = await cluster.eval(
    script,
    2,
    `account:${senderId}:balance`,
    `account:${recipientId}:balance`,
    amount.toString()
  );

  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: By enclosing the shared partition boundary `{partition:${partitionId}}` in curly braces, Valkey hashes only the text between the braces, guaranteeing both keys resolve to the exact same hash slot. The cluster client configuration handles MOVED/ASK failover redirects and activates automatic pipelining to leverage Valkey 8.0's multi-threaded I/O engine.
```typescript
import { Cluster, ClusterOptions } from 'ioredis';

// Production Invariant: Dynamic topology discovery, MOVED/ASK redirect recovery, and connection resilience
const clusterOptions: ClusterOptions = {
  enableReadyCheck: true,
  scaleReads: 'slave',
  maxRedirections: 16,
  retryDelayOnFailover: 100,
  retryDelayOnClusterDown: 250,
  slotsRefreshTimeout: 2000,
  dnsLookup: (address, callback) => callback(null, address, 4),
  redisOptions: {
    connectTimeout: 5000,
    enableAutoPipelining: true // Exploits Valkey 8.0 multi-threaded I/O multiplexing
  }
};

const cluster = new Cluster(
  [
    { host: 'valkey-seed-1.internal', port: 6379 },
    { host: 'valkey-seed-2.internal', port: 6379 }
  ],
  clusterOptions
);

export async function transferPartitionedBalance(
  partitionId: string,
  senderId: string,
  recipientId: string,
  amount: number
): Promise<boolean> {
  // Invariant: Pin both keys to the same slot using partition hash tag {partitionId}
  const senderKey = `{partition:${partitionId}}:account:${senderId}:balance`;
  const recipientKey = `{partition:${partitionId}}:account:${recipientId}:balance`;

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

  const result = await cluster.eval(script, 2, senderKey, recipientKey, amount.toString());
  return 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 Multi-Threaded I/O, Cluster Slot Pinning, and Failover Resilience

Valkey 8.0 Multi-Threaded I/O, Cluster Slot Pinning, and Failover Resilience defines an industrial-grade behavioral standard for backend engineering. Enforces strict hash-tag pinning for multi-key operations and Lua scripts, explicit topology refresh intervals during cluster failover (MOVED/ASK redirects), and non-blocking multi-threaded I/O client integration in Valkey 8.0. Prevents runtime CROSSSLOT errors, split-brain command execution, and thread-pool exhaustion during primary-replica promotions. 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: Unpinned Cross-Slot Lua Scripts and Static Node Connections Causing Failover Deadlocks and CROSSSLOT Exceptions 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 DriftUnpinned Cross-Slot Lua Scripts and Static Node Connections Causing Failover Deadlocks and CROSSSLOT ExceptionsCritical
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 co-dependent keys in curly brace hash tags (e.g., `{tenant

Engineers MUST ALWAYS encapsulate co-dependent keys in curly brace hash tags (e.g., `{tenant:123}:session`, `{tenant:123}:profile`) when executing multi-key transactions, MGET/MSET, or Lua scripts across a Valkey cluster to guarantee execution within the same 16384 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 Valkey functions with keys that span distinct hash slots, as Valkey 8.0 cluster nodes will abort with an unrecoverable `CROSSSLOT Keys in request don't hash to the same slot` error.

Engineers MUST NOT execute Lua scripts or Valkey functions with keys that span distinct hash slots, as Valkey 8.0 cluster nodes will abort with an unrecoverable `CROSSSLOT Keys in request don't hash to the same slot` error.

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 dynamic slot refresh strategies (`enableReadyCheck

Cluster clients MUST configure dynamic slot refresh strategies (`enableReadyCheck: true`, explicit handling of `MOVED` and `ASK` redirects, and periodic background slot refreshes) to prevent stale socket writes during primary node failover or replica promotions.

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 Valkey 8.0 threaded I/O optimizations on clients (auto-pipelining, batching, non-blocking asynchronous multiplexing) while ensuring client-side connection pooling scales cleanly with Valkey server `io-threads` and `io-threads-do-reads`.

Services MUST enable Valkey 8.0 threaded I/O optimizations on clients (auto-pipelining, batching, non-blocking asynchronous multiplexing) while ensuring client-side connection pooling scales cleanly with Valkey server `io-threads` and `io-threads-do-reads`.

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 raw single-node fallback queries inside failover retry blocks without handling `READONLY` redirects when routing read traffic to read-replicas during topology transitions.

Components NEVER execute raw single-node fallback queries inside failover retry blocks without handling `READONLY` redirects when routing read traffic to read-replicas during topology transitions.

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, Cluster Slot Pinning, and Failover Resilience critical for AI coding assistants?

Enforces strict hash-tag pinning for multi-key operations and Lua scripts, explicit topology refresh intervals during cluster failover (MOVED/ASK redirects), and non-blocking multi-threaded I/O client integration in Valkey 8.0. Prevents runtime CROSSSLOT errors, split-brain command execution, and thread-pool exhaustion during primary-replica promotions. 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 (Unpinned Cross-Slot Lua Scripts and Static Node Connections Causing Failover Deadlocks and CROSSSLOT Exceptions) 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