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

Valkey 8.0 Cluster Topology, Failover Resiliency, and Slot-Pinned Script Execution

Mandates explicit hash-tag pinning for multi-key operations and Lua scripts to guarantee atomicity and prevent CROSSSLOT errors in Valkey 8.0 clusters. Requires dynamic cluster topology refreshes with exponential backoff on MOVED/ASK redirects to prevent connection thrashing during failovers. Enforces non-blocking execution pipelines to fully leverage Valkey 8.0 threaded I/O capabilities.

Prohibited Anti-Pattern: Unpinned Multi-Key Operations and Naive Redirect Handling Causing CROSSSLOT Aborts and Failover Cascades

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Topology, Failover Resiliency, and Slot-Pinned Script Execution - Mandates explicit hash-tag pinning for multi-key operations and Lua scripts to guarantee atomicity and prevent CROSSSLOT errors in Valkey 8.0 clusters. Requires dynamic cluster topology refreshes with exponential backoff on MOVED/ASK redirects to prevent connection thrashing during failovers. Enforces non-blocking execution pipelines to fully leverage Valkey 8.0 threaded I/O capabilities.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts, app/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-cluster-failover-atomicity-standard"
---

# Valkey 8.0 Cluster Topology, Failover Resiliency, and Slot-Pinned Script Execution

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unpinned Multi-Key Operations and Naive Redirect Handling Causing CROSSSLOT Aborts and Failover Cascades

## System Constraints
You are a Principal Backend Architect enforcing Valkey 8.0 production standards. Ensure all Valkey cluster operations adhere strictly to slot-pinning invariants via hash tags, maintain proper handle-and-refresh semantics for MOVED and ASK redirection errors, and prevent blocking commands that bottleneck threaded I/O pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS enforce hash tagging `{tag}` on all keys touched by a single Lua script, pipeline, or transaction to guarantee single-slot allocation.
- Engineers MUST NOT execute multi-key commands across different key partitions without explicit client-side fan-out orchestration.
- Services MUST configure cluster clients with automated slot topology discovery, periodic refreshing, and backoff-regulated retries for MOVED and ASK responses.
- Services MUST NOT block the single-threaded command evaluation engine with unbounded Lua scripts; scripts must execute in O(1) or small bounded O(N) operations.
- Clients MUST use non-blocking asynchronous multiplexing to prevent head-of-line blocking in Valkey 8.0 multi-threaded socket I/O.

## Bad vs Good Implementations
### Cluster-Aware Lua Script Execution with Hash-Tag Slot Pinning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In a Valkey cluster, keys without `{hash_tag}` are distributed across 16,384 slots. Running a multi-key Lua script where keys land on different slots results in an unhandled CROSSSLOT Keys exception. Additionally, raw eval without proper hash mapping fails during slot migration.
```typescript
import { Cluster } from 'ioredis';

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

// Anti-pattern: Keys hash to different slots, causing CROSSSLOT errors in cluster mode.
// Naive invocation lacks slot topology awareness and fails completely during node migration.
export async function transferBalanceBad(
  fromUserId: string,
  toUserId: string,
  amount: number
): Promise<boolean> {
  const 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
  `;

  // KEYS[1] and KEYS[2] will resolve to arbitrary hash slots
  const result = await cluster.eval(
    script,
    2,
    `user:${fromUserId}:balance`,
    `user:${toUserId}:balance`,
    amount.toString()
  );

  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: By encapsulating the common partition key within curly braces `{tenant:${tenantId}}`, Valkey computes the CRC16 checksum exclusively on the tagged substring, guaranteeing that all referenced keys resolve to the exact same hash slot. Cluster configuration options ensure automated slot updates on MOVED/ASK redirects during node failover.
```typescript
import { Cluster, ClusterOptions } from 'ioredis';

const clusterOptions: ClusterOptions = {
  enableReadyCheck: true,
  scaleReads: 'master',
  slotsRefreshTimeout: 2000,
  // Dynamic topology discovery handles MOVED/ASK redirects automatically during failover
  dnsLookup: (address, callback) => callback(null, address),
  retryDelayOnClusterDown: 300,
  retryDelayOnFailover: 200,
  maxRedirections: 16,
};

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

// Production Invariant: Scoped within a common tenancy/shard domain using hash tags
// Ensures KEYS[1] and KEYS[2] map to the exact same hash slot on the current master node.
export async function updateTenantResources(
  tenantId: string,
  resourceA: string,
  resourceB: string,
  delta: number
): Promise<boolean> {
  const script = `
    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
  `;

  // Use {tenantId} hash tag to enforce identical slot assignment
  const key1 = `{tenant:${tenantId}}:res:${resourceA}`;
  const key2 = `{tenant:${tenantId}}:res:${resourceB}`;

  const result = await cluster.eval(script, 2, key1, key2, delta.toString());
  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 Cluster Topology, Failover Resiliency, and Slot-Pinned Script Execution

Valkey 8.0 Cluster Topology, Failover Resiliency, and Slot-Pinned Script Execution defines an industrial-grade behavioral standard for backend engineering. Mandates explicit hash-tag pinning for multi-key operations and Lua scripts to guarantee atomicity and prevent CROSSSLOT errors in Valkey 8.0 clusters. Requires dynamic cluster topology refreshes with exponential backoff on MOVED/ASK redirects to prevent connection thrashing during failovers. Enforces non-blocking execution pipelines to fully leverage Valkey 8.0 threaded I/O capabilities. 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 Operations and Naive Redirect Handling Causing CROSSSLOT Aborts and Failover Cascades 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 Operations and Naive Redirect Handling Causing CROSSSLOT Aborts and Failover CascadesCritical
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 `{tag}` on all keys touched by a single Lua script, pipeline, or transaction to guarantee single-slot allocation.

Engineers MUST ALWAYS enforce hash tagging `{tag}` on all keys touched by a single Lua script, pipeline, or transaction to guarantee single-slot allocation.

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 multi-key commands across different key partitions without explicit client-side fan-out orchestration.

Engineers MUST NOT execute multi-key commands across different key partitions without explicit client-side fan-out orchestration.

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 automated slot topology discovery, periodic refreshing, and backoff-regulated retries for MOVED and ASK responses.

Services MUST configure cluster clients with automated slot topology discovery, periodic refreshing, and backoff-regulated retries for MOVED and 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

Services MUST NOT block the single-threaded command evaluation engine with unbounded Lua scripts

Services MUST NOT block the single-threaded command evaluation engine with unbounded Lua scripts; scripts must execute in O(1) or small bounded O(N) 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.
5

Clients MUST use non-blocking asynchronous multiplexing to prevent head-of-line blocking in Valkey 8.0 multi-threaded socket I/O.

Clients MUST use non-blocking asynchronous multiplexing to prevent head-of-line blocking in Valkey 8.0 multi-threaded socket 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.
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 Topology, Failover Resiliency, and Slot-Pinned Script Execution critical for AI coding assistants?

Mandates explicit hash-tag pinning for multi-key operations and Lua scripts to guarantee atomicity and prevent CROSSSLOT errors in Valkey 8.0 clusters. Requires dynamic cluster topology refreshes with exponential backoff on MOVED/ASK redirects to prevent connection thrashing during failovers. Enforces non-blocking execution pipelines to fully leverage Valkey 8.0 threaded I/O capabilities. 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 Operations and Naive Redirect Handling Causing CROSSSLOT Aborts and Failover Cascades) 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