Learning pathsPricingChecking sign-in…
Question Breakdowns

Payment System

A payment service must represent uncertainty without creating another charge.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
Payment orchestration, wallet ledger or actual fund custody?Legal/provider integration scope and accounting ownership differ.
Authorization/capture/refunds and supported currencies?Define money units and a complete payment-state model.
Provider timeout, duplicate webhook and reversal behavior?Idempotency, immutable ledger and reconciliation govern unknown effects.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Payment System: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Payment System: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
HTTP: Hypertext Transfer ProtocolThe request/response protocol used by web APIs and media fetching. Application retries still need safe operation identities.
PK: Primary KeyThe declared row identity in a database schema; it does not automatically enforce every cross-row business rule.

Payment System: Ledger and immutable revisions

What it means: A ledger is authoritative history of recorded monetary or obligation changes. Immutable revisions keep corrections auditable rather than overwriting the past.

Why this problem needs it: Money changes require auditable revisions and conservation.

How to use it: Commit an expense/revision and its balanced deltas together, use integer minor units with a currency policy, and reconstruct balances from accepted facts.

Example in this design: A capture of 2,500 and refund reservation of 1,500 leave 1,000 available for further refunds.

When it fits: Useful when edits, retries and reconciliation must preserve an explainable balance.

Alternative and limits: Mutable balances can be faster to read but still need safe revision history and reconciliation. Recording a settlement is not proof an external payment occurred.

Payment System: Idempotency key and stored operation result

What it means: Idempotency means replaying the same logical operation produces no additional business effect. A key identifies that operation under a defined scope.

Why this problem needs it: Network retries may follow a successful provider operation.

How to use it: Atomically associate a request key and payload fingerprint with its effect and result. Return the stored result on replay; reject incompatible payload reuse.

Example in this design: Replaying the same refund ID does not consume the remaining amount again.

When it fits: Needed when a timeout can hide a successful commit or a queue can redeliver.

Alternative and limits: Unique business identities can enforce selected effects. A cache of recent requests alone may expire too early or race; local keys cannot control an uncooperative external provider.

Payment System: Saga and compensation

What it means: A saga coordinates several separately committed business steps. Compensation is an explicit corrective business action after a partial outcome.

Why this problem needs it: Provider effects and local state do not share one transaction.

How to use it: Track each step and its stable identity; on failure reconcile uncertain outcomes before requesting an allowed compensating action.

Example in this design: Keep uncertain status and reconcile a timed-out capture before issuing a corrective refund.

When it fits: Useful when inventory, payment and dispatch have independent authorities.

Alternative and limits: A local transaction is simpler when all required state shares one database. Compensation may be partial or impossible; it is not automatic transaction rollback.

Payment System: Transactional outbox

What it means: An outbox is a table of pending events written in the same local transaction as business state. It closes the local database/event-publication gap.

Why this problem needs it: Committed payment status should reach downstream consumers despite publisher failure.

How to use it: Commit the business row and outbox row together; a publisher retries delivering events and tracks progress. Consumers deduplicate logical event identities.

Example in this design: Commit the status revision and its event row together, then deduplicate delivery.

When it fits: Useful when a database commit must eventually cause downstream work.

Alternative and limits: Direct database-then-broker writes can lose or duplicate publication around failure. An outbox does not make its external delivery atomic with every subscriber.

Interview scope and guarantees

Create payment intent, authorize or capture money through a provider, record a balanced ledger, support refunds and reconcile outcomes. Define currencies and decimal representation. External payment effects cannot be rolled back with a local transaction.

Capacity worksheet

Assume 10 million payments/day: about 116/s average and 1,157/s at 10× peak. With 500 ms mean provider latency, the peak requires about 579 concurrent provider calls. Ledger storage and audit retention grow with entries per payment, not just payment count.

Concrete API contract

Contract / pseudocode
POST /payments {merchantRequestId,amountMinor,currency,paymentToken}
GET /payments/{id}
POST /payments/{id}/capture {requestId}
POST /payments/{id}/refunds {requestId,amountMinor}

Data model and access paths

Contract / pseudocode
payments(id PK,merchant_id,request_key,request_hash,amount_minor,currency,state,provider_ref); UNIQUE(merchant_id,request_key)
operations(id PK,payment_id,type,idempotency_key,amount_minor,status); UNIQUE(payment_id,type,idempotency_key)
provider_attempts(id PK,operation_id,provider_key UNIQUE,state,provider_ref,next_check_at)
provider_events(provider,event_id,payload_hash); UNIQUE(provider,event_id)
ledger_transactions(id PK,operation_id UNIQUE)
ledger_lines(transaction_id,line_no,account_id,currency,amount_minor); PK(transaction_id,line_no)

Evolve a solution and explain each change

Three architecture decisions for Payment System, including the pressure each introduces.
Three architecture decisions for Payment System, including the pressure each introduces.
Read the diagram

Record business intent / Create a payment identity and exact amount/currency before contacting a provider. / A timeout cannot determine whether money moved.; Use durable workflow / Persist attempts and stable provider keys; verify callbacks and reconcile uncertain results. / Retries with new identities can charge twice.; Keep an auditable ledger / Represent monetary postings and reversals immutably; distinguish authorization, capture, and settlement. / A mutable status field alone is not complete accounting.

