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-invariants

Valkey 8.0 Threaded I/O, Slot Redirects, and Cross-Slot Script Atomicity Standard

Enforces architectural invariants for Valkey 8.0 deployments, mandating explicit hash-tag slot pinning for multi-key commands and Lua/function scripts, client-side resilience against MOVED and ASK redirection storms during topology failovers, and optimal threaded I/O configuration to avoid thread contention.

Prohibited Anti-Pattern: Executing un-bracketed multi-key Lua scripts alongside unthrottled MOVED/ASK redirect retry loops during cluster failovers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Threaded I/O, Slot Redirects, and Cross-Slot Script Atomicity Standard - Enforces architectural invariants for Valkey 8.0 deployments, mandating explicit hash-tag slot pinning for multi-key commands and Lua/function scripts, client-side resilience against MOVED and ASK redirection storms during topology failovers, and optimal threaded I/O configuration to avoid thread contention.
globs: src/**/*.{ts,js,py,go,rs}, lib/**/*.{ts,js,py,go,rs}, config/**/valkey*.conf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-threaded-io-cluster-failover-invariants"
---

# Valkey 8.0 Threaded I/O, Slot Redirects, and Cross-Slot Script Atomicity Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing un-bracketed multi-key Lua scripts alongside unthrottled MOVED/ASK redirect retry loops during cluster failovers.

## System Constraints
You are a Principal Backend Systems Architect enforcing Valkey 8.0 invariants. Mandate that every multi-key operation or Lua/FCALL script explicitly pins keys to the same cluster hash slot using hash tags ('{...}'). Prevent unthrottled MOVED/ASK redirection retry cascades during primary-replica failovers, and enforce client-side topology refresh limits and asynchronous non-blocking failover recovery.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate cluster-partitioned keys within curly brackets `{...}` (hash tags) whenever multiple keys are evaluated atomically in a single command, pipeline, transaction, or Lua script.
- Engineers MUST NOT execute multi-key Lua scripts or functions using disparate dynamic keys without guaranteeing identical slot hashing, avoiding CROSSSLOT errors entirely.
- Clients MUST implement exponential backoff with full jitter when handling `MOVED` and `ASK` cluster redirects, capped at a maximum retry count of 3 to 5 attempts before surfacing topology errors.
- Client connection pools MUST throttle cluster topology refreshes (`CLUSTER SLOTS` / `CLUSTER SHARDS`) using a minimum debounce window (e.g., 500ms to 1000ms) to prevent herd effects during rapid primary node transitions.
- Services running Valkey 8.0 server-side configurations MUST size `io-threads` proportionally to allocated physical CPU cores (typically `core_count - 1` for systems with >= 4 cores) and MUST NOT over-provision `io-threads` beyond available physical cores.
- Lua scripts and Valkey functions MUST NEVER perform long-running or unbounded loops that block the single execution thread, ensuring latency SLA preservation across active Threaded I/O pipelines.

## Bad vs Good Implementations
### Atomic Multi-Key Lua Execution in Cluster Mode

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Valkey/Redis Cluster mode, executing multi-key Lua scripts across distinct keys without hash tags triggers a runtime `CROSSSLOT Keys in request don't hash to the same slot` exception. Additionally, the cluster client lacks retry bounds, causing request stampedes during replica promotion.
```typescript
import { Cluster } from 'ioredis';

const cluster = new Cluster([{ host: 'valkey-node-1', port: 6379 }]);

// ANTI-PATTERN: Keys do not use hash tags; produces CROSSSLOT error in cluster mode
// Lacks redirect handling bounds and topology reload debouncing
export async function transferTokens(fromUser: string, toUser: string, amount: number): Promise<boolean> {
  const script = `
    local senderBalance = tonumber(redis.call('get', KEYS[1]) or 0)
    if senderBalance >= tonumber(ARGV[1]) then
      redis.call('decrby', KEYS[1], ARGV[1])
      redis.call('incrby', KEYS[2], ARGV[1])
      return 1
    end
    return 0
  `;

  // fromUser and toUser may hash to completely different slots (0-16383)
  const result = await cluster.eval(
    script,
    2,
    `user:${fromUser}:balance`,
    `user:${toUser}:balance`,
    amount
  );

  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: Uses hash tags `{tenant:${tenantId}}` to guarantee all target keys evaluate to identical hash slots (0-16383), strictly preserving Lua atomicity on a single primary node. The client configuration enforces backoff jitter and rate-limited cluster topology refresh.
```typescript
import { Cluster, ClusterOptions } from 'ioredis';

const clusterOptions: ClusterOptions = {
  slotsRefreshTimeout: 2000,
  maxRedirections: 4,
  retryDelayOnFailover: 100,
  clusterRetryStrategy: (times) => Math.min(100 * Math.pow(2, times) + Math.random() * 50, 2000),
  enableReadyCheck: true
};

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

