Designing Reliable Payment APIs: Idempotency, Transaction Consistency and Duplicate Prevention

A payment request can succeed even when the client never receives its response. A mobile network may disconnect, a gateway may time out, or a service may restart just after committing a transaction. Retrying the request is natural, but treating every retry as a new payment can create duplicate financial obligations.
Reliable payment APIs need more than a successful HTTP response. They must preserve financial invariants across concurrency, failures and communication between independent systems. This article explains how idempotency, database transactions and reconciliation work together, using a fictional payment service and PostgreSQL-compatible examples.
1. Define the operation before designing the endpoint
Imagine a merchant application requesting a payment of USD 25.00. The application sends a request, waits for a response and experiences a timeout. At that moment, it cannot tell whether the service rejected the request, accepted it or completed it.
The same uncertainty appears when a server calls an external payment provider. A timeout is evidence of a communication failure, not proof that the payment failed.
A robust API distinguishes three concepts:
| Identifier | Purpose |
|---|---|
| Idempotency key | Identifies retries of the same API operation within a defined scope |
| Payment identifier | Identifies the durable internal payment record |
| Provider reference | Identifies an operation at an external payment service |
These identifiers may be related, but they are not interchangeable. A payment can have multiple operational attempts while retaining one business identity.
The API contract must explain how long a key remains valid, which requests are considered equivalent, and how a caller can discover the outcome of a previous operation.
2. Make retries safe with idempotency
An idempotent payment creation interface ensures that repeating the same authorized operation does not create additional payments within its documented scope and retention window.
A fictional request might look like this:
POST /v1/payments HTTP/1.1 Host: payments.example.invalid Content-Type: application/json Idempotency-Key: 7bc69f43-3cb8-4ccd-a01d-d678e182155b { "order_reference": "ORDER-1042", "amount_minor": 2500, "currency": "USD" }
The client generates and persists the key before its first attempt. It reuses that key when retrying after an ambiguous failure. Generating a fresh key for every retry defeats the purpose.
The server associates the key with the authenticated merchant, the operation and a fingerprint of the normalized request. If a retry supplies the same key but a different amount or recipient, the server rejects the mismatch instead of silently executing another transaction.
The response semantics depend on the API contract. An accepted operation can return a payment identifier and an initial status, while a later query exposes its current state. An API may alternatively replay a previously stored response. Neither model should imply that an accepted payment has already settled.
Stripe documents one concrete implementation of idempotent requests. Its retention and error-caching behavior are specific to Stripe; do not assume every provider follows the same rules.
3. Enforce uniqueness in the database
A common implementation mistake is to query for an existing key and insert a new record when no result is found. Two concurrent requests can both observe an empty result before either inserts its record.
A database uniqueness constraint provides a stronger invariant. The following simplified PostgreSQL schema models payment intents and their request identity:
CREATE TABLE payment_intents (
payment_id uuid PRIMARY KEY,
merchant_id uuid NOT NULL,
operation text NOT NULL,
idempotency_key text NOT NULL,
request_hash text NOT NULL,
amount_minor bigint NOT NULL CHECK (amount_minor > 0),
currency char(3) NOT NULL,
status text NOT NULL CHECK (
status IN ('PENDING', 'SUCCEEDED', 'FAILED', 'UNKNOWN')
),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (merchant_id, operation, idempotency_key)
);
This is an illustrative schema, not a complete financial ledger. Production systems also need domain-specific authorization, currency validation, transaction history, limits and retention controls.
Use integer minor units or an appropriately constrained exact decimal representation for money. Never depend on binary floating-point arithmetic for authoritative monetary balances. Currency precision must follow the supported currency and payment rail rather than assuming every currency has two decimal places.
The server can attempt to claim a key using PostgreSQL conflict handling. In the following statement, numbered placeholders represent bound parameters supplied by the application:
INSERT INTO payment_intents (
payment_id, merchant_id, operation,
idempotency_key, request_hash,
amount_minor, currency, status
)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'PENDING')
ON CONFLICT (merchant_id, operation, idempotency_key)
DO NOTHING
RETURNING payment_id;
When no row is returned, the application must retrieve the existing record and verify the request fingerprint. Under PostgreSQL's Read Committed isolation, use a subsequent statement to obtain a fresh snapshot. If the record still cannot be found, handle that condition explicitly rather than creating another payment without checking.
See the PostgreSQL documentation on INSERT and transaction isolation for concurrency semantics. Higher isolation levels may require retrying an entire transaction after serialization failures.
4. Keep local changes atomic
Creating a payment intent is not equivalent to debiting an account. If the service maintains an authoritative local ledger, related ledger entries and the corresponding payment-state transition must be committed together under the applicable accounting rules.
A transaction can ensure that either all required local changes become durable or none do. It cannot automatically make a remote HTTP request atomic with those changes.
For a local transfer, validate both accounts, enforce available-balance rules under appropriate concurrency control, create balanced entries and record the business identifier within one transaction. The transaction design should prevent concurrent spending from violating the permitted balance or credit limit.
Use deterministic lock ordering when locking multiple accounts, and handle deadlocks with bounded retries. A retry must preserve the original business and idempotency identifiers. Do not expose database exceptions directly to external clients.
5. Coordinate external payments with an outbox
Suppose the service must notify an external processor after persisting a payment intent. If it commits the payment and then crashes before sending the notification, the operation may remain pending indefinitely. Sending the notification before committing has the opposite risk: the receiver can observe an operation that the local database later rolls back.
A transactional outbox addresses the local dual-write problem by storing an event alongside the business change in the same transaction.
API request | Database transaction |-- Payment intent |-- Outbox event | Commit | Outbox dispatcher | External payment provider
A separate dispatcher reads committed events and attempts delivery. Each event should carry a stable identifier. The receiver should be idempotent, and the dispatcher should use the same provider-side operation key for retries where supported.
A crash between sending an event and recording its delivery may lead to redelivery. The outbox does not promise exactly-once execution across arbitrary external systems. It makes the local intent and notification record atomic and supports recoverable delivery.
The AWS transactional outbox pattern discusses these consistency and duplicate-message considerations.
6. Model uncertainty explicitly
Payment state is a business concept, not merely an HTTP status code. Consider a simplified state machine:
| State | Meaning |
|---|---|
| PENDING | Accepted locally; outcome not established |
| UNKNOWN | An external attempt has an ambiguous outcome |
| SUCCEEDED | Success established using the applicable authoritative evidence |
| FAILED | Definitive failure established under the payment contract |
Actual payment rails may require additional states such as authorization, capture, settlement, expiry, return and reversal. Define those states according to the specific service.
An UNKNOWN payment must not automatically be retried under a new provider reference. Query the original operation, process authenticated status notifications and reconcile against provider records. Where no reliable status inquiry or duplicate prevention exists, escalate ambiguous outcomes rather than risking repeated execution.
Use conditional state transitions to prevent delayed messages from replacing a newer confirmed state. For example, a late pending notification should not downgrade a completed payment.
7. Secure the API and its retry mechanism
Idempotency is not authentication. An attacker who learns a valid key must not be able to retrieve another merchant's payment or replay an unauthorized operation.
Authenticate every request and scope key lookup to the correct merchant and operation. Derive merchant identity from verified credentials rather than trusting a caller-supplied identity field. Recheck authorization before returning any stored response, and avoid logging secrets, full payment credentials or unnecessary personal data.
Request fingerprints should use an unambiguous canonical representation of the business fields. Document how optional fields, currency codes and normalized values are treated. Apply key-length limits, request-size limits and rate limiting to prevent resource exhaustion.
Retain keys for a period that reflects realistic retry behavior, and preserve durable business identifiers for reconciliation. Expiring an API key must not remove the financial record or permit a previously settled order to be charged again without an explicit business decision.
8. Reconcile and test the complete workflow
Even well-designed APIs need reconciliation. Compare internal payment records with external processor reports using stable references, exact monetary amounts, currency and the relevant settlement period. Investigate missing, duplicate, late or mismatched entries rather than automatically changing balances to force agreement.
Test using fictional accounts and synthetic transactions:
- Submit the same key concurrently and verify that only one intent exists.
- Repeat a key with a different amount and verify that it is rejected.
- Simulate a timeout after local commit and recover the original payment identifier.
- Interrupt the dispatcher after external delivery and verify that redelivery is handled safely.
- Deliver duplicate and out-of-order notifications and check state transitions.
- Test authorization boundaries between merchants and verify audit records.
Monitor the age of pending and unknown payments, repeated-key conflicts, outbox backlog, provider error rates and reconciliation exceptions. Establish clear escalation thresholds and ownership for unresolved cases.
Conclusion
Reliable payment processing depends on durable business identity, explicit state transitions and predictable retry behavior. Use database constraints to enforce local uniqueness, transactions to protect local financial invariants and an outbox to coordinate recoverable external delivery.
Most importantly, distinguish a communication timeout from a definitive payment outcome. Idempotency and reconciliation complement each other: one reduces duplicate execution, while the other detects and resolves uncertainty that remains across system boundaries.


