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

Valkey 8.0 Multi-Threaded I/O, Hash Slot Routing & Lua Atomicity Guardrails

Enforces strict hash-tag pinning for multi-key operations and Lua scripts in Valkey 8.0 clusters to prevent CROSSSLOT execution failures. Mandates non-blocking transactional script boundaries and resilient topology refresh configurations to safeguard Valkey 8.0 multi-threaded I/O pipelines during master failovers.

Prohibited Anti-Pattern: Unpinned Cross-Slot Lua Scripts and Topology-Blind Retries Triggering Main-Thread Starvation and MOVED Storms

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Multi-Threaded I/O, Hash Slot Routing & Lua Atomicity Guardrails - Enforces strict hash-tag pinning for multi-key operations and Lua scripts in Valkey 8.0 clusters to prevent CROSSSLOT execution failures. Mandates non-blocking transactional script boundaries and resilient topology refresh configurations to safeguard Valkey 8.0 multi-threaded I/O pipelines during master failovers.
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-slot-lua-atomicity-failover"
---

# Valkey 8.0 Multi-Threaded I/O, Hash Slot Routing & Lua Atomicity Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unpinned Cross-Slot Lua Scripts and Topology-Blind Retries Triggering Main-Thread Starvation and MOVED Storms

## System Constraints
You are a Principal Software Architect enforcing Valkey 8.0 operational invariants. Ensure all cluster interactions utilize proper hash-tagging for slot affinity, handle MOVED/ASK redirects with exponential backoff and jitter, prevent blocking execution on the single-threaded execution core despite multi-threaded I/O, and maintain atomic failover-safe scripts.

## Strict Guidelines
- Engineers MUST ALWAYS enforce curly brace hash tags (e.g., `{tenant:123}:resource`) on all multi-key Valkey commands, pipelines, and Lua scripts to pin keys to a single hash slot.
- Engineers MUST NOT execute cross-slot Lua scripts or transactional multi-key commands without hash-tag affinity, as Valkey 8.0 Cluster strictly returns `CROSSSLOT Keys in request don't hash to the same slot`.
- Engineers MUST NOT execute long-running O(N) operations inside Lua scripts or functions; Valkey 8.0 parallelizes socket I/O across worker threads, but core command execution remains strictly single-threaded.
- Services MUST configure cluster clients with active topology refreshes (`slotsRefreshInterval`, `enableAutoPipelining`, and DNS re-resolution) to prevent MOVED redirect loops and packet drops during cluster failover.
- Components NEVER hardcode node endpoints or execute stateful transactions during failover windows without backoff limits and reconnection rate-limiting.

## Bad vs Good Implementations
### Cluster Hash-Tag Affinity & Failover Resilience Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Lua script accesses two distinct keys (`user:${fromUser}:bal` and `user:${toUser}:bal`) without cluster hash tags, causing guaranteed runtime `CROSSSLOT` failures. Furthermore, the cluster client lacks failover retry limits, topology refresh listeners, and slot refresh intervals, causing cascading connection failures during Valkey 8.0 master failover.
```typescript
import Redis, { Cluster } from 'ioredis';

// ANTI-PATTERN: Blind cluster initialization without failover topology refresh
// and multi-key Lua script without hash-tag slot affinity
export const valkeyCluster = new Cluster([
  { host: 'valkey-node-1.internal', port: 6379 },
  { host: 'valkey-node-2.internal', port: 6379 }
]);

export async function transferCredits(fromUser: string, toUser: string, amount: number) {
  // FAILS in Valkey Cluster: fromUser and toUser route to different hash slots
  const luaScript = `
    local senderBalance = tonumber(redis.call('GET', KEYS[1]) or '0')
    if senderBalance < tonumber(ARGV[1]) then
      return 0
    end
    redis.call('DECRBY', KEYS[1], ARGV[1])
    redis.call('INCRBY', KEYS[2], ARGV[1])
    return 1
  `;

  // CROSSSLOT error thrown at runtime; unhandled MOVED redirect during node failover
  return await valkeyCluster.eval(luaScript, 2, `user:${fromUser}:bal`, `user:${toUser}:bal`, amount);
}
```

