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

Valkey 8.0 Cluster Dual-Channel Slot Migration & Zero-Loss Rebalancing Guardrail

Enforces strict synchronization between client routing topology caches (MOVED/ASK tracking) and replica stream offsets during Valkey 8.0 slot live rebalancing. Prevents split-brain routing and phantom writes by coordinating cluster slot state updates across dual channels (active client protocol connection and asynchronous replica feed).

Prohibited Anti-Pattern: Uncoordinated CLUSTER SETSLOT propagation leading to stale client routing, ASK/MOVED loops, and asynchronous replica drop

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Valkey 8.0 Cluster Dual-Channel Slot Migration & Zero-Loss Rebalancing Guardrail - Enforces strict synchronization between client routing topology caches (MOVED/ASK tracking) and replica stream offsets during Valkey 8.0 slot live rebalancing. Prevents split-brain routing and phantom writes by coordinating cluster slot state updates across dual channels (active client protocol connection and asynchronous replica feed).
globs: src/infrastructure/valkey/**/*.ts, src/infrastructure/cache/**/*.ts, src/lib/cluster/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/valkey-cluster-dual-channel-slot-migration-guardrail"
---

# Valkey 8.0 Cluster Dual-Channel Slot Migration & Zero-Loss Rebalancing Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated CLUSTER SETSLOT propagation leading to stale client routing, ASK/MOVED loops, and asynchronous replica drop

## System Constraints
You are a Principal Engineer enforcing Valkey 8.0 Cluster Dual-Channel Slot Migration Guardrail. Mandate atomic two-phase slot state transitions (IMPORTING/MIGRATING -> NODE), dual-channel client topology invalidation, and strict replica offset verification before committing slot ownership across nodes.

## Strict Guidelines
- Engineers MUST ALWAYS issue CLUSTER SETSLOT <slot> IMPORTING on the target node before issuing CLUSTER SETSLOT <slot> MIGRATING on the source node to prevent routing split-brain.
- Engineers MUST NOT finalize slot ownership via CLUSTER SETSLOT <slot> NODE <node-id> until all pending keys in the slot are evacuated and the replica lag offset delta is confirmed to be zero.
- Code SHOULD handle Valkey ASK redirects by issuing ASKING before executing the payload on the target node, while preserving the client's internal slot map until a canonical MOVED response is received.
- Services MUST publish an epoch bump and actively invalidate local cluster route caches across all application node instances upon receiving MOVED or cluster topology epoch changes.
- Components NEVER issue blind writes to keys in a slot marked MIGRATING without transactional locking or atomic pipelined verification of the key's migration state.

## Bad vs Good Implementations
### Valkey 8.0 Dual-Channel Rebalance Execution and Route Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly assigning slot ownership with SETSLOT NODE skips the IMPORTING and MIGRATING states. Clients unaware of this immediate cutover will experience write rejections or write to both shards simultaneously, leading to silent data divergence and uncoordinated replica dropouts.
```typescript
import { ValkeyCluster } from 'iovalkey';

export async function rebalanceSlotUnsafe(cluster: ValkeyCluster, slot: number, sourceNodeId: string, targetNodeId: string): Promise<void> {
  // Flawed: Sets NODE directly without IMPORTING/MIGRATING protocol handshake,
  // causing split-brain routing and dropping replication sync.
  const targetNode = cluster.nodes('all').find((n) => n.options.id === targetNodeId);
  if (!targetNode) throw new Error('Target node missing');

  await targetNode.cluster('SETSLOT', slot, 'NODE', targetNodeId);
  // Keys remain unmigrated on the source node while target takes ownership immediately.
}
```

