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

Valkey 8.0 Threaded I/O Topology Refresh, Hash Slot Affinity, and Script Atomicity Guardrails

Enforces strict cluster slot affinity, dynamic topology discovery, and non-blocking transaction patterns for Valkey 8.0 deployments. Guarantees zero CROSSSLOT script aborts, deterministic client failover during master re-elections, and prevents head-of-line blocking under multi-threaded socket I/O configurations.

Prohibited Anti-Pattern: Executing un-hashed multi-key Lua scripts against naive single-node clients during Valkey cluster failovers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Threaded I/O Topology Refresh, Hash Slot Affinity, and Script Atomicity Guardrails - Enforces strict cluster slot affinity, dynamic topology discovery, and non-blocking transaction patterns for Valkey 8.0 deployments. Guarantees zero CROSSSLOT script aborts, deterministic client failover during master re-elections, and prevents head-of-line blocking under multi-threaded socket I/O configurations.
globs: src/infrastructure/cache/**/*.ts, src/infrastructure/valkey/**/*.ts, src/lib/valkey/**/*.ts, src/modules/**/cache/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-threaded-io-cluster-topology-standard"
---

# Valkey 8.0 Threaded I/O Topology Refresh, Hash Slot Affinity, and Script Atomicity Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing un-hashed multi-key Lua scripts against naive single-node clients during Valkey cluster failovers.

## System Constraints
You are a Principal Backend Architect specializing in high-throughput distributed memory stores. Enforce strict Valkey 8.0 cluster resilience, threaded I/O configuration awareness, and hash-slot co-location invariants. Reject any pull request that accesses multi-key resources across disparate hash slots in Lua/transactions or fails to implement cluster-aware failover protocols.

## Strict Guidelines
- Engineers MUST ALWAYS enforce key co-location using explicit hash tags (`{hashTag}suffix`) for all multi-key operations, Lua scripts (`EVAL`/`EVALSHA`), and Valkey functions (`FCALL`).
- Engineers MUST configure cluster-aware clients with dynamic topology refresh enabled on both `MOVED` redirects and periodic time intervals (e.g., `slotsRefreshIntervalMs: 5000`) to absorb failovers transparently.
- Engineers MUST NOT execute blocking operations or long-running computational loops inside Lua scripts, as Valkey 8.0 threaded I/O parallelizes network socket read/write cycles but retains single-threaded execution core atomicity.
- Code MUST explicitly distinguish between transient `ASK` redirection (handled with one-shot `ASKING` semantics) and permanent `MOVED` slot migrations to prevent topology corruption in the client routing table.
- Pipelines across disparate slots MUST use client-side scatter-gather routing rather than submitting multi-key commands directly to an arbitrary cluster node.

## Bad vs Good Implementations
### Cross-Slot Lua Script and Naive Client vs Slot-Tagged Resilient Cluster Client

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The client lacks cluster topology discovery, routing keys to arbitrary nodes and failing during master failovers. The Lua script accesses two distinct keys without hash tags (`org:...` vs `audit:...`), triggering a fatal Valkey cluster CROSSSLOT execution abort.
```typescript
import Redis from 'ioredis';

// ANTI-PATTERN: Standalone client used in cluster context;
// untagged keys cause CROSSSLOT errors; no failover recovery.
export const valkeyClient = new Redis(process.env.VALKEY_URL!);

export async function deductQuotaAndAudit(
  orgId: string,
  userId: string,
  cost: number
): Promise<boolean> {
  const script = `
    local quota = redis.call('GET', KEYS[1])
    if not quota or tonumber(quota) < tonumber(ARGV[1]) then
      return 0
    end
    redis.call('DECRBY', KEYS[1], ARGV[1])
    redis.call('XADD', KEYS[2], '*', 'user', ARGV[2], 'cost', ARGV[1])
    return 1
  `;

  // BUG: Keys hash to different slots -> CROSSSLOT error in Valkey Cluster
  const quotaKey = `org:${orgId}:quota`;
  const auditKey = `audit:${orgId}:stream`;

  const result = await valkeyClient.eval(script, 2, quotaKey, auditKey, cost, userId);
  return result === 1;
}
```

