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

Valkey 8.0 Threaded I/O & Cluster Failover Production Standards

Valkey 8.0 leverages asynchronous multi-threaded I/O for socket read/write operations while preserving single-threaded execution for command mutations. In distributed cluster deployments, unhandled MOVED and ASK redirections during automatic master failovers cause cascading connection pool exhaustion and silent command drops. Furthermore, multi-key operations and Lua scripts execute atomically only when all involved keys map to the identical cluster hash slot via explicit hash tags.

Prohibited Anti-Pattern: Executing cross-slot multi-key commands without hash tags while ignoring cluster failover redirects and socket pool saturation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Threaded I/O & Cluster Failover Production Standards - Valkey 8.0 leverages asynchronous multi-threaded I/O for socket read/write operations while preserving single-threaded execution for command mutations. In distributed cluster deployments, unhandled MOVED and ASK redirections during automatic master failovers cause cascading connection pool exhaustion and silent command drops. Furthermore, multi-key operations and Lua scripts execute atomically only when all involved keys map to the identical cluster hash slot via explicit hash tags.
globs: src/**/*.ts, lib/**/*.ts, config/valkey*.conf, **/*valkey*.*, **/*redis*.*
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-0-threaded-io-cluster-failover-guardrails"
---

# Valkey 8.0 Threaded I/O & Cluster Failover Production Standards

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing cross-slot multi-key commands without hash tags while ignoring cluster failover redirects and socket pool saturation.

## System Constraints
You are an expert distributed systems engineer specializing in Valkey 8.0 cluster resilience and threaded I/O mechanics. Enforce strict cluster topology awareness, explicit hash-tagging for multi-key atomicity, and adaptive exponential backoff for cluster failover redirections. Never permit cross-slot command pipelining or untracked connection retries during topology changes.

## Strict Guidelines
- Multi-key operations, transactions, and Lua scripts MUST use explicit hash tags (e.g., `{tenant_id}:session` and `{tenant_id}:profile`) to guarantee that all targeted keys evaluate to the exact same cluster hash slot.
- Valkey client drivers MUST be initialized in cluster mode with automatic topology updates enabled (`enableReadyCheck: true`, periodic slot refresh) to gracefully intercept `MOVED` and `ASK` redirects during master failovers.
- Connection pools interacting with Valkey 8.0 threaded I/O MUST configure bounded command queues and NEVER allow unbounded pipelining that exceeds network socket buffer limits.
- During cluster topology reshuffling or failover election windows, client retries MUST employ exponential backoff with full jitter and MUST NOT exceed a predefined timeout threshold.
- Scripts executed via `EVAL` or `EVALSHA` MUST NOT mutate global state and MUST declare all accessed keys explicitly in the `KEYS` array argument rather than generating dynamic key names inside Lua code.

