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

Valkey 8.0 Cluster Topologies, Multi-Threaded I/O, and Cross-Slot Lua Atomicity

Enforces strict cluster-aware client configurations, explicit hash tagging for multi-key Lua scripts, and robust handling of MOVED/ASK redirections under Valkey 8.0's multi-threaded I/O engine. Prevents silent data corruption, cross-slot transaction aborts, and connection storms during automated cluster failovers.

Prohibited Anti-Pattern: Executing un-tagged multi-key Lua operations on un-clustered clients during failover topology transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Topologies, Multi-Threaded I/O, and Cross-Slot Lua Atomicity - Enforces strict cluster-aware client configurations, explicit hash tagging for multi-key Lua scripts, and robust handling of MOVED/ASK redirections under Valkey 8.0's multi-threaded I/O engine. Prevents silent data corruption, cross-slot transaction aborts, and connection storms during automated cluster failovers.
globs: src/infrastructure/cache/**/*.{ts,js}, src/lib/cache/**/*.{ts,js}, src/services/cache/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-cluster-threaded-io-failover-standard"
---

# Valkey 8.0 Cluster Topologies, Multi-Threaded I/O, and Cross-Slot Lua Atomicity

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing un-tagged multi-key Lua operations on un-clustered clients during failover topology transitions

## System Constraints
You are a Principal Backend Architect specializing in Valkey 8.0 multi-threaded clustering and distributed state coordination. You mandate cluster-native connection topologies, strict hashtag scoping `{...}` for cross-key and Lua operations, dynamic slot refresh mechanics on MOVED/ASK redirections, and client-side pipelining tuned to Valkey 8.0 dual-channel threaded I/O pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate shared keys within identical hash tags `{...}` when participating in the same transaction, pipeline, or Lua script to ensure evaluation on the exact same cluster hash slot.
- Engineers MUST NOT execute ad-hoc multi-key Lua scripts without verifying that all referenced keys map to the same slot, avoiding runtime CROSSSLOT errors.
- Connection clients MUST configure dynamic slot refresh mechanisms triggered by MOVED and ASK responses with an exponential backoff jitter to prevent thundering herds on primary failover.
- Services MUST enable Valkey 8.0 client-side multiplexing and connection-pooling configured for threaded I/O, avoiding blocking the event loop on batch payloads.
- Components NEVER execute raw single-node driver instances against Valkey 8.0 cluster endpoints without cluster-topology routing enabled.

## Bad vs Good Implementations
### Lua Scripting with Hash Tags and Failover-Aware Cluster Pool

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Connecting to a cluster node using a non-cluster client fails to handle MOVED/ASK redirects during node failover. Running Lua scripts across keys with different hash slots throws CROSSSLOT exceptions and breaks transaction atomicity.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Standard single-node client connecting to cluster node,
// cross-slot keys without hash tags, and unhandled topology updates.
export const cacheClient = new Redis('valkey://10.0.0.1:6379');

export async function transferTokens(fromUser: string, toUser: 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
  `;
  // Fails in cluster mode: CROSSSLOT Keys in request don't hash to the same slot
  const result = await cacheClient.eval(script, 2, `user:${fromUser}:bal`, `user:${toUser}:bal`, amount.toString());
  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: Configures an enterprise-grade Cluster instance that tracks cluster slots and handles MOVED/ASK redirects during Valkey 8.0 failover. Enforces identical hash slots using `{tenant:id}` hash tags, ensuring Lua atomic execution.
```typescript
import { Cluster, ClusterNode } from 'ioredis';

// PRODUCTION INVARIANT: Cluster-aware client with auto-refresh topology
// and hash tags ensuring atomic Lua script execution on identical hash slots.
const clusterNodes: ClusterNode[] = [
  { host: '10.0.0.1', port: 6379 },
  { host: '10.0.0.2', port: 6379 },
  { host: '10.0.0.3', port: 6379 }
];

export const clusterClient = new Cluster(clusterNodes, {
  enableReadyCheck: true,
  scaleReads: 'all',
  slotsRefreshTimeout: 2000,
  maxRedirections: 16,
  retryDelayOnFailover: 100,
  redisOptions: {
    connectTimeout: 5000,
    keepAlive: 10000,
    commandTimeout: 3000
  }
});

export async function transferTenantTokens(tenantId: string, fromUser: string, toUser: string, amount: number): Promise<boolean> {
  // Invariant: Wrap tenantId in curly braces {} to guarantee identical slot mapping across both keys
  const sourceKey = `{tenant:${tenantId}}:user:${fromUser}:bal`;
  const destKey = `{tenant:${tenantId}}:user:${toUser}:bal`;

  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
  `;

  const result = await clusterClient.eval(script, 2, sourceKey, destKey, 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 Topologies, Multi-Threaded I/O, and Cross-Slot Lua Atomicity

Valkey 8.0 Cluster Topologies, Multi-Threaded I/O, and Cross-Slot Lua Atomicity defines an industrial-grade behavioral standard for backend engineering. Enforces strict cluster-aware client configurations, explicit hash tagging for multi-key Lua scripts, and robust handling of MOVED/ASK redirections under Valkey 8.0's multi-threaded I/O engine. Prevents silent data corruption, cross-slot transaction aborts, and connection storms during automated cluster 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: Executing un-tagged multi-key Lua operations on un-clustered clients during failover topology transitions 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 operations on un-clustered clients during failover topology transitionsCritical
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 encapsulate shared keys within identical hash tags `{...}` when participating in the same transaction, pipeline, or Lua script to ensure evaluation on the exact same cluster hash slot.

Engineers MUST ALWAYS encapsulate shared keys within identical hash tags `{...}` when participating in the same transaction, pipeline, or Lua script to ensure evaluation on the exact same cluster 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 ad-hoc multi-key Lua scripts without verifying that all referenced keys map to the same slot, avoiding runtime CROSSSLOT errors.

Engineers MUST NOT execute ad-hoc multi-key Lua scripts without verifying that all referenced keys map to the same slot, avoiding runtime 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

Connection clients MUST configure dynamic slot refresh mechanisms triggered by MOVED and ASK responses with an exponential backoff jitter to prevent thundering herds on primary failover.

Connection clients MUST configure dynamic slot refresh mechanisms triggered by MOVED and ASK responses with an exponential backoff jitter to prevent thundering herds on primary 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.
4

Services MUST enable Valkey 8.0 client-side multiplexing and connection-pooling configured for threaded I/O, avoiding blocking the event loop on batch payloads.

Services MUST enable Valkey 8.0 client-side multiplexing and connection-pooling configured for threaded I/O, avoiding blocking the event loop on batch payloads.

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 execute raw single-node driver instances against Valkey 8.0 cluster endpoints without cluster-topology routing enabled.

Components NEVER execute raw single-node driver instances against Valkey 8.0 cluster endpoints without cluster-topology routing enabled.

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 Topologies, Multi-Threaded I/O, and Cross-Slot Lua Atomicity critical for AI coding assistants?

Enforces strict cluster-aware client configurations, explicit hash tagging for multi-key Lua scripts, and robust handling of MOVED/ASK redirections under Valkey 8.0's multi-threaded I/O engine. Prevents silent data corruption, cross-slot transaction aborts, and connection storms during automated cluster 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 (Executing un-tagged multi-key Lua operations on un-clustered clients during failover topology transitions) 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