Build a Payment Processing System for Short-Term Campaigns
System DesignModel answerLast updated
Design a scalable payment platform handling donation submissions with async processing, idempotency guarantees, and burst traffic support.
You're building a payment processing system for a short-lived fundraising campaign lasting several days. The platform allows donors to contribute money by entering their information and selecting contribution amounts.
Your system needs to:
- Accept donor submissions containing personal details and payment information
- Process charges through a payment service provider
- Handle traffic spikes that may exceed payment processor capacity
- Prevent duplicate charges even during network failures
- Maintain security and compliance standards for payment data
- Provide confirmation and status tracking to donors
Your task: Design the complete system architecture. Explain when and why you would choose asynchronous payment processing over synchronous. If using async, detail the full workflow including API design, queue infrastructure, worker processes, retry logic, failure handling, and how you ensure exactly-once charging semantics. Address data modeling, security considerations, rate limiting, monitoring, and strategies for handling partial failures.
The interviewer will expect you to discuss tradeoffs, provide concrete schemas and API contracts, and demonstrate understanding of distributed systems challenges in payment processing.
Hints
Hint 1
Consider what happens when request volume exceeds your payment provider's throughput limits
Hint 2
Think about the difference between network timeouts and actual payment failures
Hint 3
Design your idempotency strategy across multiple layers: client-to-API, queue-to-worker, and worker-to-payment-provider
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Payment Processing System Design
1. Requirements and Constraints
Functional scope:
- Donors submit personal information and payment details
- System charges the payment method through a third-party processor
- Donors receive confirmation and can check status
- Financial reporting available for internal teams
Non-functional requirements:
- Zero duplicate charges (strong idempotency)
- No lost successful transactions
- Handle sudden traffic surges (10-100× baseline)
- PCI-DSS compliance for payment data
- Campaign duration is limited (days), favor managed services
Capacity estimates:
- Total expected volume: ~5 million submissions over 3 days
- Steady state: ~20 requests/second
- Peak bursts: ~2,000 requests/second during high-visibility moments
- Payment processor limit: ~500 transactions/second
- Data storage: ~10GB (minimal)
The critical observation: peak ingress (2,000/s) significantly exceeds payment processor capacity (500/s), creating the primary case for asynchronous processing.
2. Synchronous vs Asynchronous Processing
Synchronous approach (charge within HTTP request):
- Pros: Immediate feedback, simpler implementation, no queue infrastructure
- Cons: Request timeouts during slow provider responses, client retries create duplicate charge risk, cannot handle sustained traffic above provider limits
Asynchronous approach (accept request, process later):
- Pros: Queue absorbs traffic spikes, controlled retry logic, better timeout handling, server-controlled idempotency
- Cons: Delayed user feedback, requires state tracking, added complexity with queues and workers
Decision criteria for async:
- Downstream capacity is lower than peak ingress
- External service has high latency or reliability issues
- User doesn't require immediate confirmation
All three apply here, making async the right choice.
Hybrid optimization: Perform client-side card tokenization and basic validation synchronously to catch obvious errors fast. Queue the actual charge for async processing. At low load, optionally perform synchronous authorization, falling back to fully async when queue depth grows.
3. API Design
POST /v1/donations
Headers:
Idempotency-Key: <client-generated-uuid>
Authorization: <optional-session-token>
Body:
{
"donor": {
"name": "Jane Doe",
"email": "[email protected]",
"address": {...}
},
"payment_token": "tok_xyz123", // from payment provider's hosted form
"currency": "USD",
"allocations": [
{"organization_id": "org_1", "amount_cents": 5000},
{"organization_id": "org_2", "amount_cents": 2500}
]
}
Response (202 Accepted):
{
"donation_id": "don_abc123",
"status": "PENDING",
"total_cents": 7500
}
Error responses:
- 409 Conflict: idempotency key reused with different request body
- 429 Too Many Requests: rate limit exceeded
- 400 Bad Request: validation failure
GET /v1/donations/{id}
Response:
{
"donation_id": "don_abc123",
"status": "PENDING|PROCESSING|SUCCEEDED|FAILED",
"total_cents": 7500,
"failure_reason": null
}
POST /v1/webhooks/payment-provider // webhook for charge events
GET /v1/reports/daily?date=YYYY-MM-DD // internal finance endpoint
Server-side validation enforces that allocations sum correctly and never trusts client-supplied totals.
4. Data Schema (PostgreSQL)
CREATE TABLE donors (
id UUID PRIMARY KEY,
email_hash VARCHAR(64) NOT NULL, -- for deduplication checks
email_encrypted BYTEA NOT NULL,
name_encrypted BYTEA NOT NULL,
address_encrypted BYTEA NOT NULL,
created_at TIMESTAMP NOT NULL,
INDEX(email_hash)
);
CREATE TABLE donations (
id UUID PRIMARY KEY,
donor_id UUID NOT NULL REFERENCES donors(id),
idempotency_key VARCHAR(255) UNIQUE NOT NULL,
request_body_hash VARCHAR(64) NOT NULL,
total_cents BIGINT NOT NULL,
currency VARCHAR(3) NOT NULL,
payment_token_encrypted BYTEA NOT NULL,
status VARCHAR(20) NOT NULL, -- PENDING, PROCESSING, SUCCEEDED, FAILED
version INT NOT NULL DEFAULT 1,
provider_charge_id VARCHAR(255),
failure_reason TEXT,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
INDEX(status, created_at)
);
CREATE TABLE allocations (
donation_id UUID NOT NULL REFERENCES donations(id),
organization_id VARCHAR(50) NOT NULL,
amount_cents BIGINT NOT NULL,
PRIMARY KEY(donation_id, organization_id)
);
CREATE TABLE charge_attempts (
id UUID PRIMARY KEY,
donation_id UUID NOT NULL REFERENCES donations(id),
attempt_number INT NOT NULL,
provider_idempotency_key VARCHAR(255) NOT NULL,
requested_at TIMESTAMP NOT NULL,
response_code INT,
provider_charge_id VARCHAR(255),
latency_ms INT,
UNIQUE(donation_id, attempt_number)
);
CREATE TABLE outbox (
id BIGSERIAL PRIMARY KEY,
aggregate_id UUID NOT NULL,
event_type VARCHAR(50) NOT NULL,
payload JSONB NOT NULL,
published_at TIMESTAMP,
INDEX(published_at) -- NULL = unpublished
);
CREATE TABLE financial_ledger (
id BIGSERIAL PRIMARY KEY,
donation_id UUID NOT NULL,
organization_id VARCHAR(50),
entry_type VARCHAR(20) NOT NULL, -- CHARGE, REFUND, CHARGEBACK
amount_cents BIGINT NOT NULL,
created_at TIMESTAMP NOT NULL
);
Key design decisions:
- Money stored as integer cents to avoid floating-point errors
- Allocations validated to sum to total in transaction
- Ledger is append-only; refunds are new entries, not updates
- Sensitive data encrypted at rest
5. System Architecture
┌─────────┐
│ Client │ (tokenizes card client-side)
└────┬────┘
│
▼
┌─────────────────┐
│ API Gateway │ (rate limiting, auth, DDoS protection)
└────┬────────────┘
│
▼
┌─────────────────┐
│ Donation API │ (stateless, auto-scaled)
│ │ • Validates request
│ │ • Single DB transaction:
│ │ - Insert donation + allocations
│ │ - Insert outbox event
└────┬────────────┘
│
▼
┌─────────────────┐
│ Outbox Relay │ (CDC or polling)
└────┬────────────┘
│
▼
┌─────────────────┐
│ Message Queue │ (SQS/Kafka, partitioned by donation_id)
└────┬────────────┘
│
▼
┌─────────────────┐
│ Payment Workers │ (concurrency capped at provider limit)
│ │ • Claim donation (optimistic lock)
│ │ • Call payment provider
│ │ • Update status
└────┬────────────┘
│
▼
┌─────────────────┐
│ Payment Provider│ (Stripe/Adyen/etc)
└─────────────────┘
▲
│ webhooks
│
┌────┴────────────┐
│ Webhook Handler │ (verifies signature, updates status)
└─────────────────┘
Dead Letter Queue → Manual Review Console
Transactional outbox pattern prevents dual-write failures where database commits but queue publish fails (or vice versa). A donation exists if and only if its event will eventually be published.
6. Idempotency Guarantees (Three Layers)
Layer 1: Client to API
- Client generates
Idempotency-Keyonce per checkout session - API enforces
UNIQUEconstraint on key - On duplicate key, compare request body hash:
- Same content → return original response (200/202)
- Different content → reject with 409 Conflict
- UI disables submit button, but server enforcement is the real guarantee
Layer 2: Queue to Worker
- Queue delivers at-least-once, workers must handle duplicates
- Worker claims donation using optimistic locking:
UPDATE donations SET status='PROCESSING', version=version+1 WHERE id=$1 AND status IN ('PENDING','RETRYABLE') AND version=$2 - If update affects zero rows, worker acknowledges message and exits (already processed)
Layer 3: Worker to Payment Provider
- Worker sends provider-specific idempotency key derived from donation ID
- Format:
campaign_don_{donation_id} - Provider returns existing charge on retry instead of creating duplicate
- Critical for timeout handling: timeout means outcome is unknown, not failed
- Mark donation as
UNKNOWN - Retry with same provider key, or query by key
- Never generate new key for unknown-outcome donations
- Mark donation as
State machine:
PENDING → PROCESSING → SUCCEEDED
↓
→ FAILED (hard decline: insufficient funds)
↓
→ RETRYABLE (timeout, 5xx, 429) → back to PENDING
↓
→ NEEDS_ACTION (3DS challenge) → awaiting donor
Transitions are unidirectional. Both worker responses and provider webhooks can trigger transitions.
7. Failure Handling and Resilience
Retry strategy:
- Exponential backoff: 1s, 2s, 4s, 8s, 16s, 32s
- Max 6 attempts over ~1 minute
- After exhaustion → Dead Letter Queue
Dead letter handling:
- Operations dashboard alerts on DLQ depth
- Manual review for genuine declines vs transient failures
- Replay tool for transient failures after provider recovery
Reconciliation:
- Nightly batch job compares internal ledger to provider settlement reports
- Flag discrepancies (missing charges, unreported failures)
- Generate financial reports by organization
Partial failure scenarios:
- Database transaction fails after outbox write: use idempotency on retry
- Provider succeeds but webhook delivery fails: worker polls provider API for final status
- Worker crashes mid-processing: message redelivered, optimistic lock prevents duplicate charge
8. Security and Compliance
PCI-DSS requirements:
- Never store raw card numbers (PAN); use provider's tokenization
- Encrypt payment tokens at rest
- TLS 1.3 for all transmission
- Minimize scope: card data touches only provider's hosted fields
PII protection:
- Encrypt names, emails, addresses using envelope encryption
- Hash email for deduplication without revealing plaintext
- Access controls: only authorized finance roles can export donor data
- Audit log for all data access
Rate limiting:
- Per-IP: 10 requests/minute
- Global: soft limit at 2,000/s, hard limit at 3,000/s with 429 response
- CAPTCHA after 3 failed validation attempts from same session
9. Observability and Monitoring
Key metrics:
- Request rate and queue depth (leading indicators of capacity issues)
- Payment success/failure rates by failure reason
- P50/P95/P99 latency for API and worker processing
- Provider API error rates and latency
- DLQ message count
Alerts:
- Queue depth > 10,000 messages for 5 minutes
- Payment failure rate > 10%
- DLQ depth > 100
- Provider API error rate > 5%
Distributed tracing:
- Trace ID propagated from API through queue to worker to provider
- Spans: request validation, database write, queue publish, worker claim, provider call
10. Scaling Strategy
API layer: Stateless containers, horizontal autoscaling based on CPU/request rate
Database: Managed PostgreSQL with read replicas for reporting queries, connection pooling
Queue: Managed service (SQS/Kafka) with partitioning by donation ID to preserve ordering per donation
Workers: Concurrency capped at 80% of provider limit (400 concurrent) to leave headroom, autoscale based on queue depth
Burst handling: Queue absorbs spikes up to millions of messages; workers drain at sustainable rate
Common Mistakes to Avoid
- Trusting client-provided totals instead of computing server-side
- Not distinguishing timeouts from failures — timeouts require lookup, not retry with new key
- Dual-write bugs — writing to database and queue separately without transactional outbox
- Logging sensitive data like tokens or full card details
- Synchronous design for high-burst scenarios — causes cascading timeouts
- Missing webhook signature verification — allows spoofed payment confirmations
This design balances operational simplicity (managed services, finite campaign duration) with robustness requirements (idempotency, compliance, burst handling) for a payment-critical system.