Open original
Payment System · architecture decisions
Three architecture decisions for Payment System, including the pressure each introduces.

Three architecture decisions for Payment System, including the pressure each introduces.

Step 1: Record business intent

Create a payment identity and exact amount/currency before contacting a provider. A timeout cannot determine whether money moved.

Step 2: Use durable workflow

Persist attempts and stable provider keys; verify callbacks and reconcile uncertain results. Retries with new identities can charge twice.

Step 3: Keep an auditable ledger

Represent monetary postings and reversals immutably; distinguish authorization, capture, and settlement. A mutable status field alone is not complete accounting.

Responsibility overview

Connected responsibilities for Payment System. Trace the authoritative and derived paths separately.
Connected responsibilities for Payment System. Trace the authoritative and derived paths separately.
Read the diagram

Merchant to Payment API: business payment identity; Payment API to Ledger DB: commit exact amount; Ledger DB to Attempt queue: provider attempt intent; Attempt queue to Reconciler: claim recovery work; Reconciler to Provider: stable provider key; Reconciler to Ledger DB: post reconciled outcome

Open original
Payment System · connected architecture
Connected responsibilities for Payment System. Trace the authoritative and derived paths separately.

Connected responsibilities for Payment System. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

Order O requests a 25-dollar charge with payment p17. The provider accepts attempt a1, but the connection drops. The service records unknown and retries using the same provider idempotency key or queries status. It does not create p18. A signed callback later reports success twice; deduplication and legal state transitions produce one capture record. A refund is a new referenced monetary operation, not deletion of the original charge. Reconciliation compares internal postings against provider reports and flags missing or contradictory outcomes for controlled repair.

Why these access paths matter

Unique business operation identity prevents repeated charge intent. Attempts are separate from payment state; provider event IDs deduplicate callbacks. Ledger entries record exact currency-specific amounts and balanced postings under the chosen accounting model. Index unknown attempts by next reconciliation time. Hold a database transaction only for local state, not across a slow external network call.

Build the baseline first

Payment System: baseline request paths.
Payment System · working baseline
Read the diagram

Payment API → intent and operation → outbox; Worker → provider with stable key → result record; Ledger transaction → balanced entries → reporting

Open original
Payment System · working baseline
Payment System: baseline request paths.

Payment System · working baseline

  1. Payment API → intent and operation → outbox.
  2. Worker → provider with stable key → result record.
  3. Ledger transaction → balanced entries → reporting.

Evolve the design under load

Payment System: additional scaling and recovery paths.
Payment System · scale and recovery paths
Read the diagram

Merchant partitions → bounded provider dispatch; Signed webhooks → dedup and transition checks; Settlement reports → reconciliation → exception workflow

Open original
Payment System · scale and recovery paths
Payment System: additional scaling and recovery paths.

Payment System · scale and recovery paths

  1. Merchant partitions → bounded provider dispatch.
  2. Signed webhooks → dedup and transition checks.
  3. Settlement reports → reconciliation → exception workflow.

Defend the hardest decision

Bind an idempotency key to the merchant and request fingerprint. Reusing a key with different amount or currency must fail. Model created, pending, authorized, captured, failed and uncertain outcomes deliberately; a transport timeout is uncertain, not failed. For each currency, ledger debits and credits balance within one transaction. Mutable account balances can be projections, but immutable entries provide the audit trail.

Failure and recovery analysis

A provider captures funds and the worker crashes before recording success. Retry or query using the same provider key; then insert the ledger transaction under a unique operation ID. A refund is another durable operation with its own identity and can fail independently. Prevent total refunds from exceeding captured value using an authoritative conditional check.

Security and privacy boundary

Tokenize payment credentials with the provider, restrict ledger writes, verify webhook signatures, and audit every manual correction.

Interview follow-ups with reasoning

Question: How do you handle webhook-before-response?

Show answer and explanation

Answer: Both converge through the same idempotent state transition.

Question: How do you recover after an outage?

Show answer and explanation

Answer: Reconcile uncertain operations and settlement totals before issuing new attempts.

Question: How do you migrate a ledger?

Show answer and explanation

Answer: Dual-validate balances and retain a reversible cutover boundary.

Operate and verify the design

Uncertain payment age, duplicate-key conflicts, unbalanced ledger attempts and settlement discrepancies.

Drop the capture response, retry with the same key and assert one provider effect and one ledger operation.

A second scenario to test transfer

A customer pays 2,500 minor units. The provider accepts the charge but the response is lost. The UI shows processing, not a definitive failure that encourages a new charge. The reconciler looks up the original provider identity, confirms success, appends the accounting event once, and updates the intent. A duplicate webhook finds the existing event identity and changes nothing.

A charge request times out. Is it safe to issue another charge with a new key?

Show answer and explanation

Answer: Not without resolving the first outcome. A new key denotes a new operation and can create a second charge. Query or retry using the original supported identity, then reconcile before deciding on a new business action.

Compare alternatives

ConcernProtectionOperational signal
Ambiguous chargeStable operation identityUnknown-state age
Duplicate callbackUnique inbox eventDuplicate rate
Missing callbackScheduled reconciliationUnmatched provider records
CorrectionNew ledger entriesBalance discrepancies

A design-changing exercise

Can a database rollback undo a provider charge?

Show answer and explanation

