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

Valkey 8 Dual-Channel Cluster Slot Migration Atomicity Guardrail

Maintains distributed cache linearizability and guarantees zero cross-slot key drift during horizontal node re-sharding in multi-terabyte Valkey 8 clusters. Enforces strict dual-channel slot synchronization by locking slot routing states, rejecting non-deterministic multi-key atomic mutations during the MIGRATING/IMPORTING handshake, and ensuring deterministic fallbacks upon ASK and MOVED redirections.

Prohibited Anti-Pattern: Unchecked Cross-Slot Command Execution and Blind Client Writes During Active Dual-Channel Slot Re-Sharding

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8 Dual-Channel Cluster Slot Migration Atomicity Guardrail - Maintains distributed cache linearizability and guarantees zero cross-slot key drift during horizontal node re-sharding in multi-terabyte Valkey 8 clusters. Enforces strict dual-channel slot synchronization by locking slot routing states, rejecting non-deterministic multi-key atomic mutations during the MIGRATING/IMPORTING handshake, and ensuring deterministic fallbacks upon ASK and MOVED redirections.
globs: src/infrastructure/cache/**/*.{ts,js,py,go}, src/lib/valkey/**/*.{ts,js,py,go}, src/services/cluster/**/*.{ts,js,py,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-8-dual-channel-migration-atomicity"
---

# Valkey 8 Dual-Channel Cluster Slot Migration Atomicity Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked Cross-Slot Command Execution and Blind Client Writes During Active Dual-Channel Slot Re-Sharding

## System Constraints
You are a Principal Distributed Systems Engineer enforcing strict Valkey 8 Dual-Channel Cluster Slot Migration Atomicity. Mandate invariants that prevent data corruption, silent key divergence, and stale reads during horizontal rebalancing. Ensure that every client interaction honors dual-channel cluster specifications, dynamic ASK/MOVED state handling, explicit key hash tagging for multi-key pipelines, and linearizable two-phase slot state handoffs.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit Valkey 8 hash tags (e.g., `{tenant:123}:key`) on all co-located multi-key operations to guarantee single-slot assignment during partition migrations.
- Engineers MUST NOT execute raw multi-key commands or batch pipelines across keys without verifying identical 16384 slot hashes when the cluster is in an active rebalancing state.
- Code SHOULD handle dynamic Valkey 8 dual-channel redirection by executing ASKING prior to re-dispatching commands to the IMPORTING node upon receiving an `-ASK` error.
- Services MUST implement an exponential backoff circuit breaker for cluster topology topology refresh (CLUSTER SLOTS / CLUSTER SHARDS) on recurring `-MOVED` errors to avoid thundering herds.
- Components NEVER issue non-idempotent blind writes directly against a slot marked in the local routing table as `MIGRATING` without routing verification against the target dual-channel receiver.

## Bad vs Good Implementations
### Dual-Channel Re-sharding ASK/MOVED Handling and Slot-Safe Pipeline Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to encapsulate keys with hash tags `{tenantId}` allows multi-key operations to scatter across disparate hash slots. During Valkey 8 dual-channel migration, half of the keys may exist on the MIGRATING node while the rest have moved to the IMPORTING node, triggering fatal CROSSSLOT errors and breaking atomicity without handling `-ASK` or `-MOVED` redirections.
```typescript
import { Redis } from 'iovalkey';

// ANTI-PATTERN: Blind execution without hash tagging or dynamic dual-channel ASK retry logic
export async function migrateTenantBatch(client: Redis, tenantId: string, updates: Record<string, string>) {
  const pipeline = client.pipeline();
  for (const [subKey, value] of Object.entries(updates)) {
    // Cross-slot drift: Keys without explicit hash tags spread across arbitrary slots
    pipeline.set(`tenant:${tenantId}:${subKey}`, value);
  }
  // Fails with CROSSSLOT or produces silent inconsistency during Valkey 8 slot migration
  return await pipeline.exec();
}
```

#### Production Standard (Correct)
> **Standard**: Enforces deterministic slot co-location using `{tenantId}` hash-tagging. Captures runtime migration redirect exceptions (`-ASK`), seamlessly executing the mandatory `ASKING` preamble protocol against the dual-channel IMPORTING target node, thereby preserving cluster linearizability without data loss.
```typescript
import { Redis, ChainableCommander } from 'iovalkey';

// PRODUCTION INVARIANT: Enforce atomic hash tags and explicit dual-channel ASK-aware execution
export async function migrateTenantBatch(
  client: Redis,
  clusterNodes: Map<string, Redis>,
  tenantId: string,
  updates: Record<string, string>
): Promise<void> {
  const taggedKey = (k: string): string => `tenant:{${tenantId}}:${k}`;
  const entries = Object.entries(updates);
  if (entries.length === 0) return;

  const executeWrite = async (targetClient: Redis, isAsking: boolean = false): Promise<void> => {
    const pipe: ChainableCommander = targetClient.pipeline();
    if (isAsking) {
      pipe.asking();
    }
    for (const [subKey, value] of entries) {
      pipe.set(taggedKey(subKey), value);
    }
    const results = await pipe.exec();
    if (!results) throw new Error('Pipeline returned null response during migration write');
    
    for (const [err] of results) {
      if (err) throw err;
    }
  };

  try {
    await executeWrite(client);
  } catch (err: any) {
    if (typeof err?.message === 'string' && err.message.startsWith('ASK')) {
      const [, , targetHostPort] = err.message.split(' ');
      const targetNode = clusterNodes.get(targetHostPort);
      if (!targetNode) {
        throw new Error(`Target node ${targetHostPort} not found in dual-channel topology pool`);
      }
      // Linearizable migration handoff: dispatch ASKING to importing node
      await executeWrite(targetNode, true);
      return;
    }
    if (typeof err?.message === 'string' && err.message.startsWith('MOVED')) {
      // Re-trigger topology discovery on permanent slot relocation
      await client.cluster('SHARDS');
      throw err;
    }
    throw err;
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Valkey 8 Dual-Channel Cluster Slot Migration Atomicity Guardrail

Valkey 8 Dual-Channel Cluster Slot Migration Atomicity Guardrail defines an industrial-grade behavioral standard for backend engineering. Maintains distributed cache linearizability and guarantees zero cross-slot key drift during horizontal node re-sharding in multi-terabyte Valkey 8 clusters. Enforces strict dual-channel slot synchronization by locking slot routing states, rejecting non-deterministic multi-key atomic mutations during the MIGRATING/IMPORTING handshake, and ensuring deterministic fallbacks upon ASK and MOVED redirections. 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: Unchecked Cross-Slot Command Execution and Blind Client Writes During Active Dual-Channel Slot Re-Sharding 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 DriftUnchecked Cross-Slot Command Execution and Blind Client Writes During Active Dual-Channel Slot Re-ShardingCritical
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 Valkey 8 hash tags (e.g., `{tenant

Engineers MUST ALWAYS enforce explicit Valkey 8 hash tags (e.g., `{tenant:123}:key`) on all co-located multi-key operations to guarantee single-slot assignment during partition migrations.

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 raw multi-key commands or batch pipelines across keys without verifying identical 16384 slot hashes when the cluster is in an active rebalancing state.

Engineers MUST NOT execute raw multi-key commands or batch pipelines across keys without verifying identical 16384 slot hashes when the cluster is in an active rebalancing state.

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 handle dynamic Valkey 8 dual-channel redirection by executing ASKING prior to re-dispatching commands to the IMPORTING node upon receiving an `-ASK` error.

Code SHOULD handle dynamic Valkey 8 dual-channel redirection by executing ASKING prior to re-dispatching commands to the IMPORTING node upon receiving an `-ASK` error.

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 implement an exponential backoff circuit breaker for cluster topology topology refresh (CLUSTER SLOTS / CLUSTER SHARDS) on recurring `-MOVED` errors to avoid thundering herds.

Services MUST implement an exponential backoff circuit breaker for cluster topology topology refresh (CLUSTER SLOTS / CLUSTER SHARDS) on recurring `-MOVED` errors to avoid thundering herds.

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 issue non-idempotent blind writes directly against a slot marked in the local routing table as `MIGRATING` without routing verification against the target dual-channel receiver.

Components NEVER issue non-idempotent blind writes directly against a slot marked in the local routing table as `MIGRATING` without routing verification against the target dual-channel receiver.

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 Dual-Channel Cluster Slot Migration Atomicity Guardrail critical for AI coding assistants?

Maintains distributed cache linearizability and guarantees zero cross-slot key drift during horizontal node re-sharding in multi-terabyte Valkey 8 clusters. Enforces strict dual-channel slot synchronization by locking slot routing states, rejecting non-deterministic multi-key atomic mutations during the MIGRATING/IMPORTING handshake, and ensuring deterministic fallbacks upon ASK and MOVED redirections. 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 (Unchecked Cross-Slot Command Execution and Blind Client Writes During Active Dual-Channel Slot Re-Sharding) 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