githubEdit

Payment System

Difficulty: Hard Topics: ACID Transactions, Double-Entry Bookkeeping, Idempotency, Distributed Transactions Time: 75 minutes Companies: Stripe, PayPal, Square, Adyen

Problem Statement

Design a payment processing system that:

  • Handles credit card payments

  • Ensures no double-charging

  • Maintains accurate account balances

  • Supports refunds and chargebacks

  • Provides transaction history

  • Integrates with external payment gateways (Visa, MasterCard)

Critical Requirements

Functional

  • Process payments (charge customer, credit merchant)

  • Refunds and partial refunds

  • Transaction history and reconciliation

  • Fraud detection (basic)

Non-Functional

  • Consistency: ACID guarantees (no lost money!)

  • Idempotency: Retry-safe (no double charges)

  • Availability: 99.99% uptime

  • Latency: P99 < 500ms for payment

  • Compliance: PCI-DSS (never store raw card numbers)

Scale Estimation

Core Concepts

1. Double-Entry Bookkeeping

Every transaction has TWO entries: Debit and Credit (sum to zero)

Why?

  • Ensures consistency (money never created/destroyed)

  • Auditable (every cent accounted for)

  • Reconciliation (sum of all entries = 0)

2. Idempotency

Problem: Network timeout, retried request

Implementation:

3. State Machine

Database Schema

Architecture

API Design

Charge Payment

Refund

Get Transaction History

Payment Flow (Step-by-Step)

Key: Everything in ONE database transaction (ACID guarantees)

Handling Distributed Transactions

Challenge: Payment gateway call + DB update not atomic

Problem:

Solution 1: Idempotency + Retry

Solution 2: Saga Pattern

Solution 3: 2-Phase Commit (Avoid if possible)

Reconciliation

Daily Reconciliation:

Gateway Reconciliation:

Scaling

Database Sharding

Read Replicas

Security & Compliance

PCI-DSS Compliance

Fraud Detection (Basic)

Failure Scenarios

Gateway Timeout

Database Failure

Monitoring

Interview Tips

Q: "How do you ensure no double charging?"

  • A: "Idempotency keys stored before processing. Retry uses same key, we detect and return cached response."

Q: "What if payment gateway succeeds but DB update fails?"

  • A: "Store idempotency key BEFORE gateway call. On retry, check key → don't re-charge. Issue refund if needed (Saga pattern)."

Q: "How do you maintain data consistency across shards?"

  • A: "For same-shard: ACID transaction. Cross-shard: 2PC (slow) OR eventual consistency with compensation (refund on failure)."

Q: "Stripe vs building in-house?"

  • Stripe: Faster, PCI-compliant, expensive (2.9% + 30¢)

  • In-house: Cheaper at scale, PCI-DSS burden, complex

Last updated