#### Production Standard (Correct)
> **Standard**: Correctly executes the two-phase migration lifecycle: establishes IMPORTING on target, MIGRATING on source, migrates keys via MIGRATE KEYS, commits ownership to the target across both nodes, and updates client routing caches to synchronize the dual-channel stream.
```typescript
import { Valkey, ValkeyCluster } from 'iovalkey';

export async function rebalanceSlotSafe(
  cluster: ValkeyCluster,
  slot: number,
  sourceNode: Valkey,
  targetNode: Valkey,
  targetNodeId: string,
  migrationBatchSize = 100
): Promise<void> {
  const sourceNodeId = await sourceNode.cluster('MYID') as string;

  // Phase 1: Set IMPORTING on target, then MIGRATING on source
  await targetNode.cluster('SETSLOT', slot, 'IMPORTING', sourceNodeId);
  await sourceNode.cluster('SETSLOT', slot, 'MIGRATING', targetNodeId);

  // Phase 2: Migrate keys in batched atomic transactions
  while (true) {
    const keys = await sourceNode.cluster('GETKEYSINSLOT', slot, migrationBatchSize) as string[];
    if (keys.length === 0) break;

    const targetHost = targetNode.options.host ?? '127.0.0.1';
    const targetPort = targetNode.options.port ?? 6379;
    await sourceNode.migrate(targetHost, targetPort, '', 0, 5000, 'KEYS', ...keys);
  }

  // Phase 3: Synchronize slot ownership propagation and update cluster epoch
  await targetNode.cluster('SETSLOT', slot, 'NODE', targetNodeId);
  await sourceNode.cluster('SETSLOT', slot, 'NODE', targetNodeId);
  
  // Invalidate dual-channel cached cluster routing slots across all cluster clients
  await cluster.refreshSlotsCache();
}
```

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 Dual-Channel Slot Migration & Zero-Loss Rebalancing Guardrail

Valkey 8.0 Cluster Dual-Channel Slot Migration & Zero-Loss Rebalancing Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict synchronization between client routing topology caches (MOVED/ASK tracking) and replica stream offsets during Valkey 8.0 slot live rebalancing. Prevents split-brain routing and phantom writes by coordinating cluster slot state updates across dual channels (active client protocol connection and asynchronous replica feed). 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: Uncoordinated CLUSTER SETSLOT propagation leading to stale client routing, ASK/MOVED loops, and asynchronous replica drop 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 DriftUncoordinated CLUSTER SETSLOT propagation leading to stale client routing, ASK/MOVED loops, and asynchronous replica dropCritical
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 issue CLUSTER SETSLOT <slot> IMPORTING on the target node before issuing CLUSTER SETSLOT <slot> MIGRATING on the source node to prevent routing split-brain.

Engineers MUST ALWAYS issue CLUSTER SETSLOT <slot> IMPORTING on the target node before issuing CLUSTER SETSLOT <slot> MIGRATING on the source node to prevent routing split-brain.

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 finalize slot ownership via CLUSTER SETSLOT <slot> NODE <node-id> until all pending keys in the slot are evacuated and the replica lag offset delta is confirmed to be zero.

Engineers MUST NOT finalize slot ownership via CLUSTER SETSLOT <slot> NODE <node-id> until all pending keys in the slot are evacuated and the replica lag offset delta is confirmed to be zero.

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 Valkey ASK redirects by issuing ASKING before executing the payload on the target node, while preserving the client's internal slot map until a canonical MOVED response is received.

Code SHOULD handle Valkey ASK redirects by issuing ASKING before executing the payload on the target node, while preserving the client's internal slot map until a canonical MOVED response is received.

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 publish an epoch bump and actively invalidate local cluster route caches across all application node instances upon receiving MOVED or cluster topology epoch changes.

Services MUST publish an epoch bump and actively invalidate local cluster route caches across all application node instances upon receiving MOVED or cluster topology epoch changes.

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 blind writes to keys in a slot marked MIGRATING without transactional locking or atomic pipelined verification of the key's migration state.

Components NEVER issue blind writes to keys in a slot marked MIGRATING without transactional locking or atomic pipelined verification of the key's migration 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.
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 Dual-Channel Slot Migration & Zero-Loss Rebalancing Guardrail critical for AI coding assistants?

Enforces strict synchronization between client routing topology caches (MOVED/ASK tracking) and replica stream offsets during Valkey 8.0 slot live rebalancing. Prevents split-brain routing and phantom writes by coordinating cluster slot state updates across dual channels (active client protocol connection and asynchronous replica feed). 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 (Uncoordinated CLUSTER SETSLOT propagation leading to stale client routing, ASK/MOVED loops, and asynchronous replica drop) 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