This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: react19-server-action-idempotency-protocol

React 19 Server Action Idempotency-Key Protocol & Optimistic Mutation Deduplication

Enforces strictly deduplicated, at-most-once mutation guarantees across transient client network retries during React 19 optimistic UI transitions. Requires client-side generation of cryptographically secure idempotency keys bounded to user action lifecycles and server-side atomic reservation before state execution.

Prohibited Anti-Pattern: Blind Server Action Invocations and Regenerated Request Keys Causing Duplicate Ledger Mutations on Transient Retries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React 19 Server Action Idempotency-Key Protocol & Optimistic Mutation Deduplication - Enforces strictly deduplicated, at-most-once mutation guarantees across transient client network retries during React 19 optimistic UI transitions. Requires client-side generation of cryptographically secure idempotency keys bounded to user action lifecycles and server-side atomic reservation before state execution.
globs: src/**/*.{ts,tsx}, app/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react19-server-action-idempotency-protocol"
---

# React 19 Server Action Idempotency-Key Protocol & Optimistic Mutation Deduplication

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Blind Server Action Invocations and Regenerated Request Keys Causing Duplicate Ledger Mutations on Transient Retries

## System Constraints
You are a Principal Engineer enforcing the React 19 Server Action Idempotency-Key Protocol. Mandate invariants that ensure non-idempotent mutations (e.g., billing, inventory, ledger state) executed via Server Actions and `useActionState`/`useOptimistic` transitions maintain at-most-once execution semantics under client network retries, connection drops, and double-submissions.

## Strict Guidelines
- Engineers MUST ALWAYS generate an immutable `idempotencyKey` on the client at the initiation of the user intent, binding it deterministically to the optimistic transaction lifecycle rather than deriving it inside the server action.
- Engineers MUST NOT generate a new `idempotencyKey` on transient network retries or component re-renders for the same user interaction.
- Components MUST pass the `idempotencyKey` explicitly as an input payload argument or signed hidden field within FormData to the React 19 Server Action.
- Server Actions MUST atomically verify, reserve, or claim the `idempotencyKey` in a shared transactional store (such as Redis with SET NX EX or Postgres advisory lock) prior to executing any mutation side effects.
- Server Actions MUST return the cached mutation result directly if the provided `idempotencyKey` has already been processed or is currently executing with an in-flight lease.
- Client UI components using `useOptimistic` MUST correlate optimistic rollbacks and reconciliations against the specific `idempotencyKey` instance to avoid desynchronizing stale states.

## Bad vs Good Implementations
### Naive Server Action invocation vs Deterministic Idempotency Key Protocol

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The server action lacks idempotency mechanics. If the client network drops before the response is acknowledged, React 19 transitions or user retries will trigger duplicate DB inserts and multiple billing operations.
```typescript
'use server';

import { db } from '@/lib/db';
import { revalidatePath } from 'next/cache';

// Anti-pattern: No idempotency tracking. Network retry duplicates charge.
export async function chargeCustomerAction(formData: FormData) {
  const customerId = formData.get('customerId') as string;
  const amount = Number(formData.get('amount'));

  // DANGEROUS: Concurrent clicks or transient retry creates duplicate charges
  const charge = await db.charges.create({
    data: { customerId, amount, status: 'succeeded' },
  });

  revalidatePath('/billing');
  return { success: true, chargeId: charge.id };
}
```

