The Anatomy of an Idempotency Key: Stripe Payment Retry Safety

Payments

Design payment idempotency keys in PostgreSQL and Stripe to prevent duplicate charges. Learn request matching, locking, webhook handling, and timeout recovery.

TL;DR

  • Generate one idempotency key for one logical attempt. Retry a timed-out request with the same key and parameters.
  • In PostgreSQL, use a unique constraint to reserve the key and commit the local business record, outbox message, and response together.
  • Use a stable provider-side key for each external mutation. Reconcile unknown outcomes before issuing a new charge or refund.
  • Define how long you replay API responses and how long you retain the business identifier that prevents repeated financial effects.

Start with the response that never arrives

An API creates a payment attempt and returns an HTTP response, but the connection drops before the browser receives it. The browser sees the same network error it would see if the request had never reached the API. One button click now has two possible histories. An automatic retry without a stable operation identifier risks a second payment. Suppressing retries leaves some customers with no payment and others with a successful payment they cannot see.

An idempotency key lets the client identify its original intent across these retries. Treat the key as a client-generated operation handle. Backoff, a disabled submit button, and transport retries are useful, but none of them gives two servers a common way to tell whether requests refer to the same intent. Keep the key through app relaunches or retry jobs as long as the attempt remains unresolved.

Define the unit of intent explicitly. A checkout session may be made of create, confirm, capture, and refund operations. Each mutating action gets its own identifier or a purpose-specific provider key derived from the durable operation ID. Equal payloads can describe distinct intended purchases. Conversely, a changed body sent with a previous key can mean the client is about to retry the wrong operation. These are separate cases.

What Stripe actually promises for a retry

Stripe API v1 records the first status and body for a key once endpoint execution begins, including a 500. A later request using the same key can receive that stored result. Stripe compares supplied parameters to prevent accidental reuse for a different request. Validation failures and conflicts that stop execution before the endpoint begins are handled differently: no endpoint result is saved in those cases. Stripe documents that v1 keys can be removed once they are at least 24 hours old and that a reused key after pruning can execute anew. Stripe idempotent requests

Stripe API v2 describes a different retry model. It avoids repeating successfully completed work and attempts to finish work that failed or partially completed when it can. Leverage the behavior of the API you are integrating with: the v1 replay contract is a useful design reference, but it is neither a universal HTTP guarantee nor a description of every Stripe endpoint. Stripe API v2 idempotency

For a v1 500 or an ambiguous network failure, keep retrying only within your documented recovery policy. A cached 500 can remain the response you see. Use a durable operation record, confirmed provider state, and appropriately verified events to determine the outcome before creating a replacement. A key makes an operation safer to repeat within its contract. It cannot guarantee delivery, successful execution, or perpetual replay. Stripe low-level error handling

Implement an idempotent payment attempt in PostgreSQL

Store the response separately from the business uniqueness rule

This example accepts an asynchronous payment request. Authentication and validation happen before the transaction, including permission to act on the order. Server code derives tenant_id, a stable order_id, and a fingerprint of the validated request. The fingerprint includes all fields that change the operation or its stored response, such as the pinned API contract. Use normalized values, for example integer minor units and a canonical currency code. Exclude volatile request fields like trace IDs. Avoid retaining payment instrument data or secrets in fingerprints, responses, or application logs.

Choose the key scope that matches your authorization model. This sample scopes the key to the tenant and one endpoint. It assumes authorized members of that tenant may view the same payment attempt and that product rules allow a single payment attempt record per order. A product supporting repeated legitimate payments or split tender needs a different durable uniqueness rule, such as one record per checkout attempt or installment. Check object-level access on replays as well as on new requests.

CREATE TABLE payment_attempt (
    id uuid PRIMARY KEY,
    tenant_id uuid NOT NULL,
    order_id uuid NOT NULL,
    state text NOT NULL DEFAULT 'pending',
    UNIQUE (tenant_id, order_id)
);

CREATE TABLE payment_idempotency (
    tenant_id uuid NOT NULL,
    key text NOT NULL,
    request_hash bytea NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now(),
    response_status smallint,
    response_body jsonb,
    PRIMARY KEY (tenant_id, key),
    CHECK ((response_status IS NULL) = (response_body IS NULL))
);