#### Production Standard (Correct)
> **Standard**: Keys are pinned to the same cluster hash slot using explicit hash tags (`{tenant:${tenantId}}`), guaranteeing atomic execution without `CROSSSLOT` exceptions. The client explicitly handles topology reconciliation via `slotsRefreshInterval`, exponential backoff with jitter on reconnects, and command timeouts to withstand node elections without stalling Valkey 8.0 threaded I/O pipelines.
```typescript
import { Cluster, ClusterOptions } from 'ioredis';

// PRODUCTION INVARIANT: Resilient Cluster Configuration for Valkey 8.0
const clusterOptions: ClusterOptions = {
  enableReadyCheck: true,
  scaleReads: 'slave',
  maxRedirections: 16,
  slotsRefreshInterval: 5000,
  slotsRefreshTimeout: 2000,
  dnsLookup: (hostname, callback) => callback(null, hostname, 4),
  redisOptions: {
    connectTimeout: 3000,
    commandTimeout: 2000,
    enableAutoPipelining: true,
    retryStrategy(times: number) {
      // Jittered exponential backoff for failover reconnection
      const delay = Math.min(times * 100, 3000);
      return delay + Math.floor(Math.random() * 200);
    }
  }
};

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

valkeyCluster.on('node error', (err, node) => {
  console.warn(`[Valkey Failover] Error on node ${node.options.host}:${node.options.port}`, err);
});

// PRODUCTION INVARIANT: Slot pinning via {tenantId} or shared entity hash tag
export async function transferTenantCredits(
  tenantId: string,
  fromUser: string,
  toUser: string,
  amount: number
): Promise<boolean> {
  // Hash tag ensures both keys resolve to the identical Valkey 8.0 hash slot
  const senderKey = `{tenant:${tenantId}}:user:${fromUser}:bal`;
  const recipientKey = `{tenant:${tenantId}}:user:${toUser}:bal`;

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

  const result = await valkeyCluster.eval(atomicTransferLua, 2, senderKey, recipientKey, amount);
  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, Hash Slot Routing & Lua Atomicity Guardrails

Valkey 8.0 Multi-Threaded I/O, Hash Slot Routing & Lua Atomicity Guardrails defines an industrial-grade behavioral standard for backend engineering. Enforces strict hash-tag pinning for multi-key operations and Lua scripts in Valkey 8.0 clusters to prevent CROSSSLOT execution failures. Mandates non-blocking transactional script boundaries and resilient topology refresh configurations to safeguard Valkey 8.0 multi-threaded I/O pipelines during master 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 Cross-Slot Lua Scripts and Topology-Blind Retries Triggering Main-Thread Starvation and MOVED Storms 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 Cross-Slot Lua Scripts and Topology-Blind Retries Triggering Main-Thread Starvation and MOVED StormsCritical
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 curly brace hash tags (e.g., `{tenant

Engineers MUST ALWAYS enforce curly brace hash tags (e.g., `{tenant:123}:resource`) on all multi-key Valkey commands, pipelines, and Lua scripts to pin keys to a single 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 cross-slot Lua scripts or transactional multi-key commands without hash-tag affinity, as Valkey 8.0 Cluster strictly returns `CROSSSLOT Keys in request don't hash to the same slot`.

Engineers MUST NOT execute cross-slot Lua scripts or transactional multi-key commands without hash-tag affinity, as Valkey 8.0 Cluster strictly returns `CROSSSLOT Keys in request don't hash to the same 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.
3

Engineers MUST NOT execute long-running O(N) operations inside Lua scripts or functions

Engineers MUST NOT execute long-running O(N) operations inside Lua scripts or functions; Valkey 8.0 parallelizes socket I/O across worker threads, but core command execution remains strictly single-threaded.

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 configure cluster clients with active topology refreshes (`slotsRefreshInterval`, `enableAutoPipelining`, and DNS re-resolution) to prevent MOVED redirect loops and packet drops during cluster failover.

Services MUST configure cluster clients with active topology refreshes (`slotsRefreshInterval`, `enableAutoPipelining`, and DNS re-resolution) to prevent MOVED redirect loops and packet drops during cluster 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.
5

Components NEVER hardcode node endpoints or execute stateful transactions during failover windows without backoff limits and reconnection rate-limiting.

Components NEVER hardcode node endpoints or execute stateful transactions during failover windows without backoff limits and reconnection rate-limiting.

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, Hash Slot Routing & Lua Atomicity Guardrails critical for AI coding assistants?

Enforces strict hash-tag pinning for multi-key operations and Lua scripts in Valkey 8.0 clusters to prevent CROSSSLOT execution failures. Mandates non-blocking transactional script boundaries and resilient topology refresh configurations to safeguard Valkey 8.0 multi-threaded I/O pipelines during master 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 Cross-Slot Lua Scripts and Topology-Blind Retries Triggering Main-Thread Starvation and MOVED Storms) 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