Answer: No. The provider is outside the local transaction. Recover through idempotency, status reconciliation, and an explicit compensating refund when appropriate.

Design workshop: a payment state and a balanced journal

Core scope is intent, authorization, capture, refund and reconciliation in one currency per payment. FX, disputes and merchant payouts are extensions. Choose durable intent acceptance, exact minor-unit amounts and no duplicated logical monetary operation. Provider/network uncertainty can delay finality; latency targets cannot turn unknown into failed.

Accept unique(merchant_id,request_key) with fingerprint over amount, currency and business identity. Same key/same fingerprint returns the original payment; changed fingerprint returns 409. Each authorize/capture/refund operation has its own stable identity and provider attempt key. Record provider inbox events uniquely and verify signatures. Do not store raw card secrets; accept tokenized provider references.

The core invariant is that one merchant request key creates one intent, one provider operation identity causes at most one externally deduplicated effect, and every posted journal transaction balances within one currency. A timeout is not a decline. The API must return the stable payment identity and a processing/unknown state when the processor outcome is ambiguous; it must never manufacture failure to meet a latency target.

Accept a payment intent across the processor trust boundary. Merchant client to Payment API: POST intent with merchant key, amount, currency and business identity; Payment API to Intent store and outbox: Validate and persist request fingerprint and stable payment ID; Payment API to Intent store and outbox: Commit payment intent and outbox event atomically; Merchant client to Payment API: POST confirm with operation key and tokenized payment method; Payment API to Intent store and outbox: Commit operation and provider-dispatch outbox record; Intent store and outbox to Processor adapter: Relay tokenized request using stable provider idempotency identity; Payment API to Merchant client: Return payment ID and processing state after durable acceptance
Accept a payment intent across the processor trust boundary.
Read the diagram

POST intent with merchant key, amount, currency and business identity; Validate and persist request fingerprint and stable payment ID; Commit payment intent and outbox event atomically; POST confirm with operation key and tokenized payment method; Commit operation and provider-dispatch outbox record; Relay tokenized request using stable provider idempotency identity; Return payment ID and processing state after durable acceptance

Open original
Accept a payment intent across the processor trust boundary
Accept a payment intent across the processor trust boundary. Merchant client to Payment API: POST intent with merchant key, amount, currency and business identity; Payment API to Intent store and outbox: Validate and persist request fingerprint and stable payment ID; Payment API to Intent store and outbox: Commit payment intent and outbox event atomically; Merchant client to Payment API: POST confirm with operation key and tokenized payment method; Payment API to Intent store and outbox: Commit operation and provider-dispatch outbox record; Intent store and outbox to Processor adapter: Relay tokenized request using stable provider idempotency identity; Payment API to Merchant client: Return payment ID and processing state after durable acceptance

Accept a payment intent across the processor trust boundary.

Suggested endpoints are POST /payment-intents with an idempotency key, POST /payment-intents/{id}/confirm, GET /payment-intents/{id}, and a signed processor callback endpoint. The intent key is merchant-scoped; operation keys are separately scoped to authorization, capture and refund. Store amount as integer minor units and currency explicitly. Tokenized payment details cross the processor boundary; raw card data and secrets never enter the general application database or logs.

Authorization reserves provider-side funds but is not captured accounting. For an illustrative captured $25 payment, post +2,500 minor units debit to processor receivable and −2,500 credit to merchant payable. Sign convention is debit positive, credit negative. Sum must be zero within the currency for every transaction; entries in different currencies cannot offset each other. On a $10 refund, reverse the corresponding obligation: debit merchant payable 1,000, credit processor receivable 1,000. Fees and settlement use separate explicit lines.

Balanced journal postings in USD minor units. Capture C1 / Processor receivable +2,500 / Merchant payable -2,500 / 0; Refund R1 / Merchant payable +1,000 / Processor receivable -1,000 / 0; Duplicate C1 event / No new transaction under operation identity / Balance unchanged / 0; Settlement extension / Cash received +net; fee expense +fee / Processor receivable -gross / 0
Balanced journal postings in USD minor units.
Read the diagram

Operation / Debit positive / Credit negative / Balance; Capture C1 / Processor receivable +2,500 / Merchant payable -2,500 / 0; Refund R1 / Merchant payable +1,000 / Processor receivable -1,000 / 0; Duplicate C1 event / No new transaction under operation identity / Balance unchanged / 0; Settlement extension / Cash received +net; fee expense +fee / Processor receivable -gross / 0

Open original
Balanced journal postings in USD minor units
Balanced journal postings in USD minor units. Capture C1 / Processor receivable +2,500 / Merchant payable -2,500 / 0; Refund R1 / Merchant payable +1,000 / Processor receivable -1,000 / 0; Duplicate C1 event / No new transaction under operation identity / Balance unchanged / 0; Settlement extension / Cash received +net; fee expense +fee / Processor receivable -gross / 0

Balanced journal postings in USD minor units.

Authorization holds provider-side funds but does not post captured-money journal entries. A partial capture posts only its confirmed amount; a later capture has its own identity. Refund postings reverse the merchant obligation and reduce processor receivable in the same currency. Settlement and fees are separate explicit operations rather than silently netted into capture.

