Move money correctly: idempotency, a double-entry ledger, reconciliation and no lost or double charges.
“Design a payment system.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Pinning down the scope | “Payment system” can mean a card network, a wallet, or a platform that sits between merchants and a payment provider. A strong candidate asks which one, and says out loud that raw card numbers must never touch our servers. |
| Correctness when things time out | The hard question is not throughput. It is: the call to the payment provider timed out, so did the customer get charged? The interviewer wants idempotency keys, a status check, and a sweeper, not a hopeful retry. |
| Modelling money | Whole numbers in the smallest unit, an immutable double-entry ledger, and balances you can always recompute. A single balance column that you update in place is the classic weak answer. |
| Consistency across systems you do not own | You cannot run two-phase commit with a bank. The interviewer wants a state machine, a transactional outbox, compensations (void or refund) and idempotent consumers. |
| Proving it is right afterwards | Reconciliation against the provider settlement file, alerts, and a way to repair differences without rewriting history. This is what separates a design from a system that is run in production. |
We build a payment platform that lets merchants take payments through one or more external payment providers (PSPs). Correctness matters more than speed: money must never be created, lost or charged twice. Every request carries an idempotency key, every change to money is an immutable double-entry ledger entry written in the same database transaction as the payment state, and a daily reconciliation job proves our books match the provider's.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Pay-in or payouts too, which payment methods, who holds card data, refunds, and what the guarantees are. |
| 2. Estimate | 3 | Payments per second, provider calls in flight, unknown outcomes per day, ledger size, and the hot-merchant limit. |
| 3. API and data | 5 | Create payment with an idempotency key, the state machine, the ledger tables. |
| 4. High-level design | 8 | Gateway, payment service, idempotency, risk, provider adapters, ledger, outbox, webhooks, reconciliation. |
| 5. Deep dives | 15 | Exactly-once effect, the ledger, consistency with the provider, reconciliation, and security. |
| 6. Scale and failures | 7 | Provider outage, our database failover, a hot merchant, and stuck payments. |
| 7. Wrap up | 3 | Recap, the trade-offs, and what you would add next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| Are we building the card network and the bank, or a platform that sends payments to an external provider (PSP)? | Building a network is a different company. A platform integrates with providers and owns the ledger and the merchant experience. | A platform. We integrate with one or more PSPs and we do not build the card network. | Our hard problems are idempotency, the ledger, reconciliation and provider failures, not card routing. |
| Pay-in only, or payouts to merchants and refunds too? | Payouts move real money out and need their own safeguards and a bank file. | Pay-in, refunds and payouts to merchants. Disputes are mentioned, not fully built. | The ledger has accounts for merchant balances and payouts, and refunds are first-class. |
| Which payment methods: cards, wallets, bank transfers? | Each has a different flow, delay and failure mode. Bank transfers settle in days. | Cards and wallets first, through the PSP. Bank transfers are an extension. | A payment is a state machine that can wait for async results, not one blocking call. |
| Who handles raw card numbers? | Storing them puts our whole company in scope for strict card-industry rules (PCI DSS) and is a huge risk. | Never us. Card data goes straight from the browser to the PSP, and we only hold a token. | Hosted fields or a PSP-hosted form, tokens in our database, and a much smaller security scope. |
| May a payment be authorized first and captured later, and can it be partly captured or partly refunded? | Two steps and partial amounts multiply the states and the ledger entries. | Yes to authorize then capture, and yes to partial refunds. | A richer state machine, and amounts tracked per payment (authorized, captured, refunded). |
| What must be guaranteed if the provider does not answer in time? | This is the core question. A timeout does not mean the charge failed. | The customer must never be charged twice, and we must never lose track of a charge. | An idempotency key end to end, a PENDING state, a status inquiry, and a sweeper. |
| How do merchants learn the result: polling, webhooks, or both? | Webhooks are delivered at least once and can arrive late or out of order. | Both. Webhooks with signatures and retries, plus a GET to check the truth. | An outbox, a webhook dispatcher, and merchants told to treat the API as the source of truth. |
| How many payments, and what are the latency and availability targets? | It sizes the database and tells us whether we need sharding at all. | 1M payments a day, about 100 a second at peak. Create-payment 99.99% available. Most of the latency is the provider. | A single primary per region is enough at first. Sharding by merchant is a later step. |
| Multiple currencies, tax and fraud? | Each adds large amounts of work that can fill the whole interview. | One currency per payment, no conversion. Fraud is a call to a risk service. Tax is out of scope. | Currency is stored with every amount. We keep a clean place to call a risk score. |
| Assumption | Value |
|---|---|
| Payments per day | 1 million (all numbers here are illustrative assumptions) |
| Peak rate | 100 payments per second for a few minutes |
| Provider call time | about 0.8 s on average, and we give up after 5 s |
| Calls with an unknown outcome (timeout, dropped reply) | 0.1% of payments |
| Ledger entries per payment | 4 (the payment itself, plus the fee and the merchant share) |
| Row sizes | payment 1 KB, ledger entry 200 B, event 500 B, idempotency record 1 KB |
| Events and webhooks per payment | 2 |
| Idempotency keys kept for | 7 days |
| Time one transaction holds a merchant balance row lock | about 10 ms |
| What | Maths | Result |
|---|---|---|
| Average payments per second | 1,000,000 ÷ 86,400 | about 12 per second |
| Peak versus average | 100 ÷ 12 | about 8 times |
| Provider calls in flight at peak | 100 per second × 0.8 s, and 100 × 5 s if the provider stalls | about 80 normally, up to 500 in a stall |
| Unknown outcomes per day | 1,000,000 × 0.1% | 1,000 a day (about 1 every 90 seconds) |
| Ledger growth | 1,000,000 × 4 entries × 200 B | 800 MB a day |
| Payments and events growth | 1,000,000 × 1 KB, and 2,000,000 × 500 B | 1 GB and 1 GB a day |
| Total growth per year | (0.8 + 1 + 1) GB × 365, then × 3 copies | about 1 TB a year, 3 TB with 3 copies |
| Database writes at peak (about 10 rows per payment) | 100 per second × 10 | about 1,000 writes per second |
| Idempotency table | 7 days × 1,000,000 × 1 KB | about 7 GB (small, can sit in the main database) |
| Webhooks to send | 2,000,000 ÷ 86,400 | about 23 per second on average |
| Hot merchant limit if every payment updates its balance row | 1 second ÷ 10 ms | about 100 updates per second on one row |
| Daily settlement file to reconcile | 1,000,000 rows × 200 B | about 200 MB |
| Downtime allowed at 99.99% | 365 × 24 × 60 × 0.0001 | about 53 minutes a year |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | /v1/payments | Idempotency-Key header + { amount, currency, paymentMethodToken, merchantOrderId, capture: true | false } | 201 { paymentId, status } or 202 when still pending | Amount in minor units as an integer (1999 means 19.99). Same key and same body returns the saved response. Same key and a different body returns 422. A request still in flight returns 409. The merchant comes from the API key. |
| GET | /v1/payments/{id} | none | 200 { status, amountAuthorized, amountCaptured, amountRefunded, events } | The source of truth for merchants. Webhooks are only hints. Scoped to the merchant, so another merchant gets 404. |
| POST | /v1/payments/{id}/capture | Idempotency-Key + { amount? } | 200 { status } | Captures all or part of an authorized amount. A second capture over the authorized amount returns 409. |
| POST | /v1/payments/{id}/refunds | Idempotency-Key + { amount, reason } | 201 { refundId, status } | The total refunded can never exceed the amount captured. The check and the write happen in one transaction. |
| POST | (merchant URL) payment.succeeded | signed webhook { eventId, type, data } | 2xx from the merchant | Signed with HMAC and a timestamp. Retried with backoff for days. Delivered at least once, so merchants dedupe by eventId. |
| GET | /v1/balance | none | 200 { available, pending, currency } | Derived from ledger entries and cached for a few seconds. Never a column that is updated in place. |
| payments | Type | Why it is there |
|---|---|---|
| payment_id, merchant_id, merchant_order_id | ids | Unique on (merchant_id, merchant_order_id) so one order cannot become two payments. |
| amount, currency | bigint, text | Whole numbers in minor units. Never floating point. |
| status | enum | CREATED, PENDING, AUTHORIZED, CAPTURED, FAILED, VOIDED, REFUNDED. Only legal transitions are allowed. |
| amount_authorized, amount_captured, amount_refunded | bigint | Checked in the same transaction as any change, so refunds cannot exceed captures. |
| psp_name, psp_reference, our_reference | text | Our reference is saved before we call the provider, so a lost reply can always be looked up. |
| version, created_at, updated_at | int, timestamps | Optimistic locking, and the data for the stuck-payment sweeper. |
| idempotency_keys | Type | Why it is there |
|---|---|---|
| merchant_id, key | unique | A unique constraint is what makes a repeat safe, even when two requests race. |
| request_hash | text | Detects the same key with a different body (422). |
| status, response_code, response_body | enum, int, json | IN_PROGRESS or DONE, and the saved answer to replay. |
| created_at | timestamp | Old keys are removed after about 7 days. |
| ledger_accounts and ledger_entries | Type | Why it is there |
|---|---|---|
| account_id, type, currency | ids | Examples: customer funds in transit, PSP clearing, merchant payable, platform fee revenue, refunds. |
| txn_id, entry_id | ids | Entries of one business event share a txn_id. |
| account_id, direction, amount | id, enum, bigint | A debit or a credit. For every txn_id the debits add up to the credits. |
| payment_id, created_at | id, timestamp | Links an entry to its payment. Entries are append-only: no UPDATE and no DELETE. |
BEGIN;
INSERT INTO idempotency_keys (merchant_id, key, request_hash, status)
VALUES (:m, :key, :hash, 'IN_PROGRESS'); -- unique: a repeat fails here
INSERT INTO payments (payment_id, merchant_id, merchant_order_id, amount, currency,
status, our_reference)
VALUES (:id, :m, :order, :amount, :cur, 'CREATED', :ourRef);
INSERT INTO outbox (event_id, type, payload) VALUES (:e, 'payment.created', :json);
COMMIT;
-- Only now call the PSP, passing our_reference as the PSP idempotency key.| Component | What it does |
|---|---|
| API gateway | Authenticates the merchant's API key, applies rate limits, and rejects bad input early. |
| Idempotency layer | Stores the key with the request hash and the saved reply. A repeat returns the saved reply. A different body returns 422. A request still in flight returns 409. |
| Payment state machine | Owns the status of a payment and allows only legal transitions, with a version number to stop two writers clashing. |
| Risk service | Returns a score and rules (velocity, amount limits). We only call it. Its model is out of scope. |
| PSP adapters | One adapter per provider. They route by cost and success rate, apply timeouts and a circuit breaker, and pass our idempotency key on. |
| Ledger service | The only writer of money. It posts balanced, immutable entries in the same transaction as the payment state change. |
| Outbox, event bus and webhook dispatcher | Publish events reliably, deliver signed webhooks at least once with backoff, and let other systems react. |
| Stuck-payment sweeper and reconciliation | Ask the provider about payments that stay PENDING, and compare the daily settlement file with our ledger. |
| Token vault (at the PSP) | Holds the real card data. We store only a token, which keeps our security scope small. |
The problem: The customer double-clicks. The merchant's server retries after a network error. Our call to the PSP times out. In every case the same request can arrive twice, and the invariant is: one order produces at most one charge. The worst case is the timeout, where we cannot tell if the money moved.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Hope: retry on error | If the call fails, call again. | Nothing to build. | A timeout often means the charge happened. A retry then charges the customer twice. This is the classic bug. |
| Our own idempotency key only | Store a key per request in our database and return the saved answer on a repeat. | Stops duplicates from the merchant and the double-click. | Does not protect the call to the PSP. A timeout followed by our own retry still creates a second PSP charge. |
| Idempotency key end to end | Our key guards our API. We also send a derived key (our reference) to the PSP, which returns the same result for the same key. | A retry of the PSP call is safe. Covers the timeout case when the PSP supports keys. | Depends on the PSP honouring keys, and its keys expire after some time. |
| Inquiry before retry | Before any retry, ask the PSP for the status of our reference. Only create a new charge if the PSP has none. | Works even with a PSP that has weak idempotency. Resolves unknown outcomes. | More calls and some delay. The inquiry API must be reliable and fast. |
The invariant is one order, at most one charge. We enforce it in three places. A unique constraint on the idempotency key stops duplicate requests from merchants. The same reference, sent to the PSP as its idempotency key, stops duplicate PSP charges. And an unknown outcome is never turned into FAILED: the payment stays PENDING until the PSP tells us what happened.
The key and the result are saved in the same transaction as the payment state, so we can never have a payment without its key, or a key without its payment. Two requests racing with the same key are separated by the unique constraint: the second sees IN_PROGRESS and gets 409.
| What the retry looks like | What we do |
|---|---|
| Same key, same body, first request done | Return the saved reply (same status code and body). No new charge. |
| Same key, same body, first request still running | 409 and Retry-After. Do not start a second call. |
| Same key, different body | 422. The key is for one request only. Never guess which body was meant. |
| New key, same order id | A unique constraint on (merchant, order id) returns the existing payment. One order, one payment. |
| Our call to the PSP timed out | Mark PENDING. Ask the PSP about our reference. Only if it has no record, retry with the same reference. |
The problem: Money must be stored so that nothing is created or lost, every number can be explained, and mistakes are fixed without hiding them. A single balance column that we update in place can drift, lose history, and break under concurrent updates.
| Option | How it works | Good | Bad |
|---|---|---|---|
| One balance column per account | UPDATE accounts SET balance = balance + :x. | Simple and fast to read. | No history. A bug or a race corrupts it silently, you cannot tell why it is wrong, and every payment fights for the same row. |
| Transaction log, balance derived | Store each change as an immutable row. The balance is the sum of the rows. | A full history. Fixes are new rows. Easy to audit and replay. | Summing is slow at scale unless you keep a cached or periodic balance. |
| Double-entry ledger | Every business event posts at least two entries: a debit on one account and a credit on another, equal amounts, in one transaction. Debits always equal credits. | A built-in check: if the sums differ, something is wrong. Every unit of money has a source and a destination. | More rows and a chart of accounts to design. Needs discipline. |
| Event sourcing for everything | Store events for the whole payment system and rebuild state from them. | Total history and replay. | Heavier to build and query, and not required to get a correct ledger. |
The invariants are: entries are never changed or deleted, debits equal credits for every transaction, and balances are derived from entries. A bug can then be found (the sums will not match), explained (follow the entries) and fixed (post a correcting entry). Money is a whole number of minor units, with the currency next to it. A payment, its fee, a refund and a payout each post entries inside the transaction that changes the payment, so the books and the state cannot disagree.
A merchant's balance row would be a hot spot if every payment updated it: at about 10 ms per update that is about 100 a second. So we write only entries (inserts do not contend), compute balances by summing, and keep a cached balance refreshed every few seconds or by a batch. A payout checks a conservative balance.
| Event | Debit | Credit | Amount (example) |
|---|---|---|---|
| Customer pays 20.00, fee 0.60 | PSP clearing 20.00 | Merchant payable 19.40, Platform fee 0.60 | 2000 = 1940 + 60 |
| Refund 5.00 to the customer | Merchant payable 5.00 | PSP clearing 5.00 | 500 |
| Payout 14.40 to the bank | Merchant payable 14.40 | Payout in transit 14.40 | 1440 |
| Fee correction found in reconciliation | Platform fee 0.10 | Merchant payable 0.10 | 10 (a new entry, the old one stays) |
BEGIN; UPDATE payments SET status = 'CAPTURED', amount_captured = :amt, version = version + 1 WHERE payment_id = :id AND version = :seen AND status = 'AUTHORIZED'; -- 0 rows: stop INSERT INTO ledger_entries (txn_id, account_id, direction, amount, payment_id) VALUES (:t, :pspClearing, 'DEBIT', 2000, :id), (:t, :merchantPay, 'CREDIT', 1940, :id), (:t, :platformFee, 'CREDIT', 60, :id); -- a deferred check (or a test) that SUM(debits) = SUM(credits) for :t INSERT INTO outbox (event_id, type, payload) VALUES (:e, 'payment.captured', :json); COMMIT;
The problem: A payment touches our database, the PSP, the merchant's server and other internal systems. We cannot run one transaction across them. Our commit can succeed while publishing the event fails, the PSP can charge while our reply is lost, and a webhook can arrive twice or out of order.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Two-phase commit across parties | A coordinator asks everyone to prepare, then commit. | All or nothing in theory. | The PSP and the bank do not take part. Locks are held while waiting, and a coordinator crash blocks everyone. |
| Dual write | Write to the database, then publish the event in code. | Easy. | If the process dies between the two, the database and the event disagree. The classic way to lose an event. |
| Transactional outbox + state machine | Write the change and an outbox row in one local transaction. A relay publishes the row at least once. Each step has an explicit state, and failures are fixed with compensations (void or refund). | Local transactions only. No lost events. A crash resumes from the state. | Consumers see duplicates and must dedupe. State machines and compensations take care to design. |
| Event sourcing as the log | Make the event log the source of truth, with state derived from it. | Natural history and replay. | A larger change of the whole system. Not needed for this problem. |
Each hop gets its own guarantee. Inside our database we use one transaction for state, ledger entries and the outbox row. Between us and the PSP we use idempotent calls and a status inquiry, and a compensation if a later step fails: a void before capture, a refund after. Between us and everyone else we use the outbox: events are published at least once, in order per payment, and every consumer dedupes by event id.
Webhooks follow the same rule. We sign them (HMAC with a timestamp so they cannot be replayed), retry with backoff for days, and tell merchants that delivery is at least once, so they must dedupe by event id and treat GET /payments/{id} as the truth. See Saga, Outbox and Compensating Transactions for the building blocks.
| State | How we get here | Which way out |
|---|---|---|
| CREATED | Request accepted and saved | PENDING when we call the PSP, FAILED if risk declines |
| PENDING | PSP call started or outcome unknown | AUTHORIZED, CAPTURED or FAILED once known (sweeper or webhook from the PSP) |
| AUTHORIZED | PSP holds the funds | CAPTURED, or VOIDED if the merchant cancels or the hold expires |
| CAPTURED | Money is ours to settle | REFUNDED (partly or fully), or a dispute |
| FAILED, VOIDED, REFUNDED | Final | A correction is a new entry, never a status rewind |
The problem: Even a careful design drifts: a reply is lost, a webhook never arrives, a provider changes an amount, a bug posts the wrong entry. We need to find every difference between our books and the provider's, and fix it without rewriting history. Nobody should learn about a missing charge from an angry customer.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Trust our own database | Assume the ledger is right. | Nothing to build. | Silent errors pile up for months and are found by auditors. |
| Real-time checks only | Compare each payment with the PSP as it happens. | Fast feedback. | Cannot see what the PSP settles later, fees, adjustments or payments it recorded that we did not. |
| Daily settlement reconciliation | Load the PSP settlement file and match it to our ledger by PSP reference and amount. Classify every difference and route it. | Catches all kinds of drift. The standard practice in finance. | A day of delay, and a team to handle the exceptions. |
| Reconciliation plus sweepers and alerts | Add a sweeper for payments stuck in PENDING, and alerts on rates (unknown outcomes, mismatches, ledger imbalance). | Most problems are found within minutes, and the rest by the daily job. | More moving parts to keep healthy. |
The sweeper asks the PSP about every payment that stays PENDING more than a few minutes, using our reference. That is why we save the reference before the call: without it there is nothing to look up. The daily job compares the settlement file with the ledger and sorts each row into: matched, missing at the PSP, missing in ours, amount differs, duplicate, or settles on the next day. Each class has a default action, and anything that is not routine goes to a human queue.
Repairs are new ledger entries (an adjustment, a refund, a reversal), never edits. We also watch simple health numbers, such as the share of unknown outcomes and the sum of all ledger debits minus credits, which must always be zero. Disputes and chargebacks post to the ledger the same way.
| Difference found | Usual cause | Action |
|---|---|---|
| In our ledger, not in the PSP file | Our entries without a real charge, or the file is late | Ask the PSP. If no charge, reverse our entries and tell the merchant. |
| In the PSP file, not in our ledger | We gave up after a timeout, but the PSP charged | Create the payment from the PSP data, or refund if the order is gone. |
| Amount differs | Partial capture, fee, rounding or a currency issue | Post an adjustment entry and find the cause. |
| Two charges for one order | A retry without an idempotency key | Refund the extra charge, and fix the missing key. |
| On the next day's file | Cut-off time | Wait a day. Not an error. |
The problem: A payment system is a prime target and is subject to strict rules. We must keep sensitive data out of our systems, limit who can do what, and keep taking payments when one provider is down, without sending a payment twice.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Store card numbers ourselves, encrypted | Collect card data, encrypt it, and send it to the PSP from our servers. | Full control of the flow. | Our whole company falls into the strictest scope of the card-industry rules (PCI DSS), and a breach is catastrophic. |
| Hosted fields or a PSP-hosted page | The browser sends the card data straight to the PSP, which returns a token. We only see the token. | Card numbers never touch our systems. A much smaller scope. | Less control of the form's look, and a dependency on one PSP's token format. |
| Our own vault with tokens | A separate, isolated vault service stores card data and gives out tokens. | Portable between PSPs. | That vault is in full scope and must be built and run to the highest standard. |
| Several PSPs with routing | Route each payment by cost, success rate and method, and fail over if one is down. | Higher availability and negotiating power. | Failover must not double-charge. Tokens may be tied to one PSP. |
A real payment system must meet card-industry and privacy rules, and they shape the design: keep card data out of our systems, encrypt what we do hold (customer details, bank accounts) with keys in a KMS, keep secrets out of code, log every sensitive action in an audit log, and give each service and person only the access they need. These are design constraints, not a claim that any particular system is compliant.
For failover, the rule is: never send the same payment to a second PSP until we know the first one did not charge. If PSP A times out, we ask A about our reference first. Only a definite "no record" allows a retry, with a new reference, on PSP B. Routing uses a circuit breaker per provider, and tokens that are tied to one PSP stay with it.
| Control | What it does |
|---|---|
| Tokenization at the PSP | We keep a token. The card number never reaches our network. |
| Encryption and key management | Sensitive fields encrypted at rest with keys in a KMS, rotated, and with access logged. |
| Least privilege and separation of duties | Support staff cannot move money. Payouts need a second approval. Service accounts have narrow scopes. |
| Audit log | Every change of money, role or setting is recorded and tamper-resistant. |
| Rate limits and velocity checks | Stop card testing and runaway merchants. Alert on odd patterns. |
| Signed requests and webhooks | HMAC signatures and timestamps stop forged or replayed calls. |
| Order | Our ledger | PSP file | Result |
|---|---|---|---|
| ord-101 | 12.00 captured | P-9001 · 12.00 | Matched |
| ord-102 | 45.00 captured | P-9002 · 45.00 | Matched |
| ord-103 | 25.00 captured | P-9003 · 25.00 | Matched |
| ord-104 | 80.00 captured | P-9004 · 75.00 | Amount differs |
A simplified model with fixed data and no random numbers. With our reference saved before the call, the timed-out ord-106 matches and the sweeper fixes it. Without it, ord-106 and the PSP row become two rows nobody can join. With no idempotency key on the retry, the PSP charges ord-103 twice. The net difference is “money in the PSP file minus money we booked as captured”, before any repair. Errors can cancel each other out in a total, so we also count the rows that need a person.
| Bottleneck | Fix |
|---|---|
| A slow PSP ties up threads and connections (up to 500 calls in flight) | A hard timeout, a limit on concurrent calls per PSP, a circuit breaker, and a bulkhead so one provider cannot starve the others. |
| One merchant's balance row updated by every payment (about 100 a second cap) | Insert-only ledger entries, derived balances with a cached copy, and batch posting for very busy merchants. |
| Ledger table growth (800 MB a day) | Partition by month, keep recent partitions on fast storage, and archive older ones. Entries are immutable, so archiving is safe. |
| Database writes (about 1,000 a second at peak) | One primary is fine to start. Then add read replicas for GETs, and shard by merchant id when a single primary is no longer enough. |
| Webhook backlog when merchants are down | A per-merchant queue with exponential backoff for days, a cap on retries, and a dashboard so the merchant can replay events. |
| The daily reconciliation job | Stream the 200 MB file, match by an indexed PSP reference, and run it per PSP in parallel. |
| Failure | How the design copes |
|---|---|
| The PSP times out | Payment stays PENDING. We ask the PSP about our reference. If it has no record we retry with the same key. The customer is told it is processing, not that it failed. |
| The PSP is fully down | The circuit breaker opens. New payments route to another PSP (a new reference, only after the first call is known not to have charged). If there is none, we return a clear error, and do not queue charges silently. |
| Our primary database fails over | A synchronous replica takes over with no committed data lost. In-flight requests retry with their idempotency keys. Payments left PENDING are picked up by the sweeper. |
| We crash after the PSP charged but before we saved the result | The payment is PENDING with our reference. The sweeper asks the PSP, finds the charge and completes the state and ledger entries. |
| The event bus is down | Events stay in the outbox table. The relay publishes them when the bus returns. No payment is blocked. |
| A merchant's webhook endpoint is down | Retries with backoff for days. The merchant can read the truth from the API, and replay events from a dashboard. |
A payment platform on external providers: one transactional database holding payments, idempotency keys, an append-only double-entry ledger and an outbox. An Idempotency-Key guards our API and, as our reference, the provider call. Unknown outcomes stay PENDING until the provider says what happened. Events go out through the outbox, and a daily reconciliation proves our books match the provider's.
| Decision | What we gain | What it costs |
|---|---|---|
| A relational database with strong consistency | Real transactions, unique constraints and a ledger you can trust | A harder path to very large scale (sharding by merchant later) |
| An append-only double-entry ledger | History, an automatic check that debits equal credits, and easy audits | More rows, a chart of accounts to design, and derived balances |
| PENDING for unknown outcomes | Never a wrong FAILED, and no double charge | Customers wait, and a sweeper and reconciliation must run well |
| State machine and compensations instead of 2PC | Works with parties that will not join a transaction | More states to design and test, and refunds instead of rollbacks |
| Hosted fields with PSP tokens | A small security scope and no card data to lose | Less control of the form and some lock-in to token formats |
| Multiple PSPs | Availability and better prices | Failover logic that must never double-charge, and more to reconcile |
The heart of the interview. Show that you treat a timeout as unknown, and that every retry is safe.
Show that you can model money so mistakes are visible, and that you know where it gets hot.
Where the senior candidates separate themselves: multi-step failures and honest trade-offs.
Changed requirements, security, testing and growth.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Add payouts to bank accounts | A payout service posts a payout-in-transit entry, sends a bank file or API call with an idempotency key, and clears the entry when the bank confirms. Failed payouts reverse the entry. Approval limits and a conservative balance check protect against overpaying. |
| Add disputes and chargebacks | A dispute is a new state and a set of ledger entries that move the amount (and the fee) out of the merchant's payable account into a held account, with deadlines for evidence. Winning or losing posts the final entries. Nothing is edited. |
| Support many currencies | Amounts carry a currency, ledger accounts exist per currency, and a conversion is its own balanced transaction with a rate and a position account. Reconciliation is per currency and per provider. |
| Bank transfers that settle in days | More PENDING time, and a state for waiting. We rely on webhooks and polling, and reserve the merchant's funds only after the transfer clears. The sweeper and reconciliation matter more. |
| Marketplace: split one payment between several sellers | One payment, several credit entries in the same transaction (one per seller plus the platform fee). Refunds and disputes must be split in the same proportions. Payouts are per seller. |
| The interviewer asks for 99.999% availability | Active-active regions with each merchant homed in one region, synchronous replication inside it, and a fenced failover. Say honestly that strong consistency and five nines pull against each other, and that a short pause on one merchant is better than a split ledger. |
| Data must stay in one country | Shard and route by region so a merchant's payments, ledger and backups live in its region. Cross-region reporting uses aggregates, not raw rows. |
| Add subscriptions and retries of failed cards | A scheduler creates payments with deterministic idempotency keys (subscription id and billing date). A retry policy (days, backoff) and customer notifications handle declines. The scheduler is a separate service. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts drawing at once. Never asks who touches card data or what a timeout means. | Asks about methods, refunds and card data, and sets the scale. | Also names the guarantees (never double-charge, never lose a charge), sets the scope boundary with the provider, and says what is out of scope. |
| Estimation | No numbers, or a huge QPS guess that justifies sharding. | Gets payments per second and storage and sees that the scale is small. | Shows that unknown outcomes (about a thousand a day) and the hot merchant row, not throughput, drive the design. |
| Correctness | Retries on error, or says a transaction makes it exactly once. | Idempotency keys, a state machine and a PENDING state. | Walks the timeout case end to end, uses our reference as the provider's key, an inquiry before retry, and a sweeper, and explains where exactly-once effect begins and ends. |
| Money model | A balance column updated in place, or floats. | Integers in minor units and an immutable ledger. | Double-entry with balanced transactions in the same commit as the state, derived balances, hot-account handling, and fixes by new entries. |
| Consistency and recovery | A distributed transaction across everyone, or a dual write. | An outbox and idempotent consumers. | Outbox, saga with compensations, signed webhooks with retries, daily reconciliation with a classified difference list, and repair by new entries. |
| Trade-offs and operations | Presents one design as obviously right. | Compares options and mentions monitoring. | Names the cost of every choice, states what is cut for 45 minutes, covers provider failover that never double-charges, security scope and what to alert on. |
| Mistake | Do this instead |
|---|---|
| Treating a timeout as a failure and letting the customer pay again | A timeout is unknown. Keep PENDING, ask the provider by our reference, and tell the customer it is processing. |
| Retrying a charge without an idempotency key | Send our reference as the provider's key on every attempt, and check the status before any retry after a long gap. |
| A balance column that is updated in place | An append-only double-entry ledger with derived balances, so history and checks exist. |
| Floats for money | Integers in minor units with the currency stored beside them. |
| A dual write: save, then publish in code | A transactional outbox, so the event and the change commit together. |
| Two-phase commit with the payment provider | Local transactions, idempotent calls and compensations (void or refund). |
| Storing card numbers | Hosted fields and tokens, so card data never reaches our servers. |
| No reconciliation, or comparing only daily totals | Match row by row against the settlement file and count rows needing a person, because errors can cancel in a total. |
The idea behind every retry in this design.
How an event is published without losing it.
Multi-step work and compensations across parties.
What exactly-once can and cannot mean.
The guarantees the ledger transaction relies on.
What two concurrent payments can see of each other.
The tamper-resistant record of every money action.
How sensitive fields are encrypted and keys are protected.