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

React 19 Server Action Idempotency-Key Deduplication Guardrail

Enforces deterministic client-side generation and server-side atomic validation of idempotency keys across all mutating React 19 Server Actions. Guarantees that concurrent submissions, network retry storms, and transient timeout replay loops cannot cause duplicate side effects or non-reentrant state corruptions. Mandates atomic distributed lock/reservation primitives prior to executing durable business mutations.

Prohibited Anti-Pattern: Blind Execution of Non-Idempotent React 19 Server Actions on Optimistic Retries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React 19 Server Action Idempotency-Key Deduplication Guardrail - Enforces deterministic client-side generation and server-side atomic validation of idempotency keys across all mutating React 19 Server Actions. Guarantees that concurrent submissions, network retry storms, and transient timeout replay loops cannot cause duplicate side effects or non-reentrant state corruptions. Mandates atomic distributed lock/reservation primitives prior to executing durable business mutations.
globs: src/actions/**/*.{ts,tsx}, src/app/**/*.{ts,tsx}, src/features/**/actions/**/*.{ts,tsx}, src/lib/mutations/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-19-server-action-idempotency-deduplication"
---

# React 19 Server Action Idempotency-Key Deduplication Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Blind Execution of Non-Idempotent React 19 Server Actions on Optimistic Retries

## System Constraints
You are a Principal Software Architect enforcing production-grade concurrency invariants on React 19 Server Actions. You must prevent duplicate writes, non-reentrant state corruption, and race conditions during network retries by requiring client-instantiated idempotency keys, atomic distributed reservation checks (e.g., Redis SET NX or DB unique constraints), and deterministic mutation response caching.

## Strict Guidelines
- Engineers MUST ALWAYS generate a cryptographically unique `idempotencyKey` (UUIDv4/NanoID) on the client per logical user intent before triggering a Server Action, passing it through form state or explicit action arguments.
- Engineers MUST NOT create or re-generate idempotency keys inside the Server Action scope, as subsequent network-level retries will receive distinct keys and defeat deduplication.
- Engineers MUST ALWAYS wrap the Server Action mutation logic with an atomic reservation check (e.g., Redis `SET key value NX PX` or an INSERT with `ON CONFLICT DO NOTHING`) prior to executing external side effects (e.g., Stripe, database writes).
- Services MUST return cached responses or handle in-flight locks gracefully when an idempotency key collision is detected, returning a deterministic result rather than re-executing business logic.
- Components MUST retain the stable `idempotencyKey` across optimistic updates and `useActionState` retries, ensuring that automated form re-submissions or transient error replays target the same server mutation identifier.

## Bad vs Good Implementations
### Naive Server Action Execution vs. Atomic Idempotency-Guarded Action

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The action accepts a raw payload without a client-originated idempotency key. A retry storm, duplicate form submission, or network drop between server response and client receipt causes duplicate order records and double charging.
```typescript
'use server';

import { db } from '@/lib/db';
import { orders } from '@/lib/schema';

interface CheckoutPayload {
  itemId: string;
  quantity: number;
  userId: string;
}

// ANTI-PATTERN: No idempotency key validation. A double-click, unstable connection,
// or automated retry will trigger multiple debits and duplicate order rows.
export async function checkoutAction(payload: CheckoutPayload) {
  const user = await db.query.users.findFirst({ where: (u, { eq }) => eq(u.id, payload.userId) });
  if (!user || user.balance < 100) {
    throw new Error('Insufficient funds');
  }

  // Non-atomic read-then-write; network retry executes this multiple times
  const [order] = await db.insert(orders).values({
    userId: payload.userId,
    itemId: payload.itemId,
    quantity: payload.quantity,
    createdAt: new Date(),
  }).returning();

  return { success: true, orderId: order.id };
}
```