#### Production Standard (Correct)
> **Standard**: Employs an atomic reservation check (SET NX) using the client-provided idempotency key. Concurrent or repeated calls with the same key safely return cached results without re-executing stateful mutations.
```typescript
'use server';

import { db } from '@/lib/db';
import { redis } from '@/lib/redis';
import { revalidatePath } from 'next/cache';

interface ChargeResponse {
  success: boolean;
  chargeId: string;
  isReplay: boolean;
}

export async function chargeCustomerAction(
  idempotencyKey: string,
  formData: FormData
): Promise<ChargeResponse> {
  if (!idempotencyKey || typeof idempotencyKey !== 'string') {
    throw new Error('MISSING_IDEMPOTENCY_KEY');
  }

  const customerId = formData.get('customerId') as string;
  const amount = Number(formData.get('amount'));
  const cacheKey = `idempotency:${customerId}:${idempotencyKey}`;

  // Atomic lease reservation using Redis SET NX with 120s TTL
  const acquired = await redis.set(cacheKey, 'IN_FLIGHT', 'EX', 120, 'NX');

  if (!acquired) {
    const cachedResult = await redis.get(cacheKey);
    if (cachedResult && cachedResult !== 'IN_FLIGHT') {
      return { ...JSON.parse(cachedResult), isReplay: true };
    }
    throw new Error('CONCURRENT_MUTATION_IN_PROGRESS');
  }

  try {
    const charge = await db.charges.create({
      data: { customerId, amount, idempotencyKey, status: 'succeeded' },
    });

    const response: ChargeResponse = { success: true, chargeId: charge.id, isReplay: false };
    await redis.set(cacheKey, JSON.stringify(response), 'EX', 86400);

    revalidatePath('/billing');
    return response;
  } catch (error) {
    await redis.del(cacheKey);
    throw error;
  }
}
```

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: React 19 Server Action Idempotency-Key Protocol & Optimistic Mutation Deduplication

React 19 Server Action Idempotency-Key Protocol & Optimistic Mutation Deduplication defines an industrial-grade behavioral standard for frontend engineering. Enforces strictly deduplicated, at-most-once mutation guarantees across transient client network retries during React 19 optimistic UI transitions. Requires client-side generation of cryptographically secure idempotency keys bounded to user action lifecycles and server-side atomic reservation before state execution. 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: Blind Server Action Invocations and Regenerated Request Keys Causing Duplicate Ledger Mutations on Transient Retries 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 DriftBlind Server Action Invocations and Regenerated Request Keys Causing Duplicate Ledger Mutations on Transient RetriesCritical
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 generate an immutable `idempotencyKey` on the client at the initiation of the user intent, binding it deterministically to the optimistic transaction lifecycle rather than deriving it inside the server action.

Engineers MUST ALWAYS generate an immutable `idempotencyKey` on the client at the initiation of the user intent, binding it deterministically to the optimistic transaction lifecycle rather than deriving it inside the server action.

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 generate a new `idempotencyKey` on transient network retries or component re-renders for the same user interaction.

Engineers MUST NOT generate a new `idempotencyKey` on transient network retries or component re-renders for the same user interaction.

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

Components MUST pass the `idempotencyKey` explicitly as an input payload argument or signed hidden field within FormData to the React 19 Server Action.

Components MUST pass the `idempotencyKey` explicitly as an input payload argument or signed hidden field within FormData to the React 19 Server Action.

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

Server Actions MUST atomically verify, reserve, or claim the `idempotencyKey` in a shared transactional store (such as Redis with SET NX EX or Postgres advisory lock) prior to executing any mutation side effects.

Server Actions MUST atomically verify, reserve, or claim the `idempotencyKey` in a shared transactional store (such as Redis with SET NX EX or Postgres advisory lock) prior to executing any mutation side effects.

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

Server Actions MUST return the cached mutation result directly if the provided `idempotencyKey` has already been processed or is currently executing with an in-flight lease.

Server Actions MUST return the cached mutation result directly if the provided `idempotencyKey` has already been processed or is currently executing with an in-flight lease.

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.
6

Client UI components using `useOptimistic` MUST correlate optimistic rollbacks and reconciliations against the specific `idempotencyKey` instance to avoid desynchronizing stale states.

Client UI components using `useOptimistic` MUST correlate optimistic rollbacks and reconciliations against the specific `idempotencyKey` instance to avoid desynchronizing stale states.

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 React 19 Server Action Idempotency-Key Protocol & Optimistic Mutation Deduplication critical for AI coding assistants?

Enforces strictly deduplicated, at-most-once mutation guarantees across transient client network retries during React 19 optimistic UI transitions. Requires client-side generation of cryptographically secure idempotency keys bounded to user action lifecycles and server-side atomic reservation before state execution. 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 (Blind Server Action Invocations and Regenerated Request Keys Causing Duplicate Ledger Mutations on Transient Retries) 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.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

React