Asked at
URL Shortener (TinyURL)
Asked from Junior level upFoundations & Storage
Distributed Rate Limiter
Asked from Mid level upAPI Gateway & Security
Distributed Key-Value Store
Asked from Senior level upFoundations & Storage
Distributed Notification Service
Asked from Mid level upMessaging & Queues
Distributed Web Crawler
Asked from Mid level upDistributed Systems
Metrics & Monitoring Platform
Asked from Senior level upObservability & Time-Series
Real-Time Chat App (like WhatsApp or Slack)
Asked from Mid level upReal-Time & WebSockets
Social News Feed (like X/Twitter)
Asked from Mid level upSocial & Feed Systems
Ride-Hailing App (like Uber)
Asked from Senior level upGeospatial & Real-Time
Low-Latency Stock Exchange Matching Engine
Asked from Staff level upFintech & Low Latency
Global Video Streaming Platform (like YouTube or Netflix)
Asked from Senior level upMedia & Streaming
Distributed Hotel & Ticket Reservation System
Asked from Mid level upE-Commerce & Transactions
Shared Document Editor (like Google Docs)
Asked from Staff level upReal-Time & Distributed State
Game Leaderboard
Asked from Junior level upCaching & Data Structures
File Sync Service (Dropbox / Google Drive)
Asked from Mid level upStorage
Payment System
Asked from Senior level upPayments & Transactions
Ad Click Aggregation
Asked from Senior level upStream Processing
AI Support Assistant (RAG)
Asked from Senior level upAI Systems
LLM Inference Platform
Asked from Senior level upAI Systems
Enterprise Semantic Search
Asked from Mid level upAI Systems
AI Code Completion
Asked from Senior level upAI Systems
LLM Gateway
Asked from Senior level upAI Systems
AI Agent That Takes Actions
Asked from Senior level upAI Systems
LLM Evaluation Platform
Asked from Senior level upAI Systems
AI Document Processing Pipeline
Asked from Mid level upAI Systems

Design a Payment System

Asked from Senior level upDomain: Payments & Transactions
Concepts to know first:

Take card payments for an online store through an external payment provider, without charging anyone twice or losing a payment.

An analogy

Like paying by card at a restaurant. If the terminal freezes, the waiter must not run your card again. At the end of the day, the restaurant's books must match the bank statement.

Where this design ends up. This is version 3 of 3. Part 5 builds it up from version 1 and says why each part was added.
  1. Clients
    • Shop
  2. Entry
    • API gateway
  3. Services
    • Payment service
    • Webhook handler
    • Outbox relay
    • Reconciliation job
  4. Queues, caches
    • Event stream
  5. Data, outside
    • Payments database
    • Card provider

1. Requirements and scope

Functional Requirements
  • Create a payment for an order and charge it through an external provider.
  • Handle results that arrive later by webhook, including 'pending'.
  • Refunds.
  • A ledger that records every movement of money.
Non-Functional Requirements & SLAs
  • Never charge twice for one order.
  • Never lose a payment that succeeded at the provider.
  • Correctness over availability: refuse rather than guess.
  • Every change is auditable.
Key Traffic Assumptions: 1 million payments a day, peaks of about 100 per second during sales. • Card numbers are handled by the provider's hosted fields; we never store them.

2. Back-of-the-envelope numbers

Writes and reads each second
  • Writes: 12 payments a second, on average (6%)
  • Reads: 200 status reads a second (94%)

Read-heavy: about 17 reads for each write. A cache and extra read copies help most here.

Write Throughput
≈ 12 payments/s on average, ~100/s at peak
Read Throughput
~200/s (order status, receipts)
Storage Growth
1M/day × ~2 KB (payment and ledger rows) × 365 ≈ 0.7 TB/year
RAM Cache Footprint
Small: idempotency keys for 24 hours ≈ 1M × 100 B ≈ 100 MB

3. API

POST/v1/payments{ orderId, amount, currency, idempotencyKey }
POST/v1/payments/{id}/refundsRefund all or part of a payment
POST/v1/webhooks/providerSigned status updates from the provider
GET/v1/payments/{id}Payment status

4. Data model and storage

Storage Strategy: A relational database (e.g. PostgreSQL): payments need transactions, unique constraints and a balanced ledger, and the volume is modest.
PAYMENT(id, order_id UNIQUE, idempotency_key UNIQUE, amount, currency, status, provider_ref) · LEDGER_ENTRY(id, payment_id, account, debit, credit, created_at) · OUTBOX(id, event, payload, published_at)

5. The design, in three versions

Version 1: Call the provider synchronously

The payment service calls the provider's API and saves the result.

Payment System: Version 1: Call the provider synchronously Version 1 of 3

The picture follows one request through the parts of this version, in order. Under it, switch a part off to see what the request does without it.

One request, step by step

Each numbered arrow is one step. Press "Simulate Request Flow" to follow them one at a time.

ShopPayment servicePayments databaseCard provider1234
  • The order of the steps
  • A request or its reply