#### Production Standard (Correct)
> **Standard**: The client passes a UUIDv4 `idempotencyKey`. The action atomically reserves this key via Redis NX semantics before initiating the transaction. Concurrent replays are blocked, while post-completion retries return the cached result deterministically without side effects.
```typescript
'use server';

import { db } from '@/lib/db';
import { orders } from '@/lib/schema';
import { redis } from '@/lib/redis';
import { z } from 'zod';

const CheckoutSchema = z.object({
  idempotencyKey: z.string().uuid(),
  itemId: z.string().min(1),
  quantity: z.number().int().positive(),
  userId: z.string().min(1),
});

export type CheckoutInput = z.infer<typeof CheckoutSchema>;

export async function checkoutAction(rawInput: CheckoutInput) {
  const input = CheckoutSchema.parse(rawInput);
  const lockKey = `idempotency:checkout:${input.userId}:${input.idempotencyKey}`;

  // Atomic distributed reservation lock with 120s TTL
  const acquired = await redis.set(lockKey, 'IN_FLIGHT', 'EX', 120, 'NX');

  if (!acquired) {
    const cachedResult = await redis.get(lockKey);
    if (cachedResult && cachedResult !== 'IN_FLIGHT') {
      // Deterministic replay of completed mutation
      return JSON.parse(cachedResult) as { success: boolean; orderId: string };
    }
    throw new Error('Mutation already in-flight. Please wait.');
  }

  try {
    const [order] = await db.insert(orders).values({
      userId: input.userId,
      itemId: input.itemId,
      quantity: input.quantity,
      idempotencyKey: input.idempotencyKey,
      createdAt: new Date(),
    }).returning();

    const response = { success: true, orderId: order.id };
    // Cache completed result for deterministic replay across retry window
    await redis.set(lockKey, JSON.stringify(response), 'EX', 86400);
    return response;
  } catch (error) {
    // Release reservation lock on unrecoverable failure to permit client retries
    await redis.del(lockKey);
    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 Deduplication Guardrail

React 19 Server Action Idempotency-Key Deduplication Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic client-side generation and server-side atomic validation of idempotency keys across all mutating React 19 Server Actions. Guarantees that concurrent submissions, network retry storms, and transient timeout replay loops cannot cause duplicate side effects or non-reentrant state corruptions. Mandates atomic distributed lock/reservation primitives prior to executing durable business mutations. 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 Execution of Non-Idempotent React 19 Server Actions on Optimistic 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 Execution of Non-Idempotent React 19 Server Actions on Optimistic 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 a cryptographically unique `idempotencyKey` (UUIDv4/NanoID) on the client per logical user intent before triggering a Server Action, passing it through form state or explicit action arguments.

Engineers MUST ALWAYS generate a cryptographically unique `idempotencyKey` (UUIDv4/NanoID) on the client per logical user intent before triggering a Server Action, passing it through form state or explicit action arguments.

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 create or re-generate idempotency keys inside the Server Action scope, as subsequent network-level retries will receive distinct keys and defeat deduplication.

Engineers MUST NOT create or re-generate idempotency keys inside the Server Action scope, as subsequent network-level retries will receive distinct keys and defeat deduplication.

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 ALWAYS wrap the Server Action mutation logic with an atomic reservation check (e.g., Redis `SET key value NX PX` or an INSERT with `ON CONFLICT DO NOTHING`) prior to executing external side effects (e.g., Stripe, database writes).

Engineers MUST ALWAYS wrap the Server Action mutation logic with an atomic reservation check (e.g., Redis `SET key value NX PX` or an INSERT with `ON CONFLICT DO NOTHING`) prior to executing external side effects (e.g., Stripe, database writes).

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 return cached responses or handle in-flight locks gracefully when an idempotency key collision is detected, returning a deterministic result rather than re-executing business logic.

Services MUST return cached responses or handle in-flight locks gracefully when an idempotency key collision is detected, returning a deterministic result rather than re-executing business logic.

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 MUST retain the stable `idempotencyKey` across optimistic updates and `useActionState` retries, ensuring that automated form re-submissions or transient error replays target the same server mutation identifier.

Components MUST retain the stable `idempotencyKey` across optimistic updates and `useActionState` retries, ensuring that automated form re-submissions or transient error replays target the same server mutation identifier.

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 Deduplication Guardrail critical for AI coding assistants?

Enforces deterministic client-side generation and server-side atomic validation of idempotency keys across all mutating React 19 Server Actions. Guarantees that concurrent submissions, network retry storms, and transient timeout replay loops cannot cause duplicate side effects or non-reentrant state corruptions. Mandates atomic distributed lock/reservation primitives prior to executing durable business mutations. 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 Execution of Non-Idempotent React 19 Server Actions on Optimistic 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