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

Valkey 8.0 Threaded I/O Sharding, Hash-Tag Atomicity, and Failover Resilience

Enforces strict cluster slot pinning via hash tags for multi-key commands and atomic Lua scripts while configuring cluster topology auto-discovery and backoff retry logic. Prevents CROSSSLOT routing errors, pipeline stall during Valkey 8.0 threaded I/O processing, and service degradation during automated node failover.

Prohibited Anti-Pattern: Cross-Slot Key Execution in Multi-Key Lua Scripts and Missing Cluster Redirection Backoff During Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Threaded I/O Sharding, Hash-Tag Atomicity, and Failover Resilience - Enforces strict cluster slot pinning via hash tags for multi-key commands and atomic Lua scripts while configuring cluster topology auto-discovery and backoff retry logic. Prevents CROSSSLOT routing errors, pipeline stall during Valkey 8.0 threaded I/O processing, and service degradation during automated node failover.
globs: src/**/*.ts, src/infra/**/*.ts, src/cache/**/*.ts, src/lib/valkey/**/*.ts, src/repositories/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-failover-io-standard"
---

# Valkey 8.0 Threaded I/O Sharding, Hash-Tag Atomicity, and Failover Resilience

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Cross-Slot Key Execution in Multi-Key Lua Scripts and Missing Cluster Redirection Backoff During Failover

## System Constraints
You are a Principal Software Architect enforcing production invariants for Valkey 8.0 multi-threaded I/O and cluster architectures. You must mandate strict hash-tag slot boundaries for all multi-key transactions and Lua scripts, explicit topology refresh policies for failovers, and non-blocking I/O pipelining.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate shared routing keys with hash tags (e.g., `{tenant:123}:session` and `{tenant:123}:profile`) in multi-key operations and Lua/Functions scripts to guarantee execution within the same 16,384 hash slot.
- Engineers MUST NOT execute multi-key commands (MGET, MSET, EVAL, EVALSHA) across untagged dynamic keys in a clustered Valkey topology.
- Cluster client configurations MUST configure proactive cluster topology refreshes (`slotsRefreshInterval` or dynamic MOVED/ASK tracking) with backoff and jitter to prevent thundering herds during master failover.
- Code MUST handle transient failover errors (`MOVED`, `ASK`, `TRYAGAIN`, `CLUSTERDOWN`, `READONLY`) through automated retry strategies with exponential backoff and maximum retry thresholds.
- Pipelines executed against Valkey 8.0 multi-threaded I/O MUST group commands by node target to avoid slot-splitting stalls and maximize threaded read/write socket efficiency.

## Bad vs Good Implementations
### Cluster-Aware Lua Scripting and Failover Topology Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Untagged keys map to arbitrary cluster slots, triggering immediate CROSSSLOT errors in Valkey Cluster. Additionally, using a single-node connection instead of a cluster client causes total failure when node-1 undergoes a failover, failing to handle MOVED/ASK redirects or node promotions.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Direct standalone client on cluster seed, missing hash-tags, naive retry
export const cacheClient = new Redis('redis://valkey-cluster-node-1:6379');

export async function transferPoints(fromUser: string, toUser: string, points: number) {
  const luaScript = `
    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
  `;

  // BUG: KEYS map to different slots -> CROSSSLOT Keys in request don't hash to the same slot
  // BUG: If node-1 undergoes failover, command fails immediately with READONLY or connection dropped
  return cacheClient.eval(
    luaScript,
    2,
    `user:${fromUser}:balance`,
    `user:${toUser}:balance`,
    points
  );
}
```

#### Production Standard (Correct)
> **Standard**: Hash tags `{tenant:...}` force all interrelated keys into the same Valkey slot, enabling atomic multi-key script execution. The `Cluster` client configures topology polling, reconnects on `READONLY`/`MOVED` signals during election windows, and applies exponential backoff with jitter to survive node failovers smoothly.
```typescript
import { Cluster } from 'ioredis';

