Designing a High-Traffic Campaign Donation System
System DesignModel answerLast updated
Build a payment platform for a short-duration global fundraiser with real-time totals, idempotency, fraud prevention, and spike handling.
You need to architect a payment system for a worldwide charitable fundraiser running for exactly 72 hours. The platform must accept contributions from donors globally, process payments through third-party providers, display live aggregate statistics, and maintain strict financial correctness.
Your design should cover:
Core functionality:
- Contribution creation and payment processing flow
- Refund handling
- Live aggregate metrics (total raised, contributor count)
- Public rankings (top teams, top individual fundraisers)
Technical requirements:
- Payment idempotency to prevent duplicate charges
- Fraud detection and prevention
- Traffic spike management (expect sudden surges from media coverage)
- Multi-region deployment for global availability
- Real-time or near-real-time metric updates
- Handling payment provider webhook delays and ordering issues
Deliverables:
- API endpoints specification
- Data storage schema
- System architecture diagram and component descriptions
- Scalability approach with capacity planning
- Trade-off discussions for consistency, availability, and performance
- Failure mode analysis
- Testing and deployment strategy
Make explicit assumptions about traffic patterns, volumes, and business constraints. Explain your reasoning for key architectural decisions.
Hints
Hint 1
Consider how to prevent a donor from being charged multiple times even if they retry or experience network issues
Hint 2
Think about what happens when metrics are read 100x more often than donations are written
Hint 3
Payment webhooks from providers can arrive out of order or be delayed by minutes—how does this affect your state management?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: High-Traffic Campaign Donation System
Requirements Gathering
Functional scope:
- Donors submit one-time contributions with optional team/fundraiser attribution
- Integration with external payment processors (Stripe, PayPal, etc.)
- Support for refund requests
- Public-facing live statistics and ranking boards
- Administrative dashboard showing conversion metrics and geographic distribution
Non-functional targets:
- Campaign duration: 72 hours only
- Availability goal: 99.95%+ for payment flows (downtime = lost revenue)
- Financial guarantee: zero duplicate charges, complete audit trail
- Metrics latency: 2-5 second acceptable staleness
- Traffic pattern: highly spiky (viral social media posts can cause 50x surge)
Scale estimation:
- Assume 10M unique donors, 20M total contributions across 72 hours
- Baseline: ~80 writes/second
- Peak load: 50x baseline = 4,000 contribution writes/second
- Each contribution generates ~3 database operations (create, update on confirmation, ledger entry)
- Peak write load: ~12,000 ops/second
- Metrics reads from landing page traffic: 100k-200k reads/second at peak
- Storage: ~3KB per contribution × 20M = 60GB (manageable; challenge is correctness under load)
API Design
POST /api/v1/contributions
Headers: X-Idempotency-Key: <uuid>
Body: {campaign_id, amount_cents, currency, team_id?, donor: {email, name}}
Response: {contribution_id, status: "pending", payment_client_token}
POST /api/v1/contributions/{id}/complete
Headers: X-Idempotency-Key: <uuid>
Response: {status: "processing"|"succeeded"|"failed"|"action_required"}
POST /api/v1/contributions/{id}/refunds
Headers: X-Idempotency-Key: <uuid>
Body: {amount_cents?, reason}
Response: {refund_id, status}
POST /api/webhooks/{provider_name}
(Provider-to-server, signature verified)
GET /api/v1/campaigns/{id}/stats
Response: {total_amount_usd, contribution_count, timestamp}
GET /api/v1/campaigns/{id}/rankings?type=team|fundraiser&limit=50
Response: {rankings: [{id, name, total_usd, rank}], updated_at}
Data Schema
contributions table:
id(ULID with region prefix),campaign_id,donor_id,team_idamount_cents,currency,usd_amount_cents,exchange_ratestatus(enum),payment_provider,provider_payment_id(unique index)optimistic_lock_version, created/updated timestamps
idempotency_records table:
- Primary key:
(client_identifier, idempotency_key) request_signature,cached_response,processing_state,expires_at
financial_ledger table (append-only):
id,contribution_id,entry_type(capture/refund/dispute)amount_cents,usd_amount_cents,provider_reference- Created timestamp (immutable)
provider_webhooks table:
provider_event_id(unique),payload_json,received_at,processed_at
event_outbox table:
id,aggregate_id,event_type,payload,published_at
Partitioning strategy: Shard by hash(contribution_id) not by campaign_id. Campaign-based sharding creates a hot partition. Use distributed SQL (CockroachDB, Spanner) or regional relational databases with read replicas.
Architecture Overview
Client → CDN/WAF (bot protection, rate limits)
→ Geographic load balancer
→ Regional API clusters (auto-scaled)
├─> Fraud scoring service (synchronous, <50ms)
├─> Payment gateway orchestrator
│ └─> Provider adapters (circuit breakers)
└─> Regional database (contributions, ledger, idempotency)
Event pipeline:
Outbox polling → Event stream (Kafka)
├─> Stream processor (Flink) → Aggregation cache (Redis)
├─> Analytics warehouse sink
└─> Notification service (emails)
Webhook ingestion:
Provider webhook → Queue (SQS/RabbitMQ) → Async processors
Background jobs:
Reconciliation cron: stale payments check, provider report comparison
Multi-region approach: Active-active deployment. Each contribution is "homed" in its creation region (encoded in ID). Routing ensures subsequent operations (confirmation, webhooks) hit the home region. No cross-region write coordination needed since contributions are independent. Global stats aggregate per-region metrics.
Critical Design Deep-Dives
Idempotency & Duplicate Prevention
Implementation:
- Client generates idempotency key on form load (not submit), survives retries
- Server attempts atomic insert of
(client_id, key, "in_progress", request_hash) - If key exists:
- Same payload hash: return cached response (if completed) or 409 retry (if in-progress)
- Different payload: reject with 422 (client error)
- Pass contribution ID as idempotency key to payment provider
- Separate soft-dedup: flag if same donor+amount+campaign within 60s (different keys) with UI confirmation
Why this works: Database uniqueness constraint prevents races. Provider-level idempotency prevents double-charges even after timeouts.
Real-Time Metrics & Rankings
Challenge: 200k reads/sec would overwhelm origin; can't query database directly.
Solution:
- Stream processor (Flink) consumes contribution events keyed by campaign/team
- Checkpoint-based exactly-once processing or idempotent writes (by ledger entry ID)
- Write to Redis sharded counters (
stats:campaign:{id}:shard:{0-63}) to avoid hot keys - Write to sorted sets for rankings (team/fundraiser leaderboards)
- API reads from Redis, cached at CDN edge with 1-2 second TTL
- Result: 200k reads/sec becomes ~1-2 origin requests/sec
Reconciliation: Hourly batch job recomputes totals from ledger (source of truth) and corrects drift.
Fraud & Abuse Prevention
Card testing (attackers trying stolen cards with small donations) is primary risk.
Defenses:
- Velocity limits: track attempts per card fingerprint, IP, device ID, email
- Minimum donation thresholds during attacks
- Payment provider risk scores (Stripe Radar, etc.)
- Step-up authentication (3D Secure) or CAPTCHA for suspicious patterns
- Block prepaid/gift card BINs during active attacks
- Async ML review for pattern detection with automated refunds
Rate Limiting & Overload Protection
Edge layer: Token bucket per IP and authenticated user. Global admission control with 503 + Retry-After header before database saturation.
Provider limits: Bulkhead pattern (concurrency limit per provider) with circuit breakers. Pre-negotiate higher limits or distribute across multiple merchant accounts.
Graceful degradation priority:
- Shed analytics consumers (Kafka lag is fine)
- Delay non-critical notifications
- Serve slightly stale leaderboards
- Last resort: shed contribution creation (with clear user messaging)
Webhook Handling
Challenges: Out-of-order delivery, duplicates, delays (minutes to hours).
Solution:
- Verify signature immediately, store in
provider_webhooks(unique on event ID), ack 200 fast - Process asynchronously from queue
- Use optimistic locking (version column) with state machine that only moves forward:
pending → processing → succeeded/failed succeeded → refund_processing → refunded - Backward transitions ignored (late webhook for already-completed payment is no-op)
- Reconciliation job: query provider API for payments stuck in "processing" >10 minutes
- Daily batch: compare provider settlement reports with ledger
Consistency Trade-offs
Strong consistency (financial data):
- Contributions, ledger entries, idempotency records use ACID transactions
- No eventual consistency for money movement
- All financial operations append to ledger in same transaction as state change
Eventual consistency (acceptable):
- Public statistics (2-5 second lag acceptable)
- Leaderboard rankings
- Analytics aggregates
Why: Users understand live metrics may lag slightly. Zero tolerance for incorrect charges or lost money.
Failure Scenarios
Payment provider outage:
- Circuit breaker opens after threshold failures
- Return user-friendly error with retry guidance
- Queue for later reconciliation
- Consider multi-provider setup with automatic failover
Database unavailability:
- Read replicas for GET endpoints
- Reject writes with 503 (better than accepting and losing data)
- Regional failover with data replication
Duplicate webhook processing:
- Idempotent handling via unique event ID and CAS updates
- No financial impact due to state machine design
Missing webhooks:
- Background reconciliation queries provider API for stale pending payments
- Daily settlement report comparison catches gaps
Capacity Planning
Compute: Auto-scale API servers targeting 50-60% CPU. Pre-warm capacity before expected spikes (celebrity announcements).
Database: Provision for 15k writes/sec with headroom. Use connection pooling (PgBouncer). Read replicas for analytics queries.
Cache: Redis cluster sized for ~100GB (rankings, counters) with replication.
Event stream: Kafka with 7-day retention, partitioned by campaign ID.
Testing & Rollout Strategy
Pre-launch:
- Load testing at 2x expected peak with realistic spike patterns
- Chaos engineering: kill payment provider mid-transaction, inject webhook delays
- Financial reconciliation dry-run with test providers
- Idempotency testing: automated duplicate request generation
- Multi-region failover drills
Launch:
- Soft launch with small initial audience (1-5% traffic)
- Monitor key metrics: payment success rate, latency p99, ledger vs stats drift
- Gradual rollout with automated rollback triggers
- War room staffing for campaign duration
Monitoring:
- Payment funnel metrics (attempt → success rate)
- Financial reconciliation dashboards (ledger vs provider vs displayed totals)
- Error rate by provider, region, failure type
- Queue depths and consumer lag
- SLO alerts: payment availability, confirmation latency
This design prioritizes financial correctness and availability under extreme load while accepting slightly stale public metrics—the right trade-offs for a time-bound fundraising campaign.