GuideAdvanced2 min read

Idempotency Keys for Payment-Style APIs

Build retry-safe POST endpoints with stable operation identity, atomic writes, replay rules and recovery after ambiguous timeouts.

Author
Pradeep Gajendra
Published
Updated

Scope of this article

Environment
SQL and state transitions illustrate a design; adapt to the provider's documented idempotency contract.

A timeout is not a cancellation. The client can abandon an HTTP request while the server still commits a payment intent, creates an order or sends a webhook. Retrying without a stable operation identity may execute the side effect twice. An idempotency key turns retries of the same logical operation into the same observable result.

The contract to specify first#

  • Scope keys to the authenticated account and endpoint or operation type; a raw globally reusable string is insufficient.

  • Bind the key to a fingerprint of the canonical request parameters. Reusing a key with different parameters must fail, not silently execute different work.

  • Persist the terminal result (status and safe response body) so subsequent identical requests replay it.

  • While the first attempt is in progress, return a documented conflict/in-progress response; never run the business operation concurrently.

  • State a retention period and what happens after expiry. Expiry means a subsequent retry can become a new operation.

Stripe's public API documentation is an example of an idempotency contract, not a rule every application must copy [1]. Define your own semantics for validation failures, concurrency and transient 5xx responses.

Minimal persistence model#

idempotency.sqlsql
create table api_idempotency (
  tenant_id uuid not null,
  route text not null,
  key text not null,
  request_hash text not null,
  state text not null check (state in ('PROCESSING', 'COMPLETED')),
  response_status int,
  response_json jsonb,
  expires_at timestamptz not null,
  primary key (tenant_id, route, key)
);
create index api_idempotency_expiry on api_idempotency (expires_at);

A transaction-safe request flow#

The first request atomically owns an operation; later attempts either replay or are rejected.

Diagram

For a database-only side effect, insert the idempotency record, create the order and persist the completed response in a single database transaction. Contending requests can use a unique constraint plus an explicit conflict protocol. For a remote payment processor, this transaction alone is insufficient: pass the same stable key downstream, persist its external reference and reconcile ambiguous network failures.

Replay, reject or retry?#

Example API decisions — choose and document your own exact status codes

Case

Result

Reason

Same key, same body, completed

Replay stored response

One logical operation

Same key, different body

409 / documented validation error

Prevent accidental key collision

Same key, first attempt active

409 plus Retry-After or poll URL

Avoid concurrent effects

Key absent

Reject for critical POSTs or define non-idempotent behavior

Make risk explicit

Expired key

Treat as new attempt only under published retention policy

Retention is finite

Tests that catch the real bugs#

  • Fire 20 concurrent requests with one key and assert exactly one domain row and one outbound intent.

  • Crash after the domain write but before the HTTP response; retry and verify replay.

  • Reuse a key with a different total or customer and assert rejection.

  • Simulate provider timeout after remote success and reconcile by reference.

  • Exercise TTL cleanup, duplicate webhooks, and tenant-crossing keys.

The most important invariant is not a 200 response: it is exactly one committed business operation per defined idempotency scope. At-least-once delivery still exists; the boundary must be designed to tolerate it.

Sources

  1. [1]
    Stripe — Idempotent Requests

    Stripe · publication date unknown · Stripe API · retrieved 2026-11-02

Spotted an error? Use “Suggest a correction” in the discussion, or read our corrections policy.

Discussion

Sign in to join the discussion. Reading is always open.

Loading discussion…

Report comment