// PRODUCTION STANDARD: Cluster-aware client with automated failover retry and topology tracking
export const valkeyCluster = new Cluster(
  [
    { host: 'valkey-cluster-node-1', port: 6379 },
    { host: 'valkey-cluster-node-2', port: 6379 },
    { host: 'valkey-cluster-node-3', port: 6379 }
  ],
  {
    enableReadyCheck: true,
    scaleReads: 'slave',
    slotsRefreshInterval: 5000,
    slotsRefreshTimeout: 2000,
    clusterRetryStrategy(times: number) {
      // Exponential backoff with jitter (max 2000ms)
      return Math.min(100 * Math.pow(2, times) + Math.random() * 50, 2000);
    },
    redisOptions: {
      connectTimeout: 5000,
      reconnectOnError(err: Error): boolean {
        const targetErrors = ['READONLY', 'MOVED', 'ASK', 'CLUSTERDOWN'];
        return targetErrors.some((target) => err.message.includes(target));
      }
    }
  }
);

export async function updateTenantLedger(
  tenantId: string,
  sourceAccount: string,
  destinationAccount: string,
  amount: number
): Promise<number> {
  // INVARIANT: Use {tenantId} hash tags to guarantee both keys map to the exact same hash slot
  const sourceKey = `{tenant:${tenantId}}:account:${sourceAccount}`;
  const destKey = `{tenant:${tenantId}}:account:${destinationAccount}`;

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

  return (await valkeyCluster.eval(
    luaScript,
    2,
    sourceKey,
    destKey,
    amount
  )) as number;
}
```

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 Sharding, Hash-Tag Atomicity, and Failover Resilience

Valkey 8.0 Threaded I/O Sharding, Hash-Tag Atomicity, and Failover Resilience defines an industrial-grade behavioral standard for backend engineering. Enforces strict cluster slot pinning via hash tags for multi-key commands and atomic Lua scripts while configuring cluster topology auto-discovery and backoff retry logic. Prevents CROSSSLOT routing errors, pipeline stall during Valkey 8.0 threaded I/O processing, and service degradation during automated node failover. 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 Key Execution in Multi-Key Lua Scripts and Missing Cluster Redirection Backoff 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 Key Execution in Multi-Key Lua Scripts and Missing Cluster Redirection Backoff 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 encapsulate shared routing keys with hash tags (e.g., `{tenant

Engineers MUST ALWAYS encapsulate shared routing keys with hash tags (e.g., `{tenant:123}:session` and `{tenant:123}:profile`) in multi-key operations and Lua/Functions scripts to guarantee execution within the same 16,384 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

Engineers MUST NOT execute multi-key commands (MGET, MSET, EVAL, EVALSHA) across untagged dynamic keys in a clustered Valkey topology.

Engineers MUST NOT execute multi-key commands (MGET, MSET, EVAL, EVALSHA) across untagged dynamic keys in a clustered Valkey topology.

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 configurations MUST configure proactive cluster topology refreshes (`slotsRefreshInterval` or dynamic MOVED/ASK tracking) with backoff and jitter to prevent thundering herds during master failover.

Cluster client configurations MUST configure proactive cluster topology refreshes (`slotsRefreshInterval` or dynamic MOVED/ASK tracking) with backoff and jitter to prevent thundering herds during master 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

Code MUST handle transient failover errors (`MOVED`, `ASK`, `TRYAGAIN`, `CLUSTERDOWN`, `READONLY`) through automated retry strategies with exponential backoff and maximum retry thresholds.

Code MUST handle transient failover errors (`MOVED`, `ASK`, `TRYAGAIN`, `CLUSTERDOWN`, `READONLY`) through automated retry strategies with exponential backoff and maximum retry 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.
5

Pipelines executed against Valkey 8.0 multi-threaded I/O MUST group commands by node target to avoid slot-splitting stalls and maximize threaded read/write socket efficiency.

Pipelines executed against Valkey 8.0 multi-threaded I/O MUST group commands by node target to avoid slot-splitting stalls and maximize threaded read/write socket efficiency.

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 Sharding, Hash-Tag Atomicity, and Failover Resilience critical for AI coding assistants?

Enforces strict cluster slot pinning via hash tags for multi-key commands and atomic Lua scripts while configuring cluster topology auto-discovery and backoff retry logic. Prevents CROSSSLOT routing errors, pipeline stall during Valkey 8.0 threaded I/O processing, and service degradation during automated node failover. 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 Key Execution in Multi-Key Lua Scripts and Missing Cluster Redirection Backoff 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