## Bad vs Good Implementations
### Cluster-Aware Lua Script Execution with Hash Tagging and Topology Refresh

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The client is instantiated as a standalone node rather than a Valkey cluster client, leading to unhandled MOVED redirects on node failover. The keys lack hash tags, causing Valkey 8.0 cluster nodes to reject the Lua script with a CROSSSLOT Keys in request don't hash to the same slot error.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Single-node client configuration, cross-slot keys without hash tags,
// and unhandled cluster redirection during node failover.
export async function transferCreditsBad(
  fromUser: string,
  toUser: string,
  amount: number
): Promise<boolean> {
  const client = new Redis('valkey://127.0.0.1:6379');

  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
  `;

  // Throws CROSSSLOT error in cluster mode because fromUser and toUser
  // hash to different slots across separate Valkey master shards.
  // If a failover occurs, the client crashes with unhandled MOVED redirect.
  const result = await client.eval(
    script,
    2,
    `user:balance:${fromUser}`,
    `user:balance:${toUser}`,
    amount.toString()
  );

  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: Uses `ioredis.Cluster` configured with dynamic slot refreshing and jittered exponential retry backoff. Keys are tagged with `{org:orgId}` to guarantee they co-locate on the same Valkey slot, satisfying Valkey 8.0's multi-key atomicity guarantees during multi-threaded I/O operations.
```typescript
import { Cluster, ClusterNode } from 'ioredis';

interface TransferParams {
  organizationId: string;
  fromUser: string;
  toUser: string;
  amount: number;
}

// PRODUCTION FIX: Configured for Valkey Cluster with auto-slot refresh,
// explicit hash tagging `{orgId}`, and robust error handling for topology transitions.
const clusterNodes: ClusterNode[] = [
  { host: process.env.VALKEY_SEED_HOST || '127.0.0.1', port: 6379 }
];

const valkeyCluster = new Cluster(clusterNodes, {
  clusterRetryStrategy: (times: number) => {
    const delay = Math.min(100 * Math.pow(2, times), 3000);
    return delay + Math.floor(Math.random() * 100); // Exponential backoff with jitter
  },
  enableReadyCheck: true,
  slotsRefreshTimeout: 2000,
  redisOptions: {
    maxRetriesPerRequest: 3,
    connectTimeout: 5000
  }
});

const TRANSFER_LUA = `
  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
`;

export async function transferCredits({
  organizationId,
  fromUser,
  toUser,
  amount
}: TransferParams): Promise<boolean> {
  if (amount <= 0) {
    throw new Error('Transfer amount must be positive');
  }

  // Hash tag ensures both keys land on the identical Valkey cluster slot
  const senderKey = `{org:${organizationId}}:user:${fromUser}:balance`;
  const recipientKey = `{org:${organizationId}}:user:${toUser}:balance`;

  try {
    const result = await valkeyCluster.eval(
      TRANSFER_LUA,
      2,
      senderKey,
      recipientKey,
      amount.toString()
    );
    return result === 1;
  } catch (error: unknown) {
    if (error instanceof Error && error.message.includes('CLUSTERDOWN')) {
      // Cluster failover in progress; topology will refresh automatically
      throw new Error('Valkey cluster is currently transitioning topology; please retry');
    }
    throw error;
  }
}
```

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 & Cluster Failover Production Standards

Valkey 8.0 Threaded I/O & Cluster Failover Production Standards defines an industrial-grade behavioral standard for backend engineering. Valkey 8.0 leverages asynchronous multi-threaded I/O for socket read/write operations while preserving single-threaded execution for command mutations. In distributed cluster deployments, unhandled MOVED and ASK redirections during automatic master failovers cause cascading connection pool exhaustion and silent command drops. Furthermore, multi-key operations and Lua scripts execute atomically only when all involved keys map to the identical cluster hash slot via explicit hash tags. 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 cross-slot multi-key commands without hash tags while ignoring cluster failover redirects and socket pool saturation. 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 cross-slot multi-key commands without hash tags while ignoring cluster failover redirects and socket pool saturation.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

Multi-key operations, transactions, and Lua scripts MUST use explicit hash tags (e.g., `{tenant_id}

Multi-key operations, transactions, and Lua scripts MUST use explicit hash tags (e.g., `{tenant_id}:session` and `{tenant_id}:profile`) to guarantee that all targeted keys evaluate to the exact same cluster 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

Valkey client drivers MUST be initialized in cluster mode with automatic topology updates enabled (`enableReadyCheck

Valkey client drivers MUST be initialized in cluster mode with automatic topology updates enabled (`enableReadyCheck: true`, periodic slot refresh) to gracefully intercept `MOVED` and `ASK` redirects during master failovers.

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

Connection pools interacting with Valkey 8.0 threaded I/O MUST configure bounded command queues and NEVER allow unbounded pipelining that exceeds network socket buffer limits.

Connection pools interacting with Valkey 8.0 threaded I/O MUST configure bounded command queues and NEVER allow unbounded pipelining that exceeds network socket buffer limits.

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

During cluster topology reshuffling or failover election windows, client retries MUST employ exponential backoff with full jitter and MUST NOT exceed a predefined timeout threshold.

During cluster topology reshuffling or failover election windows, client retries MUST employ exponential backoff with full jitter and MUST NOT exceed a predefined timeout threshold.

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

Scripts executed via `EVAL` or `EVALSHA` MUST NOT mutate global state and MUST declare all accessed keys explicitly in the `KEYS` array argument rather than generating dynamic key names inside Lua code.

Scripts executed via `EVAL` or `EVALSHA` MUST NOT mutate global state and MUST declare all accessed keys explicitly in the `KEYS` array argument rather than generating dynamic key names inside Lua code.

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 Failover Production Standards critical for AI coding assistants?

Valkey 8.0 leverages asynchronous multi-threaded I/O for socket read/write operations while preserving single-threaded execution for command mutations. In distributed cluster deployments, unhandled MOVED and ASK redirections during automatic master failovers cause cascading connection pool exhaustion and silent command drops. Furthermore, multi-key operations and Lua scripts execute atomically only when all involved keys map to the identical cluster hash slot via explicit hash tags. 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 cross-slot multi-key commands without hash tags while ignoring cluster failover redirects and socket pool saturation.) 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