The parts: switch one off

1. Clients

Shopasks to charge $20

2. Services

Payment servicemoves a payment through states

3. Data, outside

Payments databasepayments, ledger, events
Card providerapproves or declines

The steps in words0 of 4 steps shown

  1. Shop to Payment serviceHTTPS · 3 ms

    The shop asks to charge $20.

  2. Payment service to Card provideroutside call · 80 ms

    It calls the card provider and waits.

  3. Payment service to Payments databasequery · 8 ms

    It saves the result.

  4. Payment service to Shopreply · 20 ms

    The shop gets "paid" or "declined".

Why this version
The simplest way to take money.
Next bottleneck
A timeout leaves you not knowing whether the card was charged. A retry can then charge twice. A crash after charging but before saving the record loses it.

Write path, read path and failures

Each path follows one request through the final design (version 3), one hop at a time.

Write pathPay for an order

  1. Checkout page
  2. Gateway
  3. Payment service
  4. PostgreSQL
  5. Provider
  6. Outbox relay
  7. Kafka
  1. Checkout page to Gateway

    The page sends the order id, the amount and a key made once for this checkout. Card details go to the provider's own form, not to our servers.

  2. Gateway to Payment service

    The gateway checks the user and passes the request on.

  3. Payment service to PostgreSQL

    It saves the payment as PENDING under that key. If the same key comes again, it returns the first result instead.

  4. Payment service to Provider

    It asks the provider to charge the card and sends the same key. Providers such as Stripe then return the first charge on a retry, not a second one.

  5. Provider to Payment service

    The provider answers now, or later through a webhook.

  6. Payment service to PostgreSQL

    In one transaction it saves the new state, balanced ledger entries and an outbox row.

  7. Outbox relay to Kafka

    A relay publishes the outbox row as an event. Orders, receipts and analytics each read it.

Read pathCheck a payment

  1. Checkout page
  2. Gateway
  3. Payment service
  4. PostgreSQL
  1. Checkout page to Gateway

    After paying, the page asks for the payment by its id.

  2. Gateway to Payment service

    The request goes to the payment service.

  3. Payment service to PostgreSQL

    It reads the payment row from the database, not from a cache, because a payment's state must be current.

  4. Payment service to Checkout page

    It returns SUCCEEDED, FAILED or PENDING. While PENDING, the page says the payment is in progress and asks again.

What breaks, and what happens then

  • The provider times out after charging the card

    What users see
    We do not know whether the card was charged.
    What the design does
    The payment stays PENDING. A sweep asks the provider about it by the same key, and nothing is charged again before that answer.
  • The service crashes after saving the payment

    What users see
    The order may not hear that it was paid.
    What the design does
    The outbox row was saved in the same transaction, so the relay publishes it after the restart.
  • The provider sends the same webhook twice

    What users see
    The same success could be applied twice.
    What the design does
    The handler checks the payment's current state before it writes, so a repeat changes nothing.
  • Our records and the provider's disagree

    What users see
    Money may be missing or counted twice in our books.
    What the design does
    A daily job compares both lists and opens a case for each difference.

6. Deep dives

Unknown outcomes
A timeout is not a failure. Keep the payment PENDING and retry with the same idempotency key — the provider returns the original result instead of charging again. Anything still unknown is settled by the provider's webhook or by querying it. A UNIQUE constraint on order_id backs this up.
Double-entry ledger
Record each money movement as two sides that add up to zero. Money leaves one account, such as the customer, and enters others, such as the shop and fees. Entries are only ever added. A fix is a new entry. Because both sides always match, checking the books is a sum anyone can repeat.

7. Follow-up questions

  • The provider says the payment succeeded but your webhook handler crashed. How do you recover? (Providers retry webhooks, handlers are idempotent, and reconciliation catches anything missed.)
  • How would you add a second provider for failover without charging twice? (Never retry a payment on another provider until the first has confirmed it failed.)

What it costs

Your own servers are small: about 12 payments a second. The payment provider's fee on each payment is the real cost, and it is fixed by contract. A failed payment that needs a person to fix it costs more than any server.

Another way to design it

A hosted checkout page from the provider can take the card details for you. You build less and handle no card data. You give up control over how the payment page looks and works.

8. How answers are judged

A passing answer at Mid level. A complete design with numbers: about 12 payments a second on average, 100 at peak. It explains idempotency keys and goes deep on one part, such as retries or the ledger.

