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

Valkey 8.0 Threaded I/O, Cluster Slot Redirects, and Lua Atomicity

Enforces strict hash tagging for cross-key atomicity, zero-downtime cluster topology refresh during failovers, and non-blocking execution limits under Valkey 8.0 multi-threaded I/O. Prevents CROSSSLOT command rejections, network thread starvation, and stale replica reads during cluster node rebalancing.

Prohibited Anti-Pattern: Executing un-tagged multi-key Lua scripts and naive reconnect loops during cluster slot migration or failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Threaded I/O, Cluster Slot Redirects, and Lua Atomicity - Enforces strict hash tagging for cross-key atomicity, zero-downtime cluster topology refresh during failovers, and non-blocking execution limits under Valkey 8.0 multi-threaded I/O. Prevents CROSSSLOT command rejections, network thread starvation, and stale replica reads during cluster node rebalancing.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts, services/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-failover-threaded-io-standard"
---

# Valkey 8.0 Threaded I/O, Cluster Slot Redirects, and Lua Atomicity

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing un-tagged multi-key Lua scripts and naive reconnect loops during cluster slot migration or failover

## System Constraints
You are a Principal Backend Architect enforcing Valkey 8.0 Threaded I/O and Cluster Failover invariants. Ensure all multi-key operations and Lua scripts use explicit hash tags to guarantee identical hash slots. Ensure cluster clients dynamically handle MOVED and ASK slot redirects, throttle background reconnect storms, and never execute blocking Lua scripts that saturate the main execution thread while I/O threads buffer requests.

## Strict Guidelines
- Engineers MUST ALWAYS wrap shared key identifiers in curly braces (e.g., `{tenant:123}:session`, `{tenant:123}:profile`) when keys are evaluated together in Lua scripts, MGET/MSET commands, or transactions to guarantee identical hash slot placement (CRC16).
- Engineers MUST NOT execute Lua scripts or complex transactions across unbracketed distinct keys, as Valkey Cluster nodes immediately reject cross-slot keys with a `CROSSSLOT Keys in request don't hash to the same slot` error.
- Engineers MUST configure cluster client connection managers to refresh the cluster slot map (`CLUSTER SLOTS` / `CLUSTER SHARDS`) automatically upon encountering `MOVED` errors, and prepend `ASKING` within the same connection upon receiving `ASK` redirections.
- Engineers MUST enforce strict execution limits (<5ms) on all Lua scripts; Valkey 8.0 multi-threaded I/O parallelizes socket read/write processing, but script execution remains single-threaded on the main worker and will block all threaded I/O pipelines if allowed to run long queries.
- Services MUST configure exponential backoff with jitter (initial retry >= 50ms, max retry <= 3000ms) during cluster failovers (node crash / replica promotion) to prevent thundering herd socket exhaustion on newly elected primary nodes.
- Clients MUST configure read-from-replica policies with `READONLY` handshake commands strictly for read-only idempotent queries, and tolerate eventual consistency or failover redirects gracefully.

## Bad vs Good Implementations
### Cluster-Aware Lua Scripting and Failover Slot Redirect Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The keys `user:${senderId}:balance` and `user:${receiverId}:balance` map to unpredictable CRC16 hash slots across different Valkey master shards. In a clustered environment, this fails immediately with a CROSSSLOT error. Furthermore, default cluster client parameters without failover backoff or slot refresh will loop aggressively during primary node failover events.
```typescript
import Redis, { Cluster } from 'ioredis';

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

// ANTI-PATTERN: Keys do not use hash tags ({...}), causing CROSSSLOT errors in Valkey Cluster.
// Lua execution lacks timeout guards, blocking the single execution core despite Threaded I/O.
// Ignores automatic topology refresh configuration on MOVED/ASK failover storms.
export async function transferPoints(senderId: string, receiverId: string, amount: number) {
  const script = `
    local senderBal = redis.call('GET', KEYS[1])
    if not senderBal or tonumber(senderBal) < tonumber(ARGV[1]) then
      return -1
    end
    redis.call('DECRBY', KEYS[1], ARGV[1])
    redis.call('INCRBY', KEYS[2], ARGV[1])
    return 0
  `;

  // KEYS[1] and KEYS[2] will hash to different cluster slots -> Throws CROSSSLOT error
  return await cluster.eval(script, 2, `user:${senderId}:balance`, `user:${receiverId}:balance`, amount);
}
```