Authorization and capture state transitions. Intent accepted / created / Positive integer minor units; one currency / No capture journal; Authorization starts / authorization_pending / Must match the intent's authorized amount / No capture journal; Processor confirms authorization / authorized / Capture total cannot exceed confirmed authorization / No capture journal; Capture starts / capture_pending / Reserve against captured plus pending/unknown captures / No journal until confirmed; Capture succeeds / partially_captured or captured / Post only confirmed capture amount / Balanced processor receivable and merchant payable; Timeout on any external operation / unknown / Keep amount reservation until reconciliation / Never imply failure or post speculatively
Authorization and capture state transitions.
Read the diagram

Operation event / Payment/operation state / Amount rule / Ledger rule; Intent accepted / created / Positive integer minor units; one currency / No capture journal; Authorization starts / authorization_pending / Must match the intent's authorized amount / No capture journal; Processor confirms authorization / authorized / Capture total cannot exceed confirmed authorization / No capture journal; Capture starts / capture_pending / Reserve against captured plus pending/unknown captures / No journal until confirmed; Capture succeeds / partially_captured or captured / Post only confirmed capture amount / Balanced processor receivable and merchant payable; Timeout on any external operation / unknown / Keep amount reservation until reconciliation / Never imply failure or post speculatively

Open original
Authorization and capture state transitions
Authorization and capture state transitions. Intent accepted / created / Positive integer minor units; one currency / No capture journal; Authorization starts / authorization_pending / Must match the intent's authorized amount / No capture journal; Processor confirms authorization / authorized / Capture total cannot exceed confirmed authorization / No capture journal; Capture starts / capture_pending / Reserve against captured plus pending/unknown captures / No journal until confirmed; Capture succeeds / partially_captured or captured / Post only confirmed capture amount / Balanced processor receivable and merchant payable; Timeout on any external operation / unknown / Keep amount reservation until reconciliation / Never imply failure or post speculatively

Authorization and capture state transitions.

Enforce balanced posting through one trusted journal-writing transaction/service. Insert transaction header unique(operation_id), insert all lines, verify currency-specific sum and amounts, then mark posted; no reader treats incomplete lines as a committed journal. A balance check across rows needs a transaction/deferred validation or controlled writer, not a per-row CHECK pretending to sum unrelated rows.

sql
BEGIN;
SELECT captured_minor,refunded_minor,reserved_refund_minor
FROM payments WHERE id=:payment FOR UPDATE;
-- Return existing refund identity before checking remaining amount.
-- Require requested <= captured-refunded-reserved_refund.
-- Reserve amount and insert refund operation + provider outbox together.
COMMIT;

Refund reservation prevents two concurrent $15 refunds from spending the same $25 capture. Unknown refunds keep their reservation until reconciled; definitive failure releases it once; confirmed refund moves it from reserved to refunded and posts the journal once. Total successful+pending reserved refunds cannot exceed captured funds. A new refund request key does not safely resolve an uncertain previous refund.

Capture timeout reconciles the original provider operation. Merchant to Payment authority: Payment P/request K; create capture C1; Payment authority to Provider: Invoke provider with stable key C1; Provider to Payment authority: Response lost after effect may have occurred; Payment authority to Merchant: Return processing/unknown and original P; Reconciler to Provider: Query/retry original supported C1 identity; Reconciler to Payment authority: Verified success -> one journal transaction for C1
Capture timeout reconciles the original provider operation.
Read the diagram

Payment P/request K; create capture C1; Invoke provider with stable key C1; Response lost after effect may have occurred; Return processing/unknown and original P; Query/retry original supported C1 identity; Verified success -> one journal transaction for C1

Open original
Capture timeout reconciles the original provider operation
Capture timeout reconciles the original provider operation. Merchant to Payment authority: Payment P/request K; create capture C1; Payment authority to Provider: Invoke provider with stable key C1; Provider to Payment authority: Response lost after effect may have occurred; Payment authority to Merchant: Return processing/unknown and original P; Reconciler to Provider: Query/retry original supported C1 identity; Reconciler to Payment authority: Verified success -> one journal transaction for C1

Capture timeout reconciles the original provider operation.

Unknown captures and refunds keep their amounts reserved, so a caller cannot create a fresh key to spend the same authorization or refund balance again. A provider's idempotency-key retention window is finite and provider-specific. Before retrying after that horizon, query the original object or settlement evidence and escalate unresolved cases. Failover to another provider is a new external operation and can duplicate the effect while the first result is unknown; make that risk explicit rather than silently switching.

Legal states distinguish intent, authorization_pending, authorized, capture_pending, captured and failed, with unknown attempt state where a result is ambiguous. Settlement is separate from capture. Multiple captures, if supported, each reserve part of authorized remaining amount under a payment lock and have their own identity. A terminal capture failure cannot override a verified captured outcome from another authoritative provider event.

Callbacks can arrive twice or out of order. Apply event IDs once, but also reconcile the current provider object/operation state; event arrival order is not state order. Provider key retention is finite and provider-specific. For example, Stripe documents that idempotency keys can be pruned after they are at least 24 hours old; that window is not a universal provider contract. After the configured provider horizon, do not blindly retry a monetary request under a recycled key; query original object/settlement evidence and escalate unresolved ambiguity. Reconciliation compares operation totals, journal postings and provider settlement reports and appends corrections with auditable reasons.