How each level is judged
What is judgedJuniorMidSeniorStaff
BreadthHow much of the system does the answer cover?Names the core parts: clients, servers, a database and a cache.Covers the whole main flow, from the request to the stored data and back.Builds a complete design without being led through it.Covers the system, the systems around it and who owns each part.
DepthHow far does it go into the hard parts?Explains what each part does and why it is there.Goes deep on one part, such as the database or the cache.Goes deep on the two or three riskiest parts.Goes deepest where the risk is largest, and explains why the risk is there.
DrivingWho leads the conversation?Follows the interviewer, step by step.Moves forward alone, with an occasional nudge.Leads the conversation from start to finish.Changes the problem when the question asked is not the right one.
Trade-offsAre choices compared and justified?Names more than one option.Says why one option was picked over another.Compares options in detail, with what each one costs.Ties each choice to cost, speed and risk for the business.
Unclear questionsWhat happens when the question is vague?Answers the questions that are asked.Asks questions to make the problem clear.Sets the scope and says what is left out.Questions the assumptions behind the problem itself.
ScopeWhat does it consider beyond the normal path?Covers the normal path, when everything works.Adds what happens when a part fails.Adds growth: what breaks at ten times the load, and the fix.Adds abuse, cost and the daily work of running the system.

Requirements and scope

Strong answer
Before I design, I want to check the scope. This charges cards through one provider for a single online store, not a marketplace splitting funds to sellers. I will assume idempotent charges, refunds and a ledger for audits are core, and that a second provider for failover is a later concern.
Weak answer
Customers pay by card, and I would route each charge to whichever of two providers is currently cheaper or faster. I would fail over automatically if one goes down.

Shows: Unclear questionsThe difference: The weak answer builds multi-provider failover into the core design, when the problem treats a second provider as a later extension worth asking about first.

Estimates

Strong answer
1 million payments a day is about 12 a second on average, with a stated peak of about 100 a second during sales. At roughly 2 KB per payment and its ledger entries, a year of records is about 0.7 TB, small enough for one database.
Weak answer
Sales peak at about 100 payments a second, so I would size storage for that rate all day: about 6 TB a year.

Shows: DepthThe difference: The weak answer sizes storage using the peak rate as if it ran all day. The strong one uses the average, since peak is a short burst, not the norm.

Core design

Strong answer
A payments table holds each payment's status by a unique idempotency key. Every state change also writes balanced ledger entries, a debit and a credit, so total debits always equal total credits. Postgres fits this well, since payments need transactions and the volume is modest.
Weak answer
A payments table tracks each order's status and a running balance. When a payment succeeds, I update the merchant's balance column directly by adding the amount.

Shows: DepthThe difference: Updating a balance column directly leaves no record of individual movements to audit or reconcile. A double-entry ledger of debits and credits does instead.

Deep dive

Strong answer
The hard part is a timeout: I do not know whether the provider actually charged the card. I keep the payment PENDING, not FAILED, and retry with the same idempotency key. The provider then returns its original result instead of charging again, backed by a unique constraint on order id.
Weak answer
If the call to the provider times out, I would mark the payment FAILED right away. I would let the customer try again with a new payment.

Shows: DepthThe difference: The card may already be charged at the provider despite the timeout. Marking it FAILED lets a retry double-charge; the strong answer keeps it PENDING.

Failures and trade-offs

Strong answer
If our webhook handler crashes, or the webhook itself never arrives, a payment could stay PENDING forever. A nightly reconciliation job compares our records against the provider's settlement report. It also queries any payment still PENDING past a few minutes, so nothing stays silently stuck.
Weak answer
The provider always retries webhooks until one succeeds. Once we call the provider, I would wait for its webhook to give the final result.

Shows: ScopeThe difference: A lost or endlessly failing webhook leaves the payment stuck PENDING forever. The strong answer also reconciles by polling the provider, not webhooks alone.

We wrote this guide in our own words, informed by public interview guides such as AlgoMaster and Hello Interview. We are not connected to either site. Interviewers differ. The guide and the example answers show the direction each level takes, not a checklist.

10. Check your design with your own AI

Write your design first. Then copy this prompt into the AI chat you already use, and add your design at the end. It asks for a score in each area, one fix for each, and two follow-up questions.

The site sends nothing anywhere. An AI review can be wrong, so check what it says against sections 8 and 9.

See the prompt
You are a system design interviewer. Review my design for the interview problem below.

Problem: Design a Payment System
Take card payments for an online store through an external payment provider, without charging anyone twice or losing a payment.

What users must be able to do:
- Create a payment for an order and charge it through an external provider.
- Handle results that arrive later by webhook, including 'pending'.
- Refunds.
- A ledger that records every movement of money.

How well it must work:
- Never charge twice for one order.
- Never lose a payment that succeeded at the provider.
- Correctness over availability: refuse rather than guess.
- Every change is auditable.

Numbers to assume:
- 1 million payments a day, peaks of about 100 per second during sales.
- Card numbers are handled by the provider's hosted fields; we never store them.

Judge my design at the Mid level.
A passing answer at this level: A complete design with numbers: about 12 payments a second on average, 100 at peak. It explains idempotency keys and goes deep on one part, such as retries or the ledger.

For each area below, say whether my design is strong, fine or weak. Give one reason and one fix for each:
1. Requirements and scope
2. Estimates
3. Core design
4. Deep dive
5. Failures and trade-offs

Then ask me the two follow-up questions an interviewer would ask next.
Do not write a full model answer for me.

My design:
[Describe your parts, how one request moves through them, and why you chose each one.]