#### Production Standard (Correct)
> **Standard**: Uses an enterprise cluster configuration with proactive topology refreshes (`slotsRefreshInterval`) to gracefully absorb node failovers. Both keys utilize identical hash tags (`{org:${orgId}}`), ensuring assignment to the exact same cluster hash slot and guaranteeing atomic execution.
```typescript
import { Cluster, ClusterNode } from 'ioredis';

const clusterNodes: ClusterNode[] = [
  { host: process.env.VALKEY_PRIMARY_HOST!, port: Number(process.env.VALKEY_PORT) || 6379 }
];

// PRODUCTION INVARIANT: Dynamic topology discovery with slots refresh & backoff
export const valkeyCluster = new Cluster(clusterNodes, {
  scaleReads: 'slave',
  slotsRefreshInterval: 5000,
  slotsRefreshTimeout: 2000,
  maxRedirections: 16,
  retryDelayOnFailover: 100,
  retryDelayOnClusterDown: 250,
  redisOptions: {
    connectTimeout: 5000,
    commandTimeout: 2000,
    enableAutoPipelining: true
  }
});

export async function deductQuotaAndAudit(
  orgId: string,
  userId: string,
  cost: number
): Promise<boolean> {
  // PRODUCTION INVARIANT: Use {orgId} hash tags to guarantee identical slot mapping
  const quotaKey = `{org:${orgId}}:quota`;
  const auditKey = `{org:${orgId}}:audit:stream`;

  const script = `
    local quota = redis.call('GET', KEYS[1])
    if not quota or tonumber(quota) < tonumber(ARGV[1]) then
      return 0
    end
    redis.call('DECRBY', KEYS[1], ARGV[1])
    redis.call('XADD', KEYS[2], '*', 'user', ARGV[2], 'cost', ARGV[1])
    return 1
  `;

  const result = await valkeyCluster.eval(script, 2, quotaKey, auditKey, cost, userId);
  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 Threaded I/O Topology Refresh, Hash Slot Affinity, and Script Atomicity Guardrails

Valkey 8.0 Threaded I/O Topology Refresh, Hash Slot Affinity, and Script Atomicity Guardrails defines an industrial-grade behavioral standard for backend engineering. Enforces strict cluster slot affinity, dynamic topology discovery, and non-blocking transaction patterns for Valkey 8.0 deployments. Guarantees zero CROSSSLOT script aborts, deterministic client failover during master re-elections, and prevents head-of-line blocking under multi-threaded socket I/O configurations. 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-hashed multi-key Lua scripts against naive single-node clients during Valkey cluster failovers. 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-hashed multi-key Lua scripts against naive single-node clients during Valkey cluster failovers.Critical
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 key co-location using explicit hash tags (`{hashTag}suffix`) for all multi-key operations, Lua scripts (`EVAL`/`EVALSHA`), and Valkey functions (`FCALL`).

Engineers MUST ALWAYS enforce key co-location using explicit hash tags (`{hashTag}suffix`) for all multi-key operations, Lua scripts (`EVAL`/`EVALSHA`), and Valkey functions (`FCALL`).

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 configure cluster-aware clients with dynamic topology refresh enabled on both `MOVED` redirects and periodic time intervals (e.g., `slotsRefreshIntervalMs

Engineers MUST configure cluster-aware clients with dynamic topology refresh enabled on both `MOVED` redirects and periodic time intervals (e.g., `slotsRefreshIntervalMs: 5000`) to absorb failovers transparently.

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 blocking operations or long-running computational loops inside Lua scripts, as Valkey 8.0 threaded I/O parallelizes network socket read/write cycles but retains single-threaded execution core atomicity.

Engineers MUST NOT execute blocking operations or long-running computational loops inside Lua scripts, as Valkey 8.0 threaded I/O parallelizes network socket read/write cycles but retains single-threaded execution core atomicity.

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

Code MUST explicitly distinguish between transient `ASK` redirection (handled with one-shot `ASKING` semantics) and permanent `MOVED` slot migrations to prevent topology corruption in the client routing table.

Code MUST explicitly distinguish between transient `ASK` redirection (handled with one-shot `ASKING` semantics) and permanent `MOVED` slot migrations to prevent topology corruption in the client routing 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.
5

Pipelines across disparate slots MUST use client-side scatter-gather routing rather than submitting multi-key commands directly to an arbitrary cluster node.

Pipelines across disparate slots MUST use client-side scatter-gather routing rather than submitting multi-key commands directly to an arbitrary cluster node.

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 Threaded I/O Topology Refresh, Hash Slot Affinity, and Script Atomicity Guardrails critical for AI coding assistants?

Enforces strict cluster slot affinity, dynamic topology discovery, and non-blocking transaction patterns for Valkey 8.0 deployments. Guarantees zero CROSSSLOT script aborts, deterministic client failover during master re-elections, and prevents head-of-line blocking under multi-threaded socket I/O configurations. 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-hashed multi-key Lua scripts against naive single-node clients during Valkey cluster failovers.) 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