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

Valkey 8.0 Cluster Hash Tagging, Redirection & Failover Invariants

Valkey 8.0 leverages multi-threaded I/O for socket processing while enforcing single-threaded command determinism across 16,384 cluster slots. Distributed systems targeting Valkey Cluster MUST enforce hash tagging for multi-key operations and Lua scripts to prevent CROSSSLOT errors, and MUST handle MOVED/ASK redirections with managed topology refreshes during master failover.

Prohibited Anti-Pattern: Un-tagged Multi-Key Operations and Unbounded Redirection Failures During Cluster Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Hash Tagging, Redirection & Failover Invariants - Valkey 8.0 leverages multi-threaded I/O for socket processing while enforcing single-threaded command determinism across 16,384 cluster slots. Distributed systems targeting Valkey Cluster MUST enforce hash tagging for multi-key operations and Lua scripts to prevent CROSSSLOT errors, and MUST handle MOVED/ASK redirections with managed topology refreshes during master failover.
globs: src/**/*.{ts,js,py,go}, lib/**/*.{ts,js,py,go}, config/valkey*.conf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-cluster-slot-atomicity-failover"
---

# Valkey 8.0 Cluster Hash Tagging, Redirection & Failover Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Un-tagged Multi-Key Operations and Unbounded Redirection Failures During Cluster Failover

## System Constraints
You are a Principal Backend Architect enforcing Valkey 8.0 Threaded I/O & Cluster Failover invariants. Multi-threaded I/O offloads network socket read/write cycles, but cluster execution remains partitioned across 16,384 slots. You must strictly mandate that all multi-key commands, atomic pipelines, and Lua scripts encapsulate routing keys in hash tags ({...}) to ensure deterministic single-slot collocation. Furthermore, you must verify that cluster clients actively manage MOVED and ASK redirection retries with bounded exponential backoff, cluster slot cache refreshes, and READONLY replica routing to prevent service degradation during automated node failovers.

## Strict Guidelines
- Engineers MUST ALWAYS enclose common routing identifiers in hash tags (e.g., `{tenant:100}:account` and `{tenant:100}:profile`) for any multi-key commands, transactions (MULTI/EXEC), or Lua scripts in Valkey Cluster.
- Engineers MUST NOT execute Lua scripts or multi-key operations across keys that hash to disparate slots, as Valkey 8.0 immediately rejects these with fatal CROSSSLOT errors.
- Code SHOULD configure cluster clients with auto-topology refresh triggers (`slotsRefreshTimeout`, cluster state updates on `MOVED` events) and bounded retries to handle split-second master election without dropped operations.
- Services MUST route read-only queries to replicas using explicit `READONLY` cluster handshake protocols only when eventual consistency is explicitly tolerated by business logic.
- Components NEVER treat `MOVED` and `ASK` errors as generic unhandled infrastructure exceptions; client drivers must transparently follow redirections while executing ASK commands only for the single subsequent operation.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Lua script executes against two independent keys (`user:${fromUser}:balance` and `user:${toUser}:balance`) which map to different cluster slots. In Valkey Cluster mode, this immediately fails with a CROSSSLOT error. Additionally, the cluster client lacks failover retry strategies, slot refresh handling, and IO error backoff for cluster node failover events.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Default non-cluster client or unmanaged cluster client with disparate key slots
const client = new Redis.Cluster([
  { host: 'valkey-node-1.internal', port: 6379 }
]);