The reference model at examples/system-design/payment_system.py represents intents, operations, provider attempts, callback inbox, ledger transactions and a durable outbox under one lock. tests/test_payment_system_model.py exercises unknown-result recovery, refund reservations, signed callback binding, changed-key conflicts and duplicate post-commit responses. In production, replace the lock with database transactions and unique constraints: post the ledger and enqueue the merchant event in the same transaction, then let an at-least-once relay deliver it. The callback handler stores authenticated evidence and acknowledges after its inbox record is durable.

For an illustrative capacity decision, assume 500 processor operations/s and 250 ms mean processor latency. Little's Law gives about 125 in-flight calls; a 2× operating headroom target yields 250 bounded concurrent calls. More workers cannot raise a processor's contracted rate limit. Partition idempotency, operation and ledger lookup by payment/merchant identity, then use a shared provider quota across all workers. Keep slow reconciliation and settlement ingestion off the synchronous intent path.

Post a balanced ledger and publish by transactional outbox. Processor callback to Callback inbox: Verify signature, bind event to provider operation and deduplicate event ID; Callback inbox to Payment and ledger transaction: Commit event inbox, operation status and balanced journal once; Payment and ledger transaction to Payment and ledger transaction: Insert merchant webhook outbox row with the ledger transaction; Payment and ledger transaction to Webhook relay: Relay event at least once using stable merchant event identity; Webhook relay to Processor callback: Merchant retry sees same event ID; no second financial posting
Post a balanced ledger and publish by transactional outbox.
Read the diagram

Verify signature, bind event to provider operation and deduplicate event ID; Commit event inbox, operation status and balanced journal once; Insert merchant webhook outbox row with the ledger transaction; Relay event at least once using stable merchant event identity; Merchant retry sees same event ID; no second financial posting

Open original
Post a balanced ledger and publish by transactional outbox
Post a balanced ledger and publish by transactional outbox. Processor callback to Callback inbox: Verify signature, bind event to provider operation and deduplicate event ID; Callback inbox to Payment and ledger transaction: Commit event inbox, operation status and balanced journal once; Payment and ledger transaction to Payment and ledger transaction: Insert merchant webhook outbox row with the ledger transaction; Payment and ledger transaction to Webhook relay: Relay event at least once using stable merchant event identity; Webhook relay to Processor callback: Merchant retry sees same event ID; no second financial posting

Post a balanced ledger and publish by transactional outbox.

Exercise: Capture is $25. Two $15 refund requests race and one accepted refund later times out. May the second use a fresh key and proceed?

Show answer and explanation

Answer: No. The first reserves $15, leaving $10 refundable. Its timeout remains unknown/reserved until resolved. Reusing the original identity/status avoids a second effect; a fresh key represents another operation.

Final topology and operations

Payment System final topology: trust boundaries and bounded work. Intent / Merchant key, request fingerprint and payment state / Synchronous durable create / Same key/terms return one payment identity; Processor / Tokenized request and operation-scoped provider key / Async rate-limited attempts / Timeout stays unknown until original operation is reconciled; Journal / Immutable balanced entries per currency / Atomic with operation status and outbox / One ledger transaction per confirmed monetary operation; Callback / Signed event inbox and provider object reference / Async deduped ingestion / Event replay cannot post twice or regress final state; Refund / Captured less refunded and pending/unknown reservations / Account/payment serialized update / Pending refunds reserve available refundable amount
Payment System final topology: trust boundaries and bounded work.
Read the diagram

Path / Authority / Mode and bound / Invariant; Intent / Merchant key, request fingerprint and payment state / Synchronous durable create / Same key/terms return one payment identity; Processor / Tokenized request and operation-scoped provider key / Async rate-limited attempts / Timeout stays unknown until original operation is reconciled; Journal / Immutable balanced entries per currency / Atomic with operation status and outbox / One ledger transaction per confirmed monetary operation; Callback / Signed event inbox and provider object reference / Async deduped ingestion / Event replay cannot post twice or regress final state; Refund / Captured less refunded and pending/unknown reservations / Account/payment serialized update / Pending refunds reserve available refundable amount

Open original
Payment System final topology: trust boundaries and bounded work
Payment System final topology: trust boundaries and bounded work. Intent / Merchant key, request fingerprint and payment state / Synchronous durable create / Same key/terms return one payment identity; Processor / Tokenized request and operation-scoped provider key / Async rate-limited attempts / Timeout stays unknown until original operation is reconciled; Journal / Immutable balanced entries per currency / Atomic with operation status and outbox / One ledger transaction per confirmed monetary operation; Callback / Signed event inbox and provider object reference / Async deduped ingestion / Event replay cannot post twice or regress final state; Refund / Captured less refunded and pending/unknown reservations / Account/payment serialized update / Pending refunds reserve available refundable amount

Payment System final topology: trust boundaries and bounded work.

Lose processor response, replay callback, crash after posting. Merchant to Payment service: Submit stable capture identity C1; Payment service to Processor: Provider accepts, but response is lost; record operation unknown; Reconciler to Processor: Query original C1; callback event E1 may arrive more than once; Processor to Payment service: Deduplicate event and atomically post balanced journal plus outbox; Payment service to Payment service: Crash after durable commit before relay or HTTP acknowledgment; Merchant to Payment service: Retry same request; return prior state and relay the same event identity; Payment service to Reconciler: Reconcile processor object; never create C2 solely from timeout
Lose processor response, replay callback, crash after posting.
Read the diagram

