Payment processing — idempotency and error handling
The hardest payment failure is often the one where nothing appears to happen. The gateway accepts a charge, the response is lost, and the application times out. The customer sees an error. The money may already have moved.
Retrying can create another charge. Giving up can leave a successful payment recorded as failed. A local database transaction cannot make the gateway participate in its commit, so the design needs to represent uncertainty explicitly.
These are the boundaries I would build around a payment workflow. The SQL and Java below are illustrative design fragments, not excerpts from a complete payment service. Repository methods, provider adapters, authorization, and validation need implementation for the specific integration.
A timeout is not a declined payment
Separate the business result from what the transport tells you:
| Observation | What the application knows | Next action |
|---|---|---|
| Provider confirms success | The requested operation succeeded | Persist the provider reference and result |
| Provider confirms a decline | This attempt was declined | Return the classified outcome |
| Request times out after sending | The outcome is unknown | Resolve the existing attempt |
| Local validation fails before sending | No provider operation was attempted | Correct the request |
| Provider reports rate limiting | The request needs provider-specific handling | Respect retry guidance and the attempt's identity |
Authorization, capture, refunds, and disputes are separate operations. A single paid boolean cannot describe all of them. For the examples here, assume one operation that asks the provider to charge an amount; its attempt has a deliberately small state model:
PENDING → SUCCEEDED
→ DECLINED
→ UNKNOWN → SUCCEEDED / DECLINED
PENDING can also survive a worker crash, so an overdue pending attempt needs reconciliation. UNKNOWN is an operational state to investigate, not permission to create a replacement charge.
Why check-then-charge is unsafe
This is an attractive first implementation:
if (paymentRepository.findByIdempotencyKey(key).isEmpty()) {
Payment payment = gateway.charge(request);
paymentRepository.save(payment.withIdempotencyKey(key));
}
Two requests can both observe an absent key and both reach the gateway. Adding a unique constraint to the final insert only stops the second database row. It cannot undo the second external charge.
There is also a crash window: the gateway succeeds, then the application dies before saving anything. The next request sees the same empty database.
The local attempt must exist before the external side effect, and the provider request needs its own stable identity.
Claim the attempt atomically
One possible PostgreSQL schema is:
CREATE TABLE payment_attempt (
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 DEFAULT 'PENDING'
CHECK (status IN ('PENDING', 'SUCCEEDED', 'DECLINED', 'UNKNOWN')),
provider_idempotency_key TEXT NOT NULL UNIQUE,
provider_reference TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (merchant_id, operation, idempotency_key)
);
The key is scoped to the authenticated merchant and operation. A client's chosen string must not let one merchant retrieve another merchant's payment. Authentication and ownership checks happen before looking up an attempt.
Amounts use integer minor units, with currency-specific precision validated separately. The request fingerprint covers a canonical, versioned representation of the amount, currency, order, and payment-method reference. It should not be a hash of arbitrary JSON serialization or raw card data.
Claiming the request becomes an insert with an explicit conflict target:
INSERT INTO payment_attempt (
id, merchant_id, operation, idempotency_key, request_hash,
amount_minor, currency, provider_idempotency_key
)
VALUES (
:id, :merchantId, :operation, :key, :requestHash,
:amountMinor, :currency, :providerKey
)
ON CONFLICT (merchant_id, operation, idempotency_key) DO NOTHING
RETURNING id;
The unique constraint arbitrates concurrent requests. Only the caller receiving the inserted ID owns the initial submission. Commit this short transaction before contacting the provider.
When the insert returns no ID, read the existing attempt in a subsequent statement under PostgreSQL's usual READ COMMITTED isolation:
- Different request hash: reject reuse of the key, for example with
409 Conflict. - Completed attempt: return the stored result for that operation.
- Pending or unknown attempt: return its existing ID/status, for example with
202 Acceptedand a status URL. Do not start another charge.
The table is a starting point. A real API may need stored response fields, explicit result codes, attempt history, and an order-level invariant. Different idempotency keys for the same order can still create different attempts; business rules must decide when a new attempt is allowed.
Keep the provider key stable across retries
A database claim protects the application's entry point. It does not bridge the crash between the provider accepting a request and the application recording its result.
Generate and store a provider idempotency key with the local attempt. Reuse it with the same parameters when the provider's contract permits retrying that operation. Do not generate a new provider key on every HTTP retry.
A conceptual orchestration method looks like this:
// Intentionally not one @Transactional method around the network call.
public AttemptView submit(AuthorizedMerchant merchant, PaymentCommand command) {
Claim claim = attempts.claimAndCommit(merchant.id(), command);
if (!claim.created()) {
claim.requireSameRequest(command.fingerprint());
return claim.attempt().toView();
}
PaymentAttempt attempt = claim.attempt();
try {
ProviderResult result = provider.charge(
attempt.amountMinor(),
attempt.currency(),
command.paymentMethodReference(),
attempt.providerIdempotencyKey()
);
// Separate short transaction; conditional, idempotent state update.
return attempts.recordProviderResult(attempt.id(), result);
} catch (ProviderOutcomeUnknownException ex) {
// The adapter classifies ambiguity; not every exception is a decline.
return attempts.markUnknownUnlessResolved(attempt.id());
}
}
The claim must return the original attempt on a duplicate; the update methods must prevent stale results from overwriting an already resolved state. A webhook can arrive before this method records its result, so these paths need a shared transition policy.
A crash immediately after the claim still leaves work unfinished. A periodic worker can inspect overdue PENDING and UNKNOWN attempts, query the provider where possible, and retry only within the provider's supported idempotency contract. For a queued design, insert an outbox job in the same transaction as the claim so a crash cannot lose the scheduling step.
Provider behavior is not universal. For example, Stripe's API v1 replays the first saved response, including server errors, and keys have a retention window. Reusing a key is not an instruction to forget the original attempt and execute again. Check the operation and API version's idempotency contract.
Retry policy belongs to the operation
A blanket @Retryable around every gateway exception hides distinctions that matter:
- A validation error needs corrected input.
- A decline needs its business classification, not a tight retry loop.
- Rate limiting needs bounded scheduling and provider retry guidance.
- A connection loss after submission needs the existing operation resolved.
- A server error can have an indeterminate outcome; it is not proof that no side effect happened.
Use bounded exponential backoff with jitter for eligible retries. One possible scheduling rule is:
ceiling = min(maxDelay, baseDelay × 2^attempt)
delay = random(0, ceiling)
Set a total retry budget as well as individual connect/response deadlines. Persist the next-attempt time and attempt count when retries must survive restarts. Once a request exceeds the provider's safe retry window, escalate to reconciliation rather than silently issuing a fresh key. Provider-specific error semantics matter; Stripe documents these distinctions in its low-level error guidance.
A webhook needs durable acceptance
A webhook can resolve a payment after the original request timed out. Its delivery is another distributed operation: the provider can retry after losing your response, and events can arrive out of order.
The endpoint should verify the provider signature against the unmodified request body, using its supported SDK and timestamp/replay checks. Then persist the verified event before acknowledging it. Stripe's webhook documentation covers signature verification, duplicate delivery, and event ordering.
A durable inbox makes the acceptance boundary explicit:
CREATE TABLE payment_webhook_inbox (
provider TEXT NOT NULL,
provider_account TEXT NOT NULL,
event_id TEXT NOT NULL,
payload JSONB NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
processed_at TIMESTAMPTZ,
PRIMARY KEY (provider, provider_account, event_id)
);
Here payload is the verified parsed payload; signature verification happens against the original bytes before insertion. Restrict access and define retention because event payloads can contain personal data.
Conceptual controller code:
@PostMapping("/webhooks/payment")
public ResponseEntity<Void> receive(
@RequestBody byte[] rawBody,
@RequestHeader("Provider-Signature") String signature) {
VerifiedEvent event = verifier.verify(rawBody, signature);
inbox.insertIfAbsentAndCommit(event); // duplicate is a successful no-op
return ResponseEntity.ok().build();
}
The header and verifier above are placeholders for a provider adapter. Invalid signatures must be mapped to a rejection. If durable storage fails, return a failure so the provider can retry; do not acknowledge an event held only in process memory.
A background worker reads unprocessed inbox rows. Multiple workers need row locking or leases to coordinate, and the local payment update plus marking the inbox row processed belong in the same database transaction.
Event-ID deduplication handles redelivery of the same event. It does not prevent two distinct events from triggering the same business action. Fulfillment needs its own invariant, such as one fulfillment record per order. If fulfillment crosses a service boundary, publish through an outbox and make the consumer idempotent as well.
Reconciliation closes the gaps
A webhook handler should not blindly set the payment status to whatever the latest arriving message says. Arrival order is not business order.
Match the provider account and payment reference to the expected attempt. Check the amount and currency where the event supplies them. Apply only valid transitions; query the provider's current object when an event is insufficient or conflicts with local state.
Keep an audit trail of transitions rather than silently overwriting history. A useful reconciliation queue includes:
- Attempts that stayed pending beyond their expected processing time.
- Unknown outcomes with no resolving event.
- Inbox events that repeatedly fail processing.
- Amount/currency mismatches or unexpected provider references.
- Conflicts between a provider lookup and local state.
Refunds and disputes should have their own records and lifecycle. A successful charge followed by a refund is not the same history as a declined charge.
Failure cases worth exercising
The meaningful tests are around the gaps between operations:
- Submit two concurrent requests with the same key and payload: one initial provider submission, one local attempt.
- Reuse that key with a different amount: reject it before contacting the provider.
- Simulate provider success followed by a dropped response: retain the same attempt and provider key until resolved.
- Kill the process after the local claim: overdue work remains discoverable.
- Deliver a webhook twice: one local transition and one fulfillment action.
- Deliver the webhook before the synchronous provider response: neither path reverses the resolved result.
- Fail inbox storage: the endpoint does not return success.
- Deliver events out of order: business state does not regress because of arrival order.
For observability, record attempt IDs, provider request IDs, state transitions, retry counts, and the age of unresolved attempts. Avoid logging raw credentials, card data, webhook bodies, or complete request payloads by default.
The goal is a workflow that can explain what it knows after a failure. A stable operation identity prevents retries from becoming new work; durable state makes crashes recoverable; reconciliation resolves the outcomes the original HTTP request could not establish.