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

Valkey 8.0 Cluster Hash Tagging, Redirection Handling, and Non-Blocking Scripting

Valkey 8.0 multi-threaded I/O parallelizes socket read/write processing across I/O threads but maintains single-threaded execution semantics for data mutability and cluster slot routing across nodes (slots 0-16383). Developers must enforce explicit hash tagging for multi-key atomicity, strictly declare all keys in Lua or Function execution to prevent cross-slot deadlocks, and implement resilient MOVED and ASK redirection handlers with slot cache invalidation during cluster failover.

Prohibited Anti-Pattern: Cross-Slot Lua Execution and Unhandled Failover Redirections Inducing Stalled I/O Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Hash Tagging, Redirection Handling, and Non-Blocking Scripting - Valkey 8.0 multi-threaded I/O parallelizes socket read/write processing across I/O threads but maintains single-threaded execution semantics for data mutability and cluster slot routing across nodes (slots 0-16383). Developers must enforce explicit hash tagging for multi-key atomicity, strictly declare all keys in Lua or Function execution to prevent cross-slot deadlocks, and implement resilient MOVED and ASK redirection handlers with slot cache invalidation during cluster failover.
globs: src/**/*.{ts,js,py,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-slot-routing-atomicity"
---

# Valkey 8.0 Cluster Hash Tagging, Redirection Handling, and Non-Blocking Scripting

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Cross-Slot Lua Execution and Unhandled Failover Redirections Inducing Stalled I/O Pipelines

## System Constraints
You are a Principal Backend Architect enforcing strict Valkey 8.0 cluster invariants. Valkey 8.0 optimizes network I/O via multi-threaded event demuxing, but commands within cluster topologies require rigorous slot adherence and non-blocking guarantees. Reject any code constructing cross-slot multi-key operations without hash tags, mandate cluster-aware client redirection handling (MOVED/ASK), and ensure Lua scripts and Valkey Functions declare all mutated keys explicitly in KEYS arrays to prevent distributed race conditions during master-replica failovers.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit hash tags `{...}` on multi-key operations and Lua script keys to guarantee all targeted keys hash to the identical Valkey cluster slot (CRC16 % 16384).
- Engineers MUST NOT hardcode key names inside Lua scripts or Valkey 8 Functions via ARGV or string concatenation; all referenced keys MUST be passed through the `KEYS` table.
- Services MUST configure cluster clients with auto-refresh topology listeners triggered by `MOVED` errors, and execute `ASKING` commands immediately prior to redirect targets when receiving `ASK` responses.
- Engineers MUST NOT execute long-running or unbounded O(N) operations inside Lua scripts (such as `KEYS`, `SMEMBERS` on giant sets, or full table iterations), as they block the execution core despite threaded I/O.
- Code SHOULD configure exponential backoff and jitter for slot redirection retries with a maximum cap to prevent connection stampedes during failover leader election.
- Components NEVER execute multi-key transactions (`MGET`, `MSET`, `EVAL`) across heterogeneous hash tags in cluster mode; decompose or hash-tag systematically.

## Bad vs Good Implementations
### Valkey 8.0 Cluster Hash Tagging and Slot Safe Script Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Valkey cluster routing inspects KEYS[1] to map requests to the correct shard. Passing keys inside ARGV bypasses cluster proxy routing, and using un-tagged user balance keys ('balance:123' vs 'balance:456') guarantees a CROSSSLOT exception because they hash to different cluster slots (0-16383).
```typescript
import { Cluster } from 'ioredis';

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

// ANTI-PATTERN: Multi-key script uses keys in different cluster slots.
// Keys will hash to different slots, triggering CROSSSLOT errors.
// Hardcoding keys inside script hides dependencies from Valkey cluster routing.
export async function transferTokens(sourceUserId: string, targetUserId: string, amount: number) {
  const script = `
    local srcBalance = tonumber(redis.call('get', 'balance:' .. ARGV[1]) or '0')
    if srcBalance < tonumber(ARGV[3]) then
      return -1
    end
    redis.call('decrby', 'balance:' .. ARGV[1], ARGV[3])
    redis.call('incrby', 'balance:' .. ARGV[2], ARGV[3])
    return 0
  `;

  // No KEYS provided, bypassing cluster proxy slot verification
  return await cluster.eval(script, 0, sourceUserId, targetUserId, amount.toString());
}
```

#### Production Standard (Correct)
> **Standard**: By using the hash tag `{tenant:${tenantId}}`, both keys are guaranteed to evaluate to the exact same CRC16 slot. Passing both keys explicitly via `KEYS` table allows the Valkey 8 cluster client and I/O threads to correctly route the command payload to the authoritative slot master, avoiding CROSSSLOT failures and supporting atomic failover handling.
```typescript
import { Cluster } from 'ioredis';

// Correctly configure Valkey 8.0 cluster client with failover tolerance
const cluster = new Cluster([{ host: 'valkey-node-1', port: 6379 }], {
  enableReadyCheck: true,
  maxRedirections: 16,
  slotsRefreshTimeout: 2000,
  retryDelayOnFailover: 100,
  scaleReads: 'master'
});

// PRODUCTION FIX: Co-locate shard data using Hash Tags '{...}' on common entity domain
export async function transferTenantTokens(
  tenantId: string,
  sourceUserId: string,
  targetUserId: string,
  amount: number
): Promise<number> {
  // Invariant: Keys share the {tenantId} hash tag, ensuring identical CRC16 slot mapping
  const sourceKey = `{tenant:${tenantId}}:user:${sourceUserId}:balance`;
  const targetKey = `{tenant:${tenantId}}:user:${targetUserId}:balance`;

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

  // Explicitly supply KEYS to allow cluster slot routing and multi-threaded I/O socket assignment
  const result = await cluster.eval(
    script,
    2,
    sourceKey,
    targetKey,
    amount.toString()
  );

  return Number(result);
}
```

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 Cluster Hash Tagging, Redirection Handling, and Non-Blocking Scripting

Valkey 8.0 Cluster Hash Tagging, Redirection Handling, and Non-Blocking Scripting defines an industrial-grade behavioral standard for backend engineering. Valkey 8.0 multi-threaded I/O parallelizes socket read/write processing across I/O threads but maintains single-threaded execution semantics for data mutability and cluster slot routing across nodes (slots 0-16383). Developers must enforce explicit hash tagging for multi-key atomicity, strictly declare all keys in Lua or Function execution to prevent cross-slot deadlocks, and implement resilient MOVED and ASK redirection handlers with slot cache invalidation during cluster 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 Lua Execution and Unhandled Failover Redirections Inducing Stalled I/O Pipelines 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 Lua Execution and Unhandled Failover Redirections Inducing Stalled I/O PipelinesCritical
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 explicit hash tags `{...}` on multi-key operations and Lua script keys to guarantee all targeted keys hash to the identical Valkey cluster slot (CRC16 % 16384).

Engineers MUST ALWAYS enforce explicit hash tags `{...}` on multi-key operations and Lua script keys to guarantee all targeted keys hash to the identical Valkey cluster slot (CRC16 % 16384).

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 hardcode key names inside Lua scripts or Valkey 8 Functions via ARGV or string concatenation

Engineers MUST NOT hardcode key names inside Lua scripts or Valkey 8 Functions via ARGV or string concatenation; all referenced keys MUST be passed through the `KEYS` table.

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

Services MUST configure cluster clients with auto-refresh topology listeners triggered by `MOVED` errors, and execute `ASKING` commands immediately prior to redirect targets when receiving `ASK` responses.

Services MUST configure cluster clients with auto-refresh topology listeners triggered by `MOVED` errors, and execute `ASKING` commands immediately prior to redirect targets when receiving `ASK` responses.

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 NOT execute long-running or unbounded O(N) operations inside Lua scripts (such as `KEYS`, `SMEMBERS` on giant sets, or full table iterations), as they block the execution core despite threaded I/O.

Engineers MUST NOT execute long-running or unbounded O(N) operations inside Lua scripts (such as `KEYS`, `SMEMBERS` on giant sets, or full table iterations), as they block the execution core despite threaded I/O.

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

Code SHOULD configure exponential backoff and jitter for slot redirection retries with a maximum cap to prevent connection stampedes during failover leader election.

Code SHOULD configure exponential backoff and jitter for slot redirection retries with a maximum cap to prevent connection stampedes during failover leader election.

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

Components NEVER execute multi-key transactions (`MGET`, `MSET`, `EVAL`) across heterogeneous hash tags in cluster mode

Components NEVER execute multi-key transactions (`MGET`, `MSET`, `EVAL`) across heterogeneous hash tags in cluster mode; decompose or hash-tag systematically.

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 Cluster Hash Tagging, Redirection Handling, and Non-Blocking Scripting critical for AI coding assistants?

Valkey 8.0 multi-threaded I/O parallelizes socket read/write processing across I/O threads but maintains single-threaded execution semantics for data mutability and cluster slot routing across nodes (slots 0-16383). Developers must enforce explicit hash tagging for multi-key atomicity, strictly declare all keys in Lua or Function execution to prevent cross-slot deadlocks, and implement resilient MOVED and ASK redirection handlers with slot cache invalidation during cluster 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 Lua Execution and Unhandled Failover Redirections Inducing Stalled I/O Pipelines) 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