Submit stable capture identity C1; Provider accepts, but response is lost; record operation unknown; Query original C1; callback event E1 may arrive more than once; Deduplicate event and atomically post balanced journal plus outbox; Crash after durable commit before relay or HTTP acknowledgment; Retry same request; return prior state and relay the same event identity; Reconcile processor object; never create C2 solely from timeout

Open original
Lose processor response, replay callback, crash after posting
Lose processor response, replay callback, crash after posting. Merchant to Payment service: Submit stable capture identity C1; Payment service to Processor: Provider accepts, but response is lost; record operation unknown; Reconciler to Processor: Query original C1; callback event E1 may arrive more than once; Processor to Payment service: Deduplicate event and atomically post balanced journal plus outbox; Payment service to Payment service: Crash after durable commit before relay or HTTP acknowledgment; Merchant to Payment service: Retry same request; return prior state and relay the same event identity; Payment service to Reconciler: Reconcile processor object; never create C2 solely from timeout

Lose processor response, replay callback, crash after posting.

SLIs: intent acceptance latency and conflict rate; authorization/capture/refund completion and unknown age; provider timeout and decline rate; callback signature failures, duplicate rate and lag; journal imbalance (must remain zero); refund reservation backlog; settlement reconciliation difference; and outbox delivery age.

Overload and recovery: enforce global processor rate and concurrency limits, cap webhook inbox/outbox backlog, and shed noncritical status reads before payment writes. During processor outage, keep accepted operations durable, leave ambiguous operations unknown, stop unsafe provider switching, and reconcile from the original provider reference when service returns. On a journal/outbox discrepancy, pause affected merchant operations and rebuild from immutable transactions and processor evidence; never edit balances without an auditable correction transaction.

Access and cost: tokenize card details, encrypt provider references, restrict payment reads by merchant, verify callback signatures with rotated secrets, redact account details from logs, and audit support and ledger access. Processor fees, chargeback handling, tokenization and reconciliation operations dominate cost; processor rate limits and webhook delivery capacity are the primary overload ceilings.

Practice prompt: Design a payment-intent service with authorization, capture, refunds, signed callbacks and a balanced journal. For a $25 capture followed by two concurrent $15 refunds, show which request is reserved, what happens when its processor response is lost, and how a later callback changes the state.

Failure follow-up: The processor accepted a capture, the response timed out, a callback is replayed, and the process crashes after ledger commit but before the merchant receives a webhook. Walk the operation, journal, outbox and retry identities.

Rubric: The invariant is that one logical provider operation has one stable identity and every posted ledger transaction balances per currency. A strong design uses integer minor units, merchant-scoped request idempotency, separate operation keys, unknown rather than blind failure on timeout, bounded amount reservations, signed/deduplicated callbacks, and an atomic journal-plus-outbox transaction. It explains provider key expiration, safe reconciliation, refund concurrency and why queue delivery does not guarantee exactly-once external effects.

Stripe idempotent requests and webhooks document one provider's boundaries. Balanced accounting and refund reservation are application invariants.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Lose the processor response, replay callbacks, and crash after ledger commit; no second charge is caused by blind retry.

Operational contract

AreaDecision and signals
SLIsIntent-to-terminal latency; unknown processor state age; duplicate webhook rate; ledger imbalance; refund lag.
Overload limitsCap processor attempts, webhook backlog, idempotency-key retention, and reconciliation scans.
RecoveryQuery processor by stable reference; replay signed callbacks; reconcile ledger against settlement reports before closure.
Access controlsUse tokenized payment data, signed callbacks, least-privilege processor access, and strict sensitive-data redaction.
Dominant costProcessor transaction fees, fraud/risk checks, and ledger/audit retention.

Senior-level interviewer follow-ups

Question: The provider charged the card but the response and webhook are both delayed. What does the customer see?

Show answer and explanation

Answer: Keep the intent in an unknown or pending state and reconcile by provider idempotency key/status. Do not retry as a fresh charge or report failure until the outcome is known.

Question: How do refunds remain correct when two support agents act concurrently?

Show answer and explanation

Answer: Reserve refundable balance under an account/payment lock or conditional version, create an idempotent refund intent, and post a balanced journal only after the provider outcome is reconciled.

A 60-second design answer

I would record an idempotent payment intent and outbox entry before calling the provider. The external request uses a stable provider key; timeout becomes an unknown outcome that is reconciled by callback or query. A balanced journal records captures and refunds, while conditional reservations prevent over-refunding. I would monitor unknown duration, webhook lag, journal balance, and reconciliation backlog.

Multi-step Processes PostgreSQL

Technical references

Provider idempotency contract example.

PostgreSQL transaction isolation and concurrent updates.

Reserve refund capacity before the provider call

Capture P1 is 2,500 minor units in one declared currency. Two refund requests each want 1,500. An atomic local decision reserves refund R1=1,500 and rejects R2 because only 1,000 remains refundable. Calling both providers before that reservation can over-refund. An unknown R1 result retains its reserved value until reconciliation establishes the applicable outcome.

