Design a Payment System: Idempotency, State Machines and Reconciliation
Why a timeout is not a failure, how idempotency keys prevent double charges, and how a state machine, a double-entry ledger and reconciliation keep money correct.
A payment system moves money from a customer to a merchant through external parties such as banks and card networks. Unlike most systems, its primary requirement is not speed or scale but correctness: money must never be duplicated and never be lost.
The difficult cases are all partial failures. A request to the bank times out: did the payment happen or not? Simply sending the request again is how customers get charged twice. These notes explain how payment systems handle uncertainty safely.
1. Requirements
- Functional: initiate a payment for an order, query its status, and issue refunds.
- Functional: receive asynchronous results from the payment service provider (PSP) or bank.
- Non-functional: strong consistency. A payment is processed exactly once in effect; no double charge and no lost money.
- Non-functional: durability and auditability. Every movement of money is recorded permanently and can be traced.
- Non-functional: high availability matters, but when availability and correctness conflict, correctness wins.
- Security: card data is handled by a compliant provider and represented by tokens in our system.
2. Scale estimation
Assume 10 million payments per day, about 100 per second on average and perhaps 1,000 per second at a peak such as a sale. These volumes are modest compared with a feed or a chat system. A relational database handles them comfortably, which is convenient because relational transactions are exactly what the problem needs. The difficulty of a payment system is in its guarantees, not its throughput.
3. API
POST /api/v1/payments
Headers: Idempotency-Key: 5b1f0c9e-6a2d-4c57-9a41-2f6e1d0c77aa
Body: { "orderId": "o_8841", "amount": 149900, "currency": "INR",
"paymentMethodToken": "tok_3fa9" }
Response: 201 { "paymentId": "pay_1207", "status": "PENDING" }
GET /api/v1/payments/pay_1207
Response: 200 { "status": "SUCCESS" }
POST /api/v1/payments/pay_1207/refunds
Headers: Idempotency-Key: ...
Body: { "amount": 149900 }
POST /webhooks/psp <- provider notifies us of the final result
Body: { "reference": "pay_1207", "status": "SUCCESS", "signature": "..." }
Note: amounts are integers in the smallest currency unit (paise), never floats.4. The payment state machine
A payment is modelled as a state machine with a small set of states and strictly defined transitions. It starts as INITIATED when the record is created, becomes PENDING when the request has been sent to the provider, and ends in SUCCESS or FAILED. Refunds add further states.
The PENDING state is essential. It represents honest uncertainty: we have asked the bank and do not yet know the outcome. The familiar situation of 'amount debited but merchant has not received it' is a payment in the PENDING state: the bank has debited the customer, and the final confirmation has not yet reached the merchant's system. Terminal states never change; a SUCCESS payment cannot move back to PENDING or to FAILED.
INITIATED --request sent--> PENDING --provider confirms--> SUCCESS --> REFUND_PENDING --> REFUNDED
|
+------provider rejects--> FAILED
|
+------no answer---------> stays PENDING
(status check / webhook / reconciliation
will resolve it; never guessed)5. A timeout is not a failure
Suppose we send a charge request to the provider and receive no response within the time limit. There are three possibilities: the request never arrived; it arrived and failed; or it arrived, the customer was charged, and only the response was lost. From our side these are indistinguishable.
Treating the timeout as a failure and telling the user to pay again risks a double charge. Treating it as a success risks shipping goods that were never paid for. The correct action is to leave the payment in PENDING and find out the truth: call the provider's status API using our payment reference, and wait for the provider's webhook. Only when the provider reports a definite result does the state change.
If the final result is a failure but the customer's account was debited, the provider or bank reverses the debit automatically. If our system finds a successful charge for an order that was cancelled in the meantime, it issues a refund.
6. Idempotency
Retries are unavoidable: the user double-clicks, the mobile app retries on a poor network, a service retries after a timeout. An operation is idempotent if performing it several times has the same effect as performing it once. Payment creation is made idempotent with an idempotency key.
The client generates a unique key for each payment attempt and sends it with the request. The server stores the key, under a unique constraint, together with the request and its result. When a request arrives with a key that already exists, the server does not create a new payment; it returns the stored result of the original request. The same key is passed on to the provider, which applies the same rule on its side, so that a retried call to the provider also cannot charge twice.
The key is generated by the client, because only the client knows that two requests are the same attempt. The unique constraint in the database is what makes the check safe when two identical requests arrive at the same moment.
CREATE TABLE payments ( id BIGINT PRIMARY KEY, idempotency_key VARCHAR(64) NOT NULL UNIQUE, order_id BIGINT NOT NULL, amount BIGINT NOT NULL, -- smallest currency unit currency CHAR(3) NOT NULL, status VARCHAR(20) NOT NULL, -- INITIATED | PENDING | SUCCESS | FAILED psp_reference VARCHAR(64), created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL ); -- First request: the row is inserted, processing continues. -- Retry with the same key: the insert violates the UNIQUE constraint, -- so the service reads the existing row and returns its current status. INSERT INTO payments (id, idempotency_key, order_id, amount, currency, status, ...) VALUES (...);
7. High-level design
The payment service owns the payment records and the state machine. It talks to external providers through an adapter, records money movements in a ledger, and informs other services of results through events.
Client --> Order service --> Payment service ----------> PSP / bank
| ^ |
| +------ webhook -------+ (signed, may arrive twice)
v
+---------------------------+
| Payments DB (SQL, ACID) |
| payments, ledger_entries |
| outbox |
+-------------+-------------+
|
Outbox publisher v
Message queue --> Order service (mark paid)
--> Notification service
Status-check worker : polls the PSP for payments stuck in PENDING
Reconciliation job : daily, compares our records with the PSP settlement file8. The double-entry ledger
Balances are not stored as a single number that is overwritten. Money movements are recorded in a double-entry ledger, the same principle used in accounting for centuries. Every transaction produces at least two entries: a debit from one account and a credit to another, of equal amounts. The sum of all entries is always zero.
The ledger is append-only. Entries are never updated or deleted; a correction is a new pair of entries that reverses the earlier one. This gives a complete audit trail, and any account's balance can be recomputed from its entries. If the debits and credits ever fail to balance, something is wrong and it is detected immediately.
entry_id txn_id account debit credit
---------------------------------------------------------
9001 t_551 customer:42 149900
9002 t_551 merchant:17 146900
9003 t_551 platform:fees 3000
---------------------------------------------------------
totals 149900 149900 <- always equal9. Reconciliation
Even with all these safeguards, two independent systems can disagree: a webhook was never delivered, a bug skipped a state change, or the provider made an adjustment. Reconciliation is the periodic process of comparing our records with the provider's records. Each day the provider supplies a settlement file listing every transaction it processed. A job matches that file against our payments and ledger.
Any mismatch is flagged: a payment we hold as PENDING that the provider settled, a payment we hold as SUCCESS that the provider does not know, or a difference in amounts. Most cases are corrected automatically, and the rest go to a manual review queue. Reconciliation is the final safety net that guarantees the books are eventually correct.
10. Additional considerations
- Webhooks are delivered at least once, so the handler must be idempotent, verify the signature, and ignore transitions out of a terminal state.
- Updating the payment and publishing the event must not diverge. The transactional outbox pattern writes the event to an outbox table in the same database transaction and publishes it afterwards.
- Across services (order, payment, inventory), a saga with compensating actions such as a refund replaces a distributed transaction.
- Card data is tokenised by the provider; our systems store only tokens, which keeps most of the system out of compliance scope.
- Retries to the provider use exponential backoff and are limited; after that the status-check worker takes over.
Interview summary
- Requirements: correctness over speed; no double charge, no lost money.
- Model each payment as a state machine with a PENDING state.
- On timeout, check the status first; then retry or reverse. Never assume.
- Idempotency keys make every create and retry safe.
- A double-entry ledger records money, and daily reconciliation catches whatever slipped through.
Summary
Payment systems are designed around uncertainty. A state machine with an explicit pending state records what is known, status checks and webhooks resolve timeouts instead of guessing, idempotency keys make retries harmless, a double-entry ledger keeps an auditable record of every movement, and reconciliation with the provider guarantees that discrepancies are found and corrected.
Puneet Tiwari
Full Stack Developer
