Skip to content
ADevGuide Logo ADevGuide
Go back

How Would You Prevent Duplicate Payments?

Updated:

By Pratik Bhuite | 10 min read

Hub: Java / Interview Fundamentals

Series: Backend Interview Mastery

Last updated: Sep 19, 2026

Part 59 of 88 in the Backend Interview Mastery

Key Takeaways

On this page
Reading Comfort:

Preventing duplicate payments with idempotency and a payment state machine

The customer sees a timeout, taps Pay again, and two charges arrive. In this scenario, explain how you preserve the “one payment intent, one outcome” invariant when clients retry and the provider is uncertain. Pair this with API idempotency, distributed transactions, and the payment system design.

The Interview Question

“A checkout endpoint occasionally charges a card twice. Design a fix that survives timeouts, retries, provider webhooks, and multiple application replicas.”

Clarifying Questions

Ask whether the provider supports idempotency keys, whether a charge can be queried by merchant reference, the authorization-to-capture flow, and the reconciliation SLA. Assume 2,000 payment attempts per second at peak, at-least-once webhooks, and a strict no-double-charge invariant.

The Naive Design and Why It Fails

Charging directly on every POST /pay makes the request non-idempotent. A timeout after provider acceptance leaves the client unable to distinguish “not charged” from “charged but response lost.” An application mutex fails across replicas, and a cache key can expire before a late retry.

Better Design

Require a client-generated idempotency key scoped to the merchant and order. Insert it with a unique constraint before calling the provider, store PENDING, and return the stored result for later retries. Never reuse a key for a different amount or currency; reject that mismatch.

flowchart TD
    A[Client sends idempotency key] --> B[Unique payment intent row]
    B --> C{Existing result?}
    C -->|Yes| D[Return stored outcome]
    C -->|No| E[Call provider with same key]
    E --> F[Persist authorized or failed]
    F --> G[Webhook reconciliation]

Data Model and Race Safety

Store merchant_id, idempotency_key, amount, currency, provider reference, status, response payload, and timestamps. The unique index on (merchant_id, idempotency_key) arbitrates concurrent inserts. A worker claims stale PENDING intents with a lease and queries the provider before retrying.

The database constraint is the cross-replica arbitration point:

CREATE UNIQUE INDEX one_payment_intent
    ON payment_intents (merchant_id, idempotency_key);

INSERT INTO payment_intents
    (merchant_id, order_id, idempotency_key, amount, currency, status)
VALUES (:merchant, :order, :key, :amount, :currency, 'PENDING')
ON CONFLICT (merchant_id, idempotency_key) DO NOTHING;

After an insert conflict, compare the stored order, amount, and currency before returning the previous result. Reusing a key with different money is a client error, not a reason to overwrite the original intent. Store a response snapshot or a stable status reference so a retry gets the same business answer even after the application process that created it has gone away.

Payment State Machine and Provider Ambiguity

Use monotonic transitions such as PENDING -> AUTHORIZED -> CAPTURED, PENDING -> DECLINED, and PENDING -> UNKNOWN. A timeout can move only to UNKNOWN; it must not move directly to DECLINED. Webhooks and reconciliation may resolve UNKNOWN, but no path should create a second provider intent for the same order while the first one is unresolved.

Authorization and capture also deserve separate keys when the provider treats them as different operations. Persist the provider reference before acknowledging success, and pass the same key on every network retry. If the provider does not support idempotency, query by a merchant-generated reference or use a provider-side dedupe field; if neither exists, the system cannot safely infer that a timeout was harmless.

Reconciliation and Operational Recovery

At 2,000 attempts per second, retain hot idempotency records through the provider’s retry window and archive older response bodies without deleting the audit reference. A reconciler compares local intents with provider transactions and settlement files, classifies each mismatch, and emits one repair command. Operators should see the order, local status, provider reference, amount, currency, last attempt, and next safe action.

During an incident, stop automatic retries for UNKNOWN intents if the provider is degraded, keep status queries bounded, and expose a pending state to the customer. After recovery, replay the oldest unknown intents first with the original keys. Alert on duplicate provider references, key reuse with mismatched parameters, unknown age, webhook lag, and reconciliation mismatch rate. The invariant is not merely “the endpoint returned 200”; it is at most one successful charge for the intended order amount.

Failure Handling

If the provider times out, mark UNKNOWN rather than FAILED; query by provider idempotency key or merchant reference. Webhooks are deduplicated by provider event ID and can arrive before the synchronous response. A reconciliation job compares settlement reports with local intents and raises exceptions for humans.

Scaling and Trade-offs

At 2,000 attempts/second, retain hot idempotency rows for at least the provider retry window and archive older payloads to cheaper storage. Partition by merchant or intent ID, keep provider calls outside the database transaction, and cap retries to avoid a payment retry storm. The design adds storage and reconciliation but prevents an expensive correctness failure.

Interview Follow-Ups

1. What if two requests insert the same key concurrently?

The unique constraint allows one insert to win. The loser reads the winner’s row and returns its state, waiting or polling if it is still pending. This is stronger than a cache because the decision is durable and shared by every replica.

2. Should a timeout be returned as a failure?

No. A timeout describes communication, not payment outcome. Return a pending or unknown status and provide a status endpoint while a worker queries the provider. Treating it as failed can trigger a second charge.

3. How do you secure idempotency keys?

Bind them to the authenticated merchant and order, validate amount and currency, rate-limit attempts, and avoid exposing provider secrets. Store a hash or encrypted response payload where appropriate. Authorization still runs on every retry.

4. How do webhooks interact with the request path?

Both paths update the same state machine with compare-and-set transitions. A webhook can finalize an unknown intent, but it cannot move a captured payment backward. Deduplicate event IDs and acknowledge only after durable processing.

5. What invariant do you monitor?

For every order, there must be at most one successful provider payment intent for the configured amount and currency. Alert on multiple provider references, unknown intents older than the SLA, reconciliation mismatches, and unusual key reuse.

Use retry budgets, webhook delivery, and Saga compensation to extend the answer.

References

  1. Stripe: Idempotent requests
  2. AWS: Making retries safe with idempotency

YouTube Videos

  1. “Designing a Payment System” - Gaurav Sen [https://www.youtube.com/watch?v=DOFflggE_0Q]

Share this post on:

Next in Series

Continue through the [object Object] with the next recommended article.

Related Posts

Keep Learning with New Posts

Subscribe through RSS and follow the project to get new series updates.

Was this guide helpful?

Share detailed feedback

Previous Post
A Downstream Service Times Out: How Do You Contain the Failure?
Next Post
Duplicate Webhooks: How Do You Process Them Safely?