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

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

Enforces deterministic cluster hash tagging for multi-key atomic operations and Lua scripts to prevent CROSSSLOT execution failures in Valkey 8.0. Mandates dynamic cluster topology discovery, backpressure-aware connection pooling for threaded I/O, and automated retry mechanisms for MOVED and ASK redirects during cluster failovers.

Prohibited Anti-Pattern: Unpinned Multi-Key Script Execution with Naive Single-Node Clients Failing During Failover Re-Sharding

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 deterministic cluster hash tagging for multi-key atomic operations and Lua scripts to prevent CROSSSLOT execution failures in Valkey 8.0. Mandates dynamic cluster topology discovery, backpressure-aware connection pooling for threaded I/O, and automated retry mechanisms for MOVED and ASK redirects during cluster failovers.
globs: src/cache/**/*.{ts,js}, src/infra/valkey/**/*.{ts,js}, src/services/**/*.{ts,js}, src/repositories/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-threaded-io-cluster-failover-standard"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unpinned Multi-Key Script Execution with Naive Single-Node Clients Failing During Failover Re-Sharding

## System Constraints
You are a Principal Distributed Systems Engineer enforcing Valkey 8.0 Threaded I/O and Cluster Failover invariants. Mandate strict hash slot co-location via hash tags for multi-key operations, enforce asynchronous non-blocking connection pooling compatible with Valkey 8.0 threaded I/O, and verify that cluster topology refresh hooks are configured to handle MOVED/ASK redirects and cluster-down election windows seamlessly.

## Strict Guidelines
- Engineers MUST ALWAYS enforce hash tagging via `{...}` syntax on any multi-key commands, pipelines, and Lua scripts to guarantee key placement on the same hash slot and prevent CROSSSLOT errors.
- Engineers MUST NOT execute Lua scripts or transactions across un-tagged keys in Valkey cluster mode.
- Client instances MUST configure active and passive cluster topology refresh policies (e.g., `refreshConfigOnSlotMoved: true`, periodic heartbeats) to prevent split-brain routing during master elections and node failovers.
- Services MUST implement exponential backoff with full jitter when handling `MOVED`, `ASK`, and transient `CLUSTERDOWN` error states.
- Pipelines and connection pools MUST NOT exhaust Valkey 8.0 threaded I/O queues by issuing massive unbounded single-batch pipelines; split workloads into bounded sub-batches with strict timeout enforcement.

## Bad vs Good Implementations
### Cluster-Aware Atomic Rate Limiting with Hash-Tagged Slot Pinning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The script uses separate key prefixes that map to different hash slots across the cluster, triggering runtime CROSSSLOT errors. It also uses a single-node connection rather than a cluster client with dynamic slot discovery and MOVED/ASK failover handling.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Standalone client used in cluster context, un-tagged keys cause CROSSSLOT,
// and no automated slot refresh or failover redirect handling is configured.
const valkey = new Redis('valkey://127.0.0.1:6379');