Contract / pseudocode
captured: 2500
R1 pending reserve: 1500 -> available refundable 1000
R2 request 1500 -> reject
duplicate R1 callback -> no second ledger posting
captured: 2500; R1 pending reserve: 1500 -> available refundable 1000; R2 request 1500 -> reject; duplicate R1 callback -> no second ledger posting
Reserve refund capacity before the provider call
Read the diagram

captured: 2500; R1 pending reserve: 1500 -> available refundable 1000; R2 request 1500 -> reject; duplicate R1 callback -> no second ledger posting

Open original
Reserve refund capacity before the provider call
captured: 2500; R1 pending reserve: 1500 -> available refundable 1000; R2 request 1500 -> reject; duplicate R1 callback -> no second ledger posting

Reserve refund capacity before the provider call

Represent capture/refund operations and immutable ledger facts separately. Integer minor units avoid ordinary floating-point currency mistakes but still need currency exponent and rounding rules. Entries balance under a defined accounting model; a callback arriving first does not justify overwriting the payment with whichever state arrived last. Stable provider operations, verified callbacks and periodic reconciliation complete the uncertainty path.

Show answer and explanation

Answer: A timeout is not evidence that no charge/refund occurred. A new key is a new intent and can create another effect. Resolve R1 before spending its reserved refund capacity again.

Decision review: Payment System

Payment System: What it is

A payment design records money operations and reconciles captures and refunds with an external provider.

Payment System: Why it is needed

Unknown responses, duplicate callbacks and concurrent refunds can violate conservation if treated as a single overwriteable status.

Payment System: When to use it

Use integer minor units with a declared currency scale, stable operation identities and reserved capacity for pending outgoing effects.

Payment System: How to use it

Atomically reserve eligible refund capacity before calling the provider. Track each operation separately, apply provider facts idempotently and post balanced journal entries once per applicable fact.

Payment System: Compare an alternative

Waiting for provider confirmation before showing acceptance reduces pending states but cannot remove an uncertain timeout. A durable pending contract is often more honest and operable.

Payment System: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

A capture is 2,500 minor units. Refund R1 reserves 1,500 and times out. R2 asks for another 1,500; only 1,000 unreserved units remain, so it cannot also reserve the full amount. Replaying R1’s callback does not post a second refund.

Payment System: Capture amount 2500 minor units; R1 reserves 1500; reply becomes unknown; Only 1000 remains available for another refund; Replay of R1 fact posts no second refund
Payment System: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

Capture amount 2500 minor units; R1 reserves 1500; reply becomes unknown; Only 1000 remains available for another refund; Replay of R1 fact posts no second refund

Open original
Payment System: worked example
Payment System: Capture amount 2500 minor units; R1 reserves 1500; reply becomes unknown; Only 1000 remains available for another refund; Replay of R1 fact posts no second refund

Payment System: a concrete state and recovery trace under the exercise assumptions.

May a timeout release R1’s reserved value immediately?

Show answer and explanation

Answer: Not if the refund may already have succeeded. Reconcile the same provider operation or follow a declared uncertainty policy. Keep pending and completed refund commitments in the capacity check; delivery order of callbacks is not the business state order.

Payment System: Check the design

Test two simultaneous refunds, callback replay, callback reordering and delayed capture observations. Verify per-currency journal conservation and unresolved-operation age.

Payment evidence and reconciliation

Start with the existing complete baseline. The following workshop extends its authority, evidence and recovery contract under a changed requirement. Preserve scoped operation identities and distinguish durable acceptance from completed external work.

Deep dive: authenticated evidence still needs business binding

The baseline already covers merchant-scoped intents, provider operation identity, balanced journals and refund reservations. This workshop follows evidence through callback intake, outcome conflict, local posting, merchant delivery and reconciliation. It is an original processing protocol with declared assumptions, not a universal provider contract.

Give each boundary its own identity

Contract / pseudocode
operation(merchant, operation_id, payment_id, kind, amount_minor, currency,
          provider_account, environment, provider_object, provider_key,
          payload_hash, state, reserved_minor, evidence_revision)
observation(provider_account, environment, event_id, payload_hash,
            operation_id, fact, verification_state)
journal(operation_id, posting_kind, transaction_id)
merchant_event(merchant, operation_id, transition_sequence, outbox_id)
reconciliation(scope, report_id, revision, expected_manifest,
               complete_checkpoint, unresolved_items, discrepancies)

Intent, monetary operation, transport attempt, observation and posting are different. A retry sends the same operation; it does not create another capture/refund. Authenticate merchant status access separately from provider callbacks. A valid callback signature still needs account/environment, object/operation, immutable amount/currency and payment-relationship checks. Test-mode evidence cannot finalize a live operation. Scope inbox identity by the provider/account/environment contract and reject conflicting payloads at one identity.

Preserve verified facts through reordered delivery

Callbacks can precede synchronous responses or replay old pending evidence after success. Commit authenticated intake durably before acknowledging its acceptance, then process under the operation authority. Intake acknowledgment is not a promise that posting or merchant notification has finished. Unknown schemas require visible failure/quarantine rather than a default success state.

Event-ID deduplication is insufficient when distinct event IDs describe the same operation. Posting uniqueness belongs to operation/posting identity too. An older pending or decline observation cannot overwrite a verified capture/refund merely because it arrived last. Use a provider's authoritative object/revision ordering where supported; conflicting terminal evidence without an ordering proof requires investigation and reconciliation, not a local timestamp tie-break.

