Design a payments API (like Stripe)
Design a payments API like Stripe's: merchants create payments for their customers, the API charges cards through banks and card networks, and merchants learn the outcome, including refunds and failures.
A typical framing: "Merchants integrate with our API from their checkout. Networks time out, clients retry, banks answer late. Money must never be charged twice or lost. Design the resources, the payment lifecycle, the idempotency story and how merchants get notified."
TL;DR
Model a payment as a resource with an explicit state machine (requires_payment_method → processing → succeeded / failed, then refunds). Every mutating endpoint takes an Idempotency-Key: the server stores the key with the request fingerprint and the response, so a retry returns the original result instead of charging again.
Calls to the bank are the dangerous part: they can time out with an unknown result. Never guess. Mark the payment processing, then reconcile by querying the processor (with the same idempotency reference) or from settlement reports. Record every money movement in a double-entry ledger that always balances. Notify merchants with signed webhooks, delivered at least once with retries, and designed so merchants can process them idempotently. Card data never touches merchants' servers: a client-side SDK tokenizes it (PCI scope).
1. Requirements
Questions worth asking:
- Card payments only, or also bank transfers and wallets?
- One-step charge, or authorize then capture (hotels, marketplaces)?
- Refunds: full, partial, multiple?
- Do merchants need synchronous answers, or is async with webhooks fine?
- Multi-currency?
Functional
- Create a payment, confirm it with a payment method, capture, cancel.
- Refund fully or partially.
- Query payments and their history; receive events via webhooks.
Non-functional
- Correctness over availability for money: never double charge, never lose a payment.
- Safe retries from any client.
- Full auditability: every state change and money movement is recorded.
- Security: PCI DSS scope kept minimal, authenticated and signed communication.
2. Entities and classes
type Payment = {
id: string
merchantId: string
amount: number // minor units
currency: string
status: PaymentStatus
captureMethod: 'automatic' | 'manual'
paymentMethodId?: string // a token, never a raw card number
amountRefunded: number
processorReference?: string
version: number // optimistic concurrency on transitions
}
type LedgerEntry = {
transactionId: string
account: 'customer_funds' | 'merchant_balance' | 'fees' | 'refunds'
direction: 'debit' | 'credit'
amount: number
currency: string
}3. API
POST /v1/payments { amount, currency, captureMethod } Idempotency-Key: ...
POST /v1/payments/{id}/confirm { paymentMethod: "pm_tok_..." } Idempotency-Key: ...
POST /v1/payments/{id}/capture { amount? }
POST /v1/payments/{id}/cancel
POST /v1/refunds { paymentId, amount, reason } Idempotency-Key: ...
GET /v1/payments/{id}
GET /v1/events?type=payment.succeeded&after=evt_...Webhook delivery to the merchant:
POST https://merchant.example/webhooks
Payments-Signature: t=1764230400,v1=5f2b... (HMAC-SHA256 of timestamp + body)
{ "id": "evt_91", "type": "payment.succeeded", "data": { "object": { "id": "pay_42", "status": "succeeded" } } }4. Core logic
Idempotency
async function withIdempotency(
merchantId: string,
key: string,
request: Req,
run: () => Promise<Res>,
) {
// Insert first: a unique (merchantId, key) row acts as a lock for concurrent retries.
const inserted = await db.idempotency.tryInsert({
merchantId,
key,
requestHash: hash(request),
status: 'in_progress',
})
if (!inserted) {
const existing = await db.idempotency.get(merchantId, key)
if (existing.requestHash !== hash(request))
throw new Conflict('key reused with different parameters')
if (existing.status === 'in_progress') throw new Conflict('request in progress, retry later') // 409
return existing.response
}
const response = await run()
await db.idempotency.complete(merchantId, key, response)
return response
}Keys are scoped per merchant and kept for about 24 hours. The same key with different parameters is rejected, because that's a client bug, not a retry.
Confirming a payment and the unknown outcome
async function confirm(payment: Payment, paymentMethod: string) {
await payments.transition(payment, 'requires_payment_method', 'processing') // checks version
try {
// Our payment id is the processor's idempotency reference: retrying can't double charge.
const result = await processor.authorize({
reference: payment.id,
amount: payment.amount,
paymentMethod,
})
if (result.declined) return payments.transition(payment, 'processing', 'failed', result.reason)
await ledger.record(payment, result) // balanced debits and credits, same transaction as the status
return payments.transition(payment, 'processing', 'succeeded')
} catch (err) {
if (isTimeout(err)) {
// We don't know if the bank charged the card. Stay in processing and reconcile.
await reconciliationQueue.add(payment.id)
return payment
}
throw err
}
}A reconciliation worker asks the processor "what happened to reference pay_42?" and finishes the transition. Daily settlement files from the processor are matched against the ledger to catch anything that still slipped through.
Double-entry ledger
Every money movement is a transaction of entries whose debits and credits are equal. A $100 payment with a $3 fee: debit customer_funds 100, credit merchant_balance 97, credit fees 3. Entries are immutable; a refund is a new transaction, never an edit. Balances are sums of entries, and a sum that doesn't add up is an alert.
Webhooks
Write the event in the same database transaction as the state change (the transactional outbox pattern). A dispatcher reads the outbox and delivers with exponential backoff for up to a few days. Each event has an id; merchants dedupe by it and must not assume order (they can fetch the current object if needed). The signature includes a timestamp so old events can't be replayed.
5. Edge cases and extensions
- Concurrent requests on the same payment (capture and cancel at once): transitions use optimistic concurrency (
WHERE id = ? AND version = ?), and the loser gets409. - Partial refunds: check
amountRefunded + amount <= amountinside the transaction. - Authorization expiry: card authorizations expire after some days; a job cancels uncaptured payments in time.
- 3-D Secure:
requires_actionreturns a URL or SDK step for the customer to authenticate, then the flow resumes. - PCI scope: the browser SDK sends card details straight to the payment provider's vault and gets a token; merchants' servers only see the token.
- Multi-currency: store amounts with their currency, convert at a recorded rate, and keep ledger accounts per currency.
- API keys: separate test and live keys, restricted keys with limited permissions, and rotation.
Common follow-ups
- "Why not just use database transactions for everything?" The bank isn't in your database. A transaction can't roll back a charge at a card network, so you need state machines, idempotency references and reconciliation across the boundary.
- "What if the merchant's webhook endpoint is down for a day?" Keep retrying with backoff, show failures in the dashboard, and let merchants list missed events with
GET /v1/eventsand replay them. - "Exactly-once charging?" Not achievable over an unreliable network by itself. You get it in effect with at-least-once retries plus idempotency at every hop: client to API (idempotency key) and API to processor (payment id as reference).
What interviewers look for
- An explicit payment state machine, including the
processingstate for unknown outcomes. - Correct idempotency keys: scoped, fingerprinted, safe under concurrent retries.
- Reconciliation with the processor instead of guessing after a timeout.
- A double-entry ledger that is immutable and always balances.
- Webhooks via an outbox, signed, retried and processed idempotently, plus PCI-aware tokenization.