CREATE TABLE payment_outbox (
    payment_id uuid PRIMARY KEY REFERENCES payment_attempt(id),
    topic text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

The outbox primary key models one provider-create command for each local payment. A production outbox needs retry and availability fields, delivery ownership, and an attempt history suited to the worker architecture. Keep each later provider mutation separate. Requiring the same local response key for every action would make legitimate captures or refunds ambiguous.

Commit acceptance and the response before returning HTTP 202

The example below uses an idle Psycopg 3 connection in autocommit mode and opens an explicit transaction per call. Read Committed isolation is assumed. After a conflicting insert finishes, the next SQL statement sees the committed response if the first writer succeeded. An exception aborts the entire transaction. The function stores a logical JSON response; store encoded body bytes and allowlisted headers as well if you promise exact HTTP replay. PostgreSQL INSERT and ON CONFLICT · PostgreSQL Read Committed visibility · Psycopg transaction management

# Send the HTTP response only after this function returns.
from uuid import uuid4
from psycopg.errors import LockNotAvailable
from psycopg.types.json import Jsonb

def accept_payment(conn, tenant_id, order_id, key, request_hash):
    try:
        with conn.transaction(), conn.cursor() as db:
            db.execute("SET LOCAL lock_timeout = '250ms'")
            db.execute("""
                INSERT INTO payment_idempotency (tenant_id, key, request_hash)
                VALUES (%s, %s, %s)
                ON CONFLICT (tenant_id, key) DO NOTHING
                RETURNING 1
            """, (tenant_id, key, request_hash))
            if db.fetchone() is None:
                db.execute("""
                    SELECT request_hash, response_status, response_body
                    FROM payment_idempotency WHERE tenant_id = %s AND key = %s
                """, (tenant_id, key))
                previous = db.fetchone()
                if previous is None or previous[1] is None:
                    return 503, {"code": "payment_retry_required"}
                if previous[0] != request_hash:
                    return 409, {"code": "idempotency_key_mismatch"}
                return previous[1], previous[2]

            payment_id = uuid4()
            db.execute("""
                INSERT INTO payment_attempt (id, tenant_id, order_id)
                VALUES (%s, %s, %s)
                ON CONFLICT (tenant_id, order_id) DO NOTHING
                RETURNING id
            """, (payment_id, tenant_id, order_id))
            if db.fetchone() is None:
                status, body = 409, {"code": "order_already_has_payment_attempt"}
            else:
                db.execute("""
                    INSERT INTO payment_outbox (payment_id, topic)
                    VALUES (%s, 'payment.create')
                """, (payment_id,))
                status, body = 202, {"payment_id": str(payment_id), "state": "pending"}

            db.execute("""
                UPDATE payment_idempotency
                SET response_status = %s, response_body = %s
                WHERE tenant_id = %s AND key = %s
            """, (status, Jsonb(body), tenant_id, key))
            return status, body
    except LockNotAvailable:
        return 503, {"code": "payment_temporarily_busy"}

The lock timeout is an illustrative wait budget. It may also be reached by unrelated lock contention inside the transaction, which is why the response says temporarily busy instead of claiming another copy of the identical request is definitely running. Use retries with bounded delay and jitter. Replayed 202 responses preserve acceptance semantics even if the payment subsequently completes. Clients retrieve current state through a separate status route.

Store the original response or document semantic replay carefully. If you regenerate a response using the current deployment's serializer, a retry may experience a response change that the pinned API version was supposed to prevent. If you store the response, define a retention policy and keep sensitive data out of its representation. See the companion guide to dated API contracts in FastAPI.

Send provider requests through a durable worker

A worker reads the committed outbox record and calls the provider outside the database transaction. Derive the provider key from the local payment ID and action, for example create-payment:<payment-id>. Persist the request parameters early enough that the retried call can keep them stable across deployments. Keeping a database transaction open across the network call would hold locks longer and still leave the provider free to commit after a local rollback.

On provider success, store the provider object ID and apply the local state change. Correlate incoming events with the same business attempt and make their own processing repeatable. If a webhook arrives before the synchronous provider response is saved, either process it against existing correlation data or store it for reconciliation. Provider event delivery is asynchronous, and Stripe's webhook documentation covers retry, ordering, and duplicates. Stripe webhooks

Plan for events with distinct event IDs that report the same financial effect. A unique key around the ledger mutation should reflect business identity rather than only the event delivery identity. A payment completion transition and its postings can be protected by a transaction plus appropriate uniqueness constraints. Database constraints for double-entry ledger entries

Keep records longer than the retry horizon for customers who have to reconcile ambiguous payments manually. Once provider replay protection might have expired, treat a new external mutation as a separate risk decision. Look up the provider resource using durable correlation, recover from verified events, and quarantine uncertain requests for review if genuine ambiguity remains.

Exercise three failure boundaries before release

Two requests arrive before the first commit

Start two requests from separate connections using the same key. Hold the first transaction open, and verify the second either replays the same result after commit or receives a retryable temporary error. Repeat with the first transaction rolled back. Assert exactly one accepted business record and outbox row in the successful case. Repeat with changed parameters and confirm the client sees a key mismatch without replacing the saved reply.

The server loses the response after committing

Drop the application connection after the database commits. Retry with the original key and expect the original payment ID. Then use a distinct key for the same order and verify the durable business constraint prevents another attempt. Testing this second path shows which protections remain after the response cache expires.

The provider succeeds before the worker records its response

Inject a worker crash after a provider stub accepts the request. On retry, inspect the key and parameters. Confirm that the worker processes the original external operation and produces the corresponding local result only once. In the same fixture, simulate an expired provider key and require reconciliation before dispatching a possible duplicate. Leases and retry fencing in shared worker pools

Frequently asked questions

Which idempotency key should a paying client send after a timeout?

Send the same key and the same validated input for the original operation. A timeout alone gives no reliable evidence about whether the first request reached the server or whether a provider carried out the charge. Use a new key for a separate payment attempt only after the first attempt's state is resolved.

Does Stripe API v1 replay an HTTP 500 for the same key?

Yes, Stripe API v1 can replay the original HTTP 500 when endpoint execution began and the response was recorded. Check the documented error and reconciliation guidance for that endpoint and avoid switching keys solely because a failure response repeats. Stripe API v2 has different retry behavior.

How long should a payment API store idempotency keys?

Choose a response replay window based on client retry behavior, asynchronous delays, and data retention needs. Keep a separate durable business identifier for as long as the product must prevent duplicate processing. Provider-side retention is an independent limit, so design explicit recovery for ambiguous requests outside its replay window.

Do webhook deduplication and payment idempotency solve the same problem?

Payment request idempotency guards an operation initiated by a caller. Webhook deduplication guards repeated delivery of provider notifications. A single financial effect can also be represented by multiple events, so local state changes and ledger entries need operation-level uniqueness in addition to delivery tracking.

Further reading

Designing a payment flow that can recover from timeouts and retries? Ask Dumb Potato to review its idempotency and reconciliation boundaries.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with e-commerce

Discuss your project