Keep established monetary facts and unresolved commitments visible. A real refund, reversal or dispute is a referenced new financial fact; do not rewrite the original capture as if it never occurred. Versioned adapters must retain decoding support for accepted evidence during rollout/rollback.

Payment recovery: refund R has a pending reservation; verified success commits journal and outbox; its response is lost; old pending evidence arrives; recovery keeps success and the original merchant event
Outcome, posting and notification intent survive replay as distinct durable facts.
Read the diagram

Refund R keeps a pending reservation → Verified success commits journal and outbox → The successful response is lost → An older pending observation arrives → Keep success and original merchant event

Open original
Payment System: recovery decision
Payment recovery: refund R has a pending reservation; verified success commits journal and outbox; its response is lost; old pending evidence arrives; recovery keeps success and the original merchant event

Outcome, posting and notification intent survive replay as distinct durable facts.

Settle locally under one authority

A 2,500-unit capture with refund R reserving 1,500 leaves 1,000 free refund capacity. Verified R success atomically moves reserved to refunded, posts the balanced journal once and records one merchant transition/outbox intent. Replay cannot subtract its reservation twice. Definitive failure releases once; timeout or inconclusive lookup does not.

Apply the same conservation principle to pending captures against permitted authorization, while respecting the provider's actual expiry/partial-capture rules. Local reservation does not prove remote authorization remains valid. A provider adjustment discovered later needs an explicit discrepancy/adjustment workflow, not an unexplained increase in refundable balance.

A crash after journal commit but before reply returns the existing operation on retry. Journal and merchant outbox must share a local transaction or an explicit recoverable publication protocol. Writing the outbox afterward can lose the event; writing it before a rolled-back posting can falsely report finality. Cross-shard journals require additional coordination beyond a single balanced-sum example.

Merchant deliveries keep stable merchant/operation/transition identity. Delivery retry does not create another refund. The merchant's acknowledgment is separate from operation success and settlement; receiving systems deduplicate their effects under their own contract.

Pin provider-specific retry and evidence horizons

Stripe's idempotent-request documentation distinguishes API v1 saved responses from API v2 retry behavior and documents finite v1 retention. Record the actual version/account/endpoint retry contract instead of assuming every provider retains keys or failures identically. Webhook guidance supplies one provider's authentication and delivery boundaries; application-level posting and business binding remain separate.

Outside a supported retry horizon, query the original object/reports and escalate unresolved outcomes. Recycled keys or another provider can create new work. The second provider cannot deduplicate an uncertain effect accepted by the first. Pause or use an explicitly bounded exposure policy instead of silent failover. Durable operation/inbox/journal evidence must cover the supported replay and reconciliation horizon, which can exceed a provider's retry cache.

Reconcile complete populations, then totals

Declare account/environment, currency, operation types, report period and report revision/cutoff. Paginated or corrected exports require a complete manifest/checkpoint with unresolved rows retained. Receiving page 3 before page 2 is not complete coverage; the maximum timestamp is not a complete checkpoint when records tie, arrive late or change by report revision.

Compare each operation's identity, amount/currency, provider outcome, local posting and settlement relationship, then compare totals. Missing capture X=1,000 and extra capture Y=1,000 can leave totals equal while the populations are wrong. Gross captures, refunds, fees, disputes and net settlements are different populations and timing boundaries. A fee-net settlement report cannot be compared directly to gross capture totals.

Classify internal-only, provider-only, conflicting amount/currency, delayed settlement and incomplete evidence. Corrections use audited operations, preserving the original journal. A corrected report revision receives its own completeness evidence rather than retroactively certifying an incomplete earlier run.

At 200 uncertain operations/s over five minutes, 60,000 cases accumulate. Recovery at 300/s with 200/s new work drains at 100/s, taking at least 600 seconds. Fetching 10,000 report pages at 100/s takes at least 100 seconds before throttling, lookup fanout and comparison. Bound provider, report, synchronous-payment and merchant-delivery quotas separately. Track binding failures, conflicting observations, unresolved reservation age, journal/outbox divergence, complete reconciliation lag and discrepancy classes.

Payment assessment: preserve evidence through recovery

Question: A signed success names the wrong account/environment or amount. Can authenticity alone finalize this operation?

Show answer and explanation

Answer: No. Bind exact account/environment/object/operation/amount/currency and quarantine mismatches before changing financial state.

Question: Pending evidence arrives after a verified refund success. Should its later arrival restore pending state?

Show answer and explanation

Answer: No. Recover committed outcome/journal/outbox identity. Conflicting terminal facts require investigation, not arrival-order overwrite.

Question: Totals match but a report page is missing. Is reconciliation complete?

Show answer and explanation

Answer: No. Establish the complete scoped population and compare operation identities; equal totals can hide offsetting errors.

Score one point for exact evidence/business binding, conflict-aware ordered facts, atomic reservation/journal/outbox settlement, provider and notification identity horizons, and complete population-based reconciliation with finite capacity. Compare Ledger, Outbox and Sagas and Ticketmaster.

Shared foundation: Idempotency and Delivery Semantics

Idempotency and Delivery Semantics: Scope operation identities, couple deduplication to effects and resolve uncertain provider outcomes. Work its failure history before extending this design.

Your study notes