export async function rateLimit(tenantId: string, metric: string): Promise<boolean> {
  const tokenKey = `rate:tenant:${tenantId}:tokens`;
  const timestampKey = `rate:tenant:${tenantId}:last_ts`;

  // CROSSSLOT error: tokenKey and timestampKey hash to different cluster slots
  const result = await valkey.eval(
    `
    local tokens = tonumber(redis.call('get', KEYS[1]) or '10')
    local last_ts = tonumber(redis.call('get', KEYS[2]) or '0')
    local now = tonumber(ARGV[1])
    if tokens > 0 then
      redis.call('set', KEYS[1], tokens - 1)
      redis.call('set', KEYS[2], now)
      return 1
    end
    return 0
    `,
    2,
    tokenKey,
    timestampKey,
    Date.now()
  );

  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: Hash tags `{tenant:...}` force both keys into the exact same 16384 slot partition. The cluster client manages active slot refresh, read-scaling, and redirection retries across failover events.
```typescript
import { Cluster, ClusterNode, ClusterOptions } from 'ioredis';

// PRODUCTION PATTERN: Valkey 8.0 Cluster-aware configuration with dynamic slot discovery,
// backoff retry for MOVED/ASK redirects, and bracketed hash tags for slot affinity.
const clusterNodes: ClusterNode[] = [
  { host: 'valkey-cluster-node-1.internal', port: 6379 },
  { host: 'valkey-cluster-node-2.internal', port: 6379 },
  { host: 'valkey-cluster-node-3.internal', port: 6379 },
];

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

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

export async function rateLimit(tenantId: string): Promise<boolean> {
  // Invariant: Both keys share the hash tag `{tenantId}`, pinning them to the identical slot.
  const tokenKey = `rate:{tenant:${tenantId}}:tokens`;
  const timestampKey = `rate:{tenant:${tenantId}}:last_ts`;

  const script = `
    local tokens = tonumber(redis.call('get', KEYS[1]) or '10')
    local last_ts = tonumber(redis.call('get', KEYS[2]) or '0')
    local now = tonumber(ARGV[1])
    if tokens > 0 then
      redis.call('set', KEYS[1], tokens - 1)
      redis.call('set', KEYS[2], now)
      return 1
    end
    return 0
  `;

  const result = await valkeyCluster.eval(
    script,
    2,
    tokenKey,
    timestampKey,
    Date.now()
  );

  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 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 deterministic cluster hash tagging for multi-key atomic operations and Lua scripts to prevent CROSSSLOT execution failures in Valkey 8.0. Mandates dynamic cluster topology discovery, backpressure-aware connection pooling for threaded I/O, and automated retry mechanisms for MOVED and ASK redirects during cluster failovers. 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 Multi-Key Script Execution with Naive Single-Node Clients Failing During Failover Re-Sharding 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 Multi-Key Script Execution with Naive Single-Node Clients Failing During Failover Re-ShardingCritical
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 enforce hash tagging via `{...}` syntax on any multi-key commands, pipelines, and Lua scripts to guarantee key placement on the same hash slot and prevent CROSSSLOT errors.

Engineers MUST ALWAYS enforce hash tagging via `{...}` syntax on any multi-key commands, pipelines, and Lua scripts to guarantee key placement on the same hash slot and prevent CROSSSLOT 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 execute Lua scripts or transactions across un-tagged keys in Valkey cluster mode.

Engineers MUST NOT execute Lua scripts or transactions across un-tagged keys in Valkey cluster mode.

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

Client instances MUST configure active and passive cluster topology refresh policies (e.g., `refreshConfigOnSlotMoved

Client instances MUST configure active and passive cluster topology refresh policies (e.g., `refreshConfigOnSlotMoved: true`, periodic heartbeats) to prevent split-brain routing during master elections and node 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.
4

Services MUST implement exponential backoff with full jitter when handling `MOVED`, `ASK`, and transient `CLUSTERDOWN` error states.

Services MUST implement exponential backoff with full jitter when handling `MOVED`, `ASK`, and transient `CLUSTERDOWN` error states.

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 and connection pools MUST NOT exhaust Valkey 8.0 threaded I/O queues by issuing massive unbounded single-batch pipelines

Pipelines and connection pools MUST NOT exhaust Valkey 8.0 threaded I/O queues by issuing massive unbounded single-batch pipelines; split workloads into bounded sub-batches with strict timeout enforcement.

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 deterministic cluster hash tagging for multi-key atomic operations and Lua scripts to prevent CROSSSLOT execution failures in Valkey 8.0. Mandates dynamic cluster topology discovery, backpressure-aware connection pooling for threaded I/O, and automated retry mechanisms for MOVED and ASK redirects during cluster failovers. 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 Multi-Key Script Execution with Naive Single-Node Clients Failing During Failover Re-Sharding) 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