// PRODUCTION FIX: Pin keys to the exact same hash slot using a partition/tenant/shard hash tag
export async function transferTokensInShard(
  tenantId: string,
  fromUser: string,
  toUser: string,
  amount: number
): Promise<boolean> {
  const script = `
    local senderBalance = tonumber(redis.call('get', KEYS[1]) or 0)
    local deduct = tonumber(ARGV[1])
    if senderBalance >= deduct then
      redis.call('decrby', KEYS[1], deduct)
      redis.call('incrby', KEYS[2], deduct)
      return 1
    end
    return 0
  `;

  // Hash tag '{tenantId}' guarantees both keys map to the same slot on the same Valkey node
  const senderKey = `{tenant:${tenantId}}:user:${fromUser}:balance`;
  const receiverKey = `{tenant:${tenantId}}:user:${toUser}:balance`;

  const result = await cluster.eval(script, 2, senderKey, receiverKey, amount.toString());
  return 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, Slot Redirects, and Cross-Slot Script Atomicity Standard

Valkey 8.0 Threaded I/O, Slot Redirects, and Cross-Slot Script Atomicity Standard defines an industrial-grade behavioral standard for backend engineering. Enforces architectural invariants for Valkey 8.0 deployments, mandating explicit hash-tag slot pinning for multi-key commands and Lua/function scripts, client-side resilience against MOVED and ASK redirection storms during topology failovers, and optimal threaded I/O configuration to avoid thread contention. 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 un-bracketed multi-key Lua scripts alongside unthrottled MOVED/ASK redirect retry loops during cluster failovers. 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 un-bracketed multi-key Lua scripts alongside unthrottled MOVED/ASK redirect retry loops during cluster failovers.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 cluster-partitioned keys within curly brackets `{...}` (hash tags) whenever multiple keys are evaluated atomically in a single command, pipeline, transaction, or Lua script.

Engineers MUST ALWAYS encapsulate cluster-partitioned keys within curly brackets `{...}` (hash tags) whenever multiple keys are evaluated atomically in a single command, pipeline, transaction, or Lua script.

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 Lua scripts or functions using disparate dynamic keys without guaranteeing identical slot hashing, avoiding CROSSSLOT errors entirely.

Engineers MUST NOT execute multi-key Lua scripts or functions using disparate dynamic keys without guaranteeing identical slot hashing, avoiding CROSSSLOT errors entirely.

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

Clients MUST implement exponential backoff with full jitter when handling `MOVED` and `ASK` cluster redirects, capped at a maximum retry count of 3 to 5 attempts before surfacing topology errors.

Clients MUST implement exponential backoff with full jitter when handling `MOVED` and `ASK` cluster redirects, capped at a maximum retry count of 3 to 5 attempts before surfacing topology 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.
4

Client connection pools MUST throttle cluster topology refreshes (`CLUSTER SLOTS` / `CLUSTER SHARDS`) using a minimum debounce window (e.g., 500ms to 1000ms) to prevent herd effects during rapid primary node transitions.

Client connection pools MUST throttle cluster topology refreshes (`CLUSTER SLOTS` / `CLUSTER SHARDS`) using a minimum debounce window (e.g., 500ms to 1000ms) to prevent herd effects during rapid primary node 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.
5

Services running Valkey 8.0 server-side configurations MUST size `io-threads` proportionally to allocated physical CPU cores (typically `core_count - 1` for systems with >= 4 cores) and MUST NOT over-provision `io-threads` beyond available physical cores.

Services running Valkey 8.0 server-side configurations MUST size `io-threads` proportionally to allocated physical CPU cores (typically `core_count - 1` for systems with >= 4 cores) and MUST NOT over-provision `io-threads` beyond available physical cores.

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

Lua scripts and Valkey functions MUST NEVER perform long-running or unbounded loops that block the single execution thread, ensuring latency SLA preservation across active Threaded I/O pipelines.

Lua scripts and Valkey functions MUST NEVER perform long-running or unbounded loops that block the single execution thread, ensuring latency SLA preservation across active Threaded I/O pipelines.

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, Slot Redirects, and Cross-Slot Script Atomicity Standard critical for AI coding assistants?

Enforces architectural invariants for Valkey 8.0 deployments, mandating explicit hash-tag slot pinning for multi-key commands and Lua/function scripts, client-side resilience against MOVED and ASK redirection storms during topology failovers, and optimal threaded I/O configuration to avoid thread contention. 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 un-bracketed multi-key Lua scripts alongside unthrottled MOVED/ASK redirect retry loops during cluster failovers.) 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