Home » How to Prevent Duplicate AI Agent Actions with Idempotency Keys and React Native Status Controls
React • Top companies

How to Prevent Duplicate AI Agent Actions with Idempotency Keys and React Native Status Controls

Use a stable action ID, server-side deduplication, and a status-aware approval button to make AI agent retries safe.

An AI agent drafts a Jira ticket. A project lead taps Approve and run in a React Native app. The backend creates the ticket, but the phone switches networks before the response arrives. The app shows a timeout. The lead taps again, and now there are two tickets.

The second tap is only one way this can happen. A worker can retry after a crash, a queue can redeliver a message, or two reviewers can approve the same draft on different devices. Disabling a button handles repeated taps on one screen. A stable action ID and a server-side claim handle repeated execution attempts across the system.

What should an idempotency key identify?

An idempotency key identifies one intended action across multiple attempts. For an AI agent, a good default is to issue a server-generated actionId when the agent creates a draft. The draft binds that ID to an immutable payload, such as the destination project, ticket title, and ticket description. The React Native app, approval endpoint, and execution worker all refer to that same action.

ScenarioExpected behavior
A request times out after approvalCheck status and reuse the original action ID if a retry is needed.
Two reviewers approve the same draftBoth requests resolve to the same execution record.
A reviewer edits the draft or changes its destinationCreate a new revision with a new action ID and invalidate the superseded draft.
Two agent runs independently propose the same business actionApply a business-level rule, such as one incident ticket per incident ID.

The last row matters. Two requests with different keys represent separate intents to the idempotency layer. If the product also requires one ticket per incident, enforce that invariant separately. Conversely, hashing the payload to generate the key can merge two legitimate actions that happen to have identical content. AWS documents the same distinction between a caller-provided request ID and an inferred duplicate.

How should the backend claim and execute an action?

Treat approval as a state transition. After authorizing the reviewer, the API atomically moves the action from ready to pending and creates an outbox record in the same database transaction. A retry reads the existing state and result. With PostgreSQL, a conditional UPDATE on the action row or an INSERT ... ON CONFLICT backed by a unique constraint can enforce the claim. An application-level lookup followed by a separate write leaves a race between requests.

The worker still needs its own retry policy. A transactional outbox keeps the database update and the intent to enqueue work together, but the relay can deliver a message more than once. Pass a stable key derived from the action ID to the downstream API where it supports idempotency. Store the downstream resource ID alongside the result so the application can show or reconcile what happened.

The hardest case is a worker crash after the downstream API succeeds and before the worker records the result. If that API supports idempotency, retry with the same downstream key within its retention window. If it offers a reliable lookup by a client-supplied reference, reconcile the existing resource first. When neither option is available, keep the outcome unresolved for review. Automatically replaying the write can create the duplicate the rest of the design was meant to prevent.

How can React Native show the real action status?

The UI should distinguish a request in progress, an action pending on the server, and an outcome the device could not confirm. When connectivity drops, show Check status. Once the server confirms the action is still ready, the same draft can be submitted again with the original ID.

This illustrative component assumes POST /agent-actions/:id/approve returns the current action status and GET /agent-actions/:idreads it. The request prop is the app’s authenticated API client. The parent should fetch initialStatus when opening or restoring the screen and mount the component with key={actionId} so a new draft gets fresh UI state.

import { useRef, useState } from 'react';
import { Pressable, Text } from 'react-native';

type ActionStatus = 'ready' | 'pending' | 'succeeded' | 'failed';
type ScreenStatus = ActionStatus | 'unknown';

type Props = {
  actionId: string;
  initialStatus: ActionStatus;
  request: (path: string, options?: RequestInit) => Promise<Response>;
};

const label: Record<ScreenStatus, string> = {
  ready: 'Approve and run',
  pending: 'Check status · Action in progress',
  unknown: 'Check status · Outcome unconfirmed',
  succeeded: 'Completed',
  failed: 'Action failed · Review details',
};

export function AgentActionButton({
  actionId,
  initialStatus,
  request,
}: Props) {
  const [status, setStatus] = useState<ScreenStatus>(initialStatus);
  const [busy, setBusy] = useState(false);
  const inFlight = useRef(false);
  const terminal = status === 'succeeded' || status === 'failed';

  async function handlePress() {
    if (inFlight.current || terminal) return;

    inFlight.current = true;
    setBusy(true);

    try {
      const path = `/agent-actions/${encodeURIComponent(actionId)}`;
      const response = status === 'ready'
        ? await request(`${path}/approve`, {
            method: 'POST',
            headers: { 'Idempotency-Key': actionId },
          })
        : await request(path);

      if (!response.ok) throw new Error('Action status unavailable');

      const { status: next } = await response.json();
      if (
        next !== 'ready' && next !== 'pending' &&
        next !== 'succeeded' && next !== 'failed'
      ) {
        throw new Error('Unexpected action status');
      }
      setStatus(next);
    } catch {
      setStatus('unknown');
    } finally {
      inFlight.current = false;
      setBusy(false);
    }
  }

  return (
    <Pressable
      onPress={handlePress}
      disabled={busy || terminal}
      accessibilityRole="button"
      accessibilityState={{ busy, disabled: busy || terminal }}
    >
      <Text>{busy ? 'Contacting server…' : label[status]}</Text>
    </Pressable>
  );
}

The ref blocks another invocation of the handler immediately. React state drives the next render, and Pressable exposes the disabled and busy states to assistive technology. After an app restart, the screen can recover by loading the action ID and status from the server. The backend should reserve failed for confirmed terminal failures and keep ambiguous outcomes available for reconciliation. React

How five companies apply these controls

CompanyPublicly documented practice
GeekyAntsIts AI Signal Bot lets a lead review proposed project updates before they reach tools such as Jira or Asana and preserves the source message and approval history. Its payment engineering guidance describes idempotency to prevent duplicate transactions. The public Signal Bot write-up documents the approval workflow. It does not specify the bot’s internal deduplication implementation.
StripeAPI v1 saves the first response after endpoint execution begins, including 500 responses, and checks that parameters match on reuse. Keys can be pruned after they are at least 24 hours old. API v2 has different retry semantics.
AWSAmazon EC2 uses a caller-provided ClientToken for supported idempotent operations. AWS describes storing the original parameters and returning a validation error when the same token is reused with a different intent.
PayPalSupported REST endpoints use PayPal-Request-Id. A retry can return the latest status of the earlier request, while two simultaneous submissions using the same ID can cause the second request to fail. Support and retention depend on the endpoint.
SquareCreatePayment accepts an idempotency key so the same payment request can be recognized when a client submits it again after losing the response.

Which failure cases should teams test before release?

  • Drop the response after the write succeeds. Reopen the app and verify that checking status returns the original result and resource ID.
  • Approve from two devices at once. Confirm both clients see the same execution and the downstream system receives one effective write.
  • Crash the worker after downstream success. Confirm the retry recovers the existing result or moves the action to reconciliation.
  • Reuse a key with changed parameters. Verify that the API rejects the mismatch and keeps the original action intact.
  • Retry after the downstream key expires. Confirm the worker checks for an existing result before attempting another write.

The most revealing test is the first one. If the phone never receives the success response, the user should still be able to find out what happened to the original action. That is what makes the retry safe from the user’s point of view.