#### Production Standard (Correct)
> **Standard**: Hash tags `{tenant:${tenantId}}` force both keys into the exact same CRC16 slot, guaranteeing atomic cross-key execution without CROSSSLOT errors. The cluster configuration defines explicit exponential backoff with jitter and automated slot refreshes for MOVED/ASK responses during primary failovers.
```typescript
import { Cluster, ClusterOptions } from 'ioredis';

const clusterOptions: ClusterOptions = {
  enableReadyCheck: true,
  // Valkey 8.0 cluster failover configuration: dynamically refresh slot map
  slotsRefreshTimeout: 2000,
  maxRedirections: 16,
  retryDelayOnFailover: 100,
  retryDelayOnClusterDown: 250,
  scaleReads: 'slave',
  clusterRetryStrategy(times: number) {
    // Exponential backoff with jitter to prevent reconnect storms during failover
    const delay = Math.min(100 * Math.pow(2, times), 2000);
    const jitter = Math.floor(Math.random() * 50);
    return delay + jitter;
  }
};

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

// PRODUCTION INVARIANT: Use hash tags `{tenantId}` to guarantee deterministic slot assignment.
// Lua scripts are short, deterministic, and bounded to prevent blocking the Valkey execution thread.
const TRANSFER_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
`;

export async function transferTenantPoints(
  tenantId: string,
  senderUserId: string,
  receiverUserId: string,
  amount: number
): Promise<boolean> {
  // Invariant: Both keys share the exact same hash tag `{tenant:${tenantId}}`
  const senderKey = `{tenant:${tenantId}}:user:${senderUserId}:balance`;
  const receiverKey = `{tenant:${tenantId}}:user:${receiverUserId}:balance`;

  const result = await valkeyCluster.eval(
    TRANSFER_SCRIPT,
    2,
    senderKey,
    receiverKey,
    amount.toString()
  );

  return result === 1;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Valkey 8.0 Threaded I/O, Cluster Slot Redirects, and Lua Atomicity

Valkey 8.0 Threaded I/O, Cluster Slot Redirects, and Lua Atomicity defines an industrial-grade behavioral standard for backend engineering. Enforces strict hash tagging for cross-key atomicity, zero-downtime cluster topology refresh during failovers, and non-blocking execution limits under Valkey 8.0 multi-threaded I/O. Prevents CROSSSLOT command rejections, network thread starvation, and stale replica reads during cluster node rebalancing. 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-tagged multi-key Lua scripts and naive reconnect loops during cluster slot migration or 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 DriftExecuting un-tagged multi-key Lua scripts and naive reconnect loops during cluster slot migration or 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 wrap shared key identifiers in curly braces (e.g., `{tenant

Engineers MUST ALWAYS wrap shared key identifiers in curly braces (e.g., `{tenant:123}:session`, `{tenant:123}:profile`) when keys are evaluated together in Lua scripts, MGET/MSET commands, or transactions to guarantee identical hash slot placement (CRC16).

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 complex transactions across unbracketed distinct keys, as Valkey Cluster nodes immediately reject cross-slot keys with a `CROSSSLOT Keys in request don't hash to the same slot` error.

Engineers MUST NOT execute Lua scripts or complex transactions across unbracketed distinct keys, as Valkey Cluster nodes immediately reject cross-slot keys with a `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

Engineers MUST configure cluster client connection managers to refresh the cluster slot map (`CLUSTER SLOTS` / `CLUSTER SHARDS`) automatically upon encountering `MOVED` errors, and prepend `ASKING` within the same connection upon receiving `ASK` redirections.

Engineers MUST configure cluster client connection managers to refresh the cluster slot map (`CLUSTER SLOTS` / `CLUSTER SHARDS`) automatically upon encountering `MOVED` errors, and prepend `ASKING` within the same connection upon receiving `ASK` redirections.

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

Engineers MUST enforce strict execution limits (<5ms) on all Lua scripts

Engineers MUST enforce strict execution limits (<5ms) on all Lua scripts; Valkey 8.0 multi-threaded I/O parallelizes socket read/write processing, but script execution remains single-threaded on the main worker and will block all threaded I/O pipelines if allowed to run long queries.

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 MUST configure exponential backoff with jitter (initial retry >= 50ms, max retry <= 3000ms) during cluster failovers (node crash / replica promotion) to prevent thundering herd socket exhaustion on newly elected primary nodes.

Services MUST configure exponential backoff with jitter (initial retry >= 50ms, max retry <= 3000ms) during cluster failovers (node crash / replica promotion) to prevent thundering herd socket exhaustion on newly elected primary nodes.

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

Clients MUST configure read-from-replica policies with `READONLY` handshake commands strictly for read-only idempotent queries, and tolerate eventual consistency or failover redirects gracefully.

Clients MUST configure read-from-replica policies with `READONLY` handshake commands strictly for read-only idempotent queries, and tolerate eventual consistency or failover redirects gracefully.

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

Enforces strict hash tagging for cross-key atomicity, zero-downtime cluster topology refresh during failovers, and non-blocking execution limits under Valkey 8.0 multi-threaded I/O. Prevents CROSSSLOT command rejections, network thread starvation, and stale replica reads during cluster node rebalancing. 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-tagged multi-key Lua scripts and naive reconnect loops during cluster slot migration or 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