Quick revision
The short answer
The service stores payments with an exact amount, currency, status, provider, provider reference and a version, plus an append-only payment_events table. Requests are idempotent through a unique (client id, idempotency key) constraint that stores the request hash and response, and the payment id is reused as the provider's idempotency key on every retry. An explicit state machine with optimistic locking controls status changes; provider timeouts move a payment to UNKNOWN and are resolved by querying the provider, never by a blind retry with a new key. Outcomes are published through a transactional outbox, and a daily reconciliation against settlement files catches anything left.
What to remember
In this answer, we designed a payment service that never double-charges. The data model stores exact amounts, status, provider details and a version, with an append-only event history. A unique (client, idempotency key) constraint makes requests idempotent, and the payment id serves as the provider's idempotency key. An explicit state machine with optimistic locking controls status, timeouts lead to UNKNOWN and a lookup rather than a blind retry, a transactional outbox publishes outcomes reliably, and daily reconciliation against settlement files catches the rest.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The service stores payments with an exact amount, currency, status, provider, provider reference and a version, plus an append-only payment_events table. Requests are idempotent through a unique (client id, idempotency key) constraint that stores the request hash and response, and the payment id is reused as the provider's idempotency key on every retry. An explicit state machine with optimistic locking controls status changes; provider timeouts move a payment to UNKNOWN and are resolved by querying the provider, never by a blind retry with a new key. Outcomes are published through a transactional outbox, and a daily reconciliation against settlement files catches anything left.
Why this question is asked
A payment service has one non-negotiable property: a customer must never be charged twice for one order, even when networks time out, pods restart and providers fail. Every part of the design, from the table constraints to the retry rules, exists to protect that property. Interviewers ask this question because it brings together idempotency, state machines, distributed failures and reconciliation in one realistic system. In this answer, we will design the data model, make requests idempotent, enforce a state machine, call two providers safely, publish outcomes reliably, reconcile daily, and then answer the follow-ups on routing and on partial captures and refunds.
1The Data Model
The payments table holds the current state of each payment; payment_events records every change as an append-only history for audit and debugging.
Amounts are long minor units (or BigDecimal with a fixed scale) together with the currency, never double. The unique constraint on (client_id, idempotency_key) is the foundation of idempotency, as the next section shows.
2Idempotent Requests
Checkout sends each payment request with an Idempotency-Key header that it generates once per order attempt and reuses on every retry. We insert the payment with that key. If the insert fails on the unique constraint, this is a retry: we load the existing row, compare the stored request hash with the hash of the new body, and either return the stored response (same body) or reject with 422 (same key, different body, which is a client bug).
The second layer is at the provider. Every call for a payment uses our payment id as the provider's idempotency key, so even if we call the provider twice for the same payment, after a crash or timeout, the provider charges once. The rule that protects us most is this: a retry always reuses the same key. A new key means a new charge.
3The State Machine
A payment moves through explicit states: CREATED, then AUTHORIZED (money reserved), then CAPTURED (money taken), or FAILED; captured payments can become REFUNDED; and UNKNOWN covers the case where we do not know the provider's outcome. The allowed transitions live in one place in the Payment entity, and any other transition throws. The @Version column means two threads, for example the API flow and a provider webhook, cannot both update the same payment from the same version; the second gets an OptimisticLockException, reloads and re-checks the transition.
- CREATEDrow saved, provider not yet called
- Did the provider answer?YesAUTHORIZED or FAILEDNoUNKNOWN: query the provider
- AUTHORIZEDfunds reserved on the card
- CAPTUREDmoney taken; only from AUTHORIZED
- REFUNDEDonly from CAPTURED; partial refunds tracked separately
5 steps in order. Play them, or step through them one at a time.
Transitions are checked in the entity and protected by @Version.
4Calling Two Providers Safely
Each provider sits behind an adapter that implements one interface: authorize, capture, refund and lookup. Every call has a timeout (for example 10 seconds) and a Resilience4j circuit breaker, so when a provider is failing we stop sending it traffic within seconds instead of piling up slow calls.
The dangerous case is a timeout. We sent the request, but we do not know whether the provider charged the card. Retrying with a new key, or failing over to the second provider, could charge twice. So on a timeout the payment becomes UNKNOWN, and a resolver queries the same provider by our idempotency key until it gets an answer: if the charge exists, we record it; if the provider confirms it never received the request, we can safely try again, possibly with the other provider. Only payments that definitely failed before reaching the provider, or that were cleanly declined for technical reasons, are eligible for failover.
5Publishing Outcomes With an Outbox
The order service needs to learn when a payment is captured or failed. If we update the payment and then publish to Kafka as a separate step, a crash between the two loses the message. With a transactional outbox, the status update and an outbox row are written in the same database transaction. A relay, either a polling job or Debezium reading the database log, publishes outbox rows to Kafka and marks them sent. Messages may be published more than once, so the order service deduplicates by event id.
6Daily Reconciliation
Each provider sends a daily settlement file listing every transaction it processed. A reconciliation job matches each line to our payments by provider reference, then compares amount, currency and status. Unmatched or different rows go to an exception queue with an owner, typically the payments operations team, and the exception rate is tracked as a metric. This is the final safety net: anything our real-time flow got wrong, such as a lost webhook or a payment left UNKNOWN, appears here within a day.
- APIidempotency key, request hash, stored response
- Payment state machineallowed transitions,
@Version - Provider router and adapterstimeouts, circuit breakers, provider idempotency
- Outbox relayevents to Kafka for orders and finance
- Resolver and reconciliationUNKNOWN lookups, daily settlement matching
5 layers, from the top down. Step through them one at a time.
7Follow-up questions
How would you route between the two providers and fail over?
A router chooses the provider per payment from rules: card network and country, cost per transaction, and each provider's recent success rate and breaker state. If provider A's breaker is open, new payments go to B. Failover for an individual payment is allowed only when we know A did not process it: a connection refused, an open breaker before the call, or a definite technical error from A. After a timeout, the payment is UNKNOWN and stays with A until a lookup resolves it, because sending it to B too could charge the customer twice. The chosen provider is stored on the payment, so refunds and captures always go to the provider that holds the money.
What changes if you must support partial captures and refunds?
The single status is no longer enough. We add tables for captures and refunds, each row with its own id, amount, status and provider idempotency key, and keep running totals on the payment: authorized, captured and refunded amounts. Rules become amount checks: total captures may not exceed the authorized amount, and total refunds may not exceed the captured amount, enforced under the payment's version lock. Status then describes the overall position, such as PARTIALLY_CAPTURED or PARTIALLY_REFUNDED, and reconciliation matches each capture and refund line individually.
8Conclusion
In this answer, we designed a payment service that never double-charges. The data model stores exact amounts, status, provider details and a version, with an append-only event history. A unique (client, idempotency key) constraint makes requests idempotent, and the payment id serves as the provider's idempotency key. An explicit state machine with optimistic locking controls status, timeouts lead to UNKNOWN and a lookup rather than a blind retry, a transactional outbox publishes outcomes reliably, and daily reconciliation against settlement files catches the rest.
Open with
I would build it around one rule: a retry must always reuse the same key, so nothing can be charged twice. The payments table has the id, client id, idempotency key and a hash of the request, the merchant order id, the amount as minor units or BigDecimal with the currency, the status, which provider handled it, the provider reference and a version column, plus an append-only payment_events table for history.
Then, if they want more
Checkout sends an idempotency key per order attempt. I insert with a unique constraint on client id and key; if it already exists, I compare the request hash and return the stored response, or reject if the body differs. When calling a provider, I use our payment id as the provider's idempotency key, so even repeated calls charge once.
Status changes go through an explicit state machine, created, authorized, captured, failed, refunded, enforced in the entity, with @Version so a webhook and the API flow cannot both win. Each provider adapter has timeouts and a Resilience4j circuit breaker.
On a timeout I mark the payment UNKNOWN and resolve it by querying the provider; I never retry with a new key or fail over to the other provider, because that is exactly how double charges happen. Failover is only for payments that definitely did not reach the first provider.
Outcomes go to the order service through a transactional outbox, and every day we reconcile against the providers' settlement files and send mismatches to an exception queue.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Design a payment service in Java and Spring Boot that accepts payment requests from a...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/c99d939844/