export async function transferCredits(fromUser: string, toUser: string, amount: number): Promise<boolean> {
  // FAILS: In Valkey Cluster, fromUser and toUser hash to different slots out of 16384.
  // This triggers a runtime: 'CROSSSLOT Keys in request don't hash to the same slot' error.
  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
  `;

  const result = await client.eval(
    luaScript,
    2,
    `user:${fromUser}:balance`,
    `user:${toUser}:balance`,
    amount
  );

  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: Hash tags `{tenant:${tenantId}}` ensure that both keys hash to the identical slot (0-16383), preserving Lua atomicity and eliminating CROSSSLOT errors. The cluster client configuration specifies explicit `slotsRefreshTimeout` and a bounded `clusterRetryStrategy`, ensuring resilience during automated master failover and topology resharding.
```typescript
import { Cluster, ClusterNode, ClusterOptions } from 'ioredis';

const clusterNodes: ClusterNode[] = [
  { host: 'valkey-node-1.internal', port: 6379 },
  { host: 'valkey-node-2.internal', port: 6379 },
  { host: 'valkey-node-3.internal', port: 6379 }
];

const clusterOptions: ClusterOptions = {
  enableReadyCheck: true,
  // Automatically refresh slot mapping on cluster failover
  slotsRefreshTimeout: 2000,
  autoPipelining: true,
  clusterRetryStrategy: (times: number) => {
    if (times > 5) return null; // Terminate after 5 bounded retries
    return Math.min(times * 100, 1000); // Exponential backoff with jitter ceiling
  },
  redisOptions: {
    connectTimeout: 5000,
    commandTimeout: 3000,
    enableAutoPipelining: true
  }
};

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

// PRODUCTION FIX: Anchor keys to identical slot using hash tags {shardId}
export async function transferTenantCredits(
  tenantId: string,
  fromAccount: string,
  toAccount: string,
  amount: number
): Promise<boolean> {
  // Valkey hashes solely the content within '{...}' guaranteeing identical slot mapping
  const sourceKey = `balance:{tenant:${tenantId}}:${fromAccount}`;
  const targetKey = `balance:{tenant:${tenantId}}:${toAccount}`;

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

  const result = await valkeyCluster.eval(
    luaScript,
    2,
    sourceKey,
    targetKey,
    amount.toString()
  );

  return Number(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 Cluster Hash Tagging, Redirection & Failover Invariants

Valkey 8.0 Cluster Hash Tagging, Redirection & Failover Invariants defines an industrial-grade behavioral standard for backend engineering. Valkey 8.0 leverages multi-threaded I/O for socket processing while enforcing single-threaded command determinism across 16,384 cluster slots. Distributed systems targeting Valkey Cluster MUST enforce hash tagging for multi-key operations and Lua scripts to prevent CROSSSLOT errors, and MUST handle MOVED/ASK redirections with managed topology refreshes during master 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: Un-tagged Multi-Key Operations and Unbounded Redirection Failures During Cluster 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 DriftUn-tagged Multi-Key Operations and Unbounded Redirection Failures During Cluster 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 enclose common routing identifiers in hash tags (e.g., `{tenant

Engineers MUST ALWAYS enclose common routing identifiers in hash tags (e.g., `{tenant:100}:account` and `{tenant:100}:profile`) for any multi-key commands, transactions (MULTI/EXEC), or Lua scripts in Valkey Cluster.

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 multi-key operations across keys that hash to disparate slots, as Valkey 8.0 immediately rejects these with fatal CROSSSLOT errors.

Engineers MUST NOT execute Lua scripts or multi-key operations across keys that hash to disparate slots, as Valkey 8.0 immediately rejects these with fatal 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.
3

Code SHOULD configure cluster clients with auto-topology refresh triggers (`slotsRefreshTimeout`, cluster state updates on `MOVED` events) and bounded retries to handle split-second master election without dropped operations.

Code SHOULD configure cluster clients with auto-topology refresh triggers (`slotsRefreshTimeout`, cluster state updates on `MOVED` events) and bounded retries to handle split-second master election without dropped operations.

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 route read-only queries to replicas using explicit `READONLY` cluster handshake protocols only when eventual consistency is explicitly tolerated by business logic.

Services MUST route read-only queries to replicas using explicit `READONLY` cluster handshake protocols only when eventual consistency is explicitly tolerated by business logic.

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 treat `MOVED` and `ASK` errors as generic unhandled infrastructure exceptions

Components NEVER treat `MOVED` and `ASK` errors as generic unhandled infrastructure exceptions; client drivers must transparently follow redirections while executing ASK commands only for the single subsequent operation.

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 & Failover Invariants critical for AI coding assistants?

Valkey 8.0 leverages multi-threaded I/O for socket processing while enforcing single-threaded command determinism across 16,384 cluster slots. Distributed systems targeting Valkey Cluster MUST enforce hash tagging for multi-key operations and Lua scripts to prevent CROSSSLOT errors, and MUST handle MOVED/ASK redirections with managed topology refreshes during master 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 (Un-tagged Multi-Key Operations and Unbounded Redirection Failures During Cluster 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