Backend Architecture for a Live Fundraising Platform
System DesignModel answerLast updated
Design a scalable donation system handling 5k writes/sec with payment idempotency, real-time aggregation, and strict financial consistency.
Context
You're architecting the server-side infrastructure for a fundraising platform that supports charitable organizations and content creators running live donation events. The system must handle sudden spikes in donation volume, integrate safely with third-party payment processors, ensure donors are never charged twice, and display live progress updates to thousands of viewers.
Core Requirements
Must Support
- Fundraiser Creation: Organizations launch fundraising drives with target amounts and deadlines. Supporters can browse active drives.
- Payment Processing: Accept donations of any amount via credit card or saved payment methods. Send automated tax receipts by email after successful payment.
- Live Updates: Show a running total and recent supporter list on each fundraiser page, updating within 1–2 seconds of payment confirmation.
- Financial Records: Maintain an unchangeable audit trail of all payments, refunds, chargebacks, and transfers.
Quality Attributes
- Payment Reliability: Prevent duplicate charges even when users retry, connections drop, or webhooks arrive out of order.
- Uptime: Maintain 99.99% availability during peak live events.
- Consistency Trade-offs: Financial ledgers require strict correctness; live counters can tolerate brief delays up to 2 seconds.
- Security & Compliance: Meet PCI-DSS requirements (no storing raw card numbers), detect fraudulent patterns, encrypt sensitive data.
Traffic Profile
- Active Fundraisers: Around 10,000 running concurrently.
- Burst Load: A single popular live event can generate 5,000 donations per second.
- Viewer Concurrency: Up to 100,000 people watching progress on a single fundraiser simultaneously.
What You Should Address
- API Design: Describe the key endpoints for submitting donations, receiving payment provider callbacks, and retrieving fundraiser statistics.
- Database Schema: Outline tables for fundraisers, supporters, payments, and immutable financial records.
- Payment Flow & Idempotency: Walk through the complete lifecycle of a donation from submission to confirmation, explaining how you guarantee exactly-once charging despite retries and network failures.
- Real-Time Aggregation: Explain how you update fundraiser totals and broadcast changes to many viewers without database lock contention.
- Resilience: Discuss how you handle payment gateway timeouts, delayed or duplicate webhooks, and system recovery.
Hints
Hint 1
Separate the money path (strict consistency) from the display path (eventual consistency with short lag)
Hint 2
Use idempotency keys generated client-side and stored server-side with unique constraints to prevent duplicate charges
Hint 3
Aggregate donation totals asynchronously using a message queue partitioned by fundraiser, avoiding hot-row updates
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Backend Architecture for a Live Fundraising Platform
A strong solution to this problem hinges on two architectural decisions: keeping the payment path strictly correct and idempotent, while making the aggregation and display path fast and eventually consistent. Mixing these concerns—such as updating fundraiser totals inside the payment transaction—leads to severe performance bottlenecks.
1. Capacity Planning and Constraints
Start by translating requirements into concrete numbers:
- Write throughput: 5,000 donations/second on one fundraiser. With double-entry bookkeeping, this means inserting roughly 10,000 ledger rows per second. A single database row updated 5,000 times/second would serialize on row-level locks—this is the core contention problem to avoid.
- Viewer broadcast: Sending every donation to all 100,000 viewers would require 5k × 100k = 500 million messages/second, which is infeasible. Instead, send aggregated snapshots every 500ms: 100k viewers × 2 updates/sec = 200k messages/sec, distributed across 10–20 WebSocket servers.
- Consistency requirements: Totals can lag by up to 2 seconds; financial ledgers must be strictly consistent. This guides caching and transaction boundaries.
- PCI compliance: Tokenize card data client-side using hosted forms (Stripe Elements, Adyen Components), so servers only handle opaque tokens.
2. API Contracts
POST /api/v1/fundraisers/{id}/donate
Headers: Idempotency-Key: <client-generated-uuid>, Authorization: Bearer <token>
Body: { amount_cents: 2500, currency: "USD",
payment_token: "tok_...", display_name: "...",
is_anonymous: false, message: "..." }
Response: 201 { donation_id, status: "pending"|"succeeded"|"requires_action",
client_secret?: "..." }
409 if key already processing
422 if key reused with different payload
POST /api/v1/webhooks/payment-gateway
(Signature verified, always returns 200 after persisting event)
GET /api/v1/fundraisers/{id}/summary
Response: { total_cents, donor_count, goal_cents,
recent_donations: [...], updated_at }
WebSocket /api/v1/fundraisers/{id}/live
Pushes summary snapshots every ~500ms
The client generates a unique idempotency key once per donation attempt and reuses it on every retry, covering double-clicks, page refreshes, and network interruptions.
3. Database Schema
All monetary values stored as integers (cents, minor units).
Core Tables:
fundraisers(id, org_id, goal_cents, currency, start_time, end_time, state)supporters(id, email, external_customer_id)— references to payment gateway's customer objects onlydonations(id PK, fundraiser_id, supporter_id, amount_cents, currency, idempotency_key, request_fingerprint, state, gateway_charge_id UNIQUE, created_at, updated_at)withUNIQUE(supporter_id, idempotency_key)ledger(id, transaction_id, account, direction, amount_cents, currency, donation_id, entry_type, recorded_at)— append-only with no UPDATE/DELETE permissionswebhook_log(gateway_event_id PK, payload_json, received_at, processed_at)event_outbox(id, topic, partition_key, payload, created_at, published_at)fundraiser_stats(fundraiser_id PK, total_cents, donor_count, last_processed_offset)
Partition donations and ledger by time or shard by fundraiser_id. Insert rates of 10k rows/sec are achievable with properly indexed, sharded PostgreSQL.
4. Payment Flow with Idempotency Guarantees
Step 1 — Fast deduplication:
Check Redis with SET NX lock:supporter:{id}:key:{key} EX 30. If already held, return 409 immediately. This is an optimization to reduce database load.
Step 2 — Durable deduplication:
Insert a donations row with state = 'pending'. The UNIQUE(supporter_id, idempotency_key) constraint provides the actual guarantee. On conflict, fetch and return the existing donation's current state. If the stored request_fingerprint differs from the new request, return 422 (key reused with different data).
Step 3 — Fraud checks:
Before calling the gateway, run:
- Velocity checks (per user, card fingerprint, IP address)
- Gateway risk scoring
- Rate limits on micro-donations that probe for valid card numbers
Step 4 — Call payment gateway:
Make the charge API call with Idempotency-Key = donation_id. If this call is retried, the gateway returns the original charge instead of creating a duplicate.
Step 5 — Record immediate response:
Update donation state to succeeded, requires_action (3D Secure flow), failed, or unknown (timeout). Commit immediately.
Step 6 — Asynchronous webhook confirmation:
- Verify cryptographic signature
- Insert into
webhook_log, deduplicating ongateway_event_id - Return 200 immediately
- Background worker processes the event
Step 7 — Apply state transition atomically:
In a single database transaction:
- Update donation state following a monotonic state machine:
pending → requires_action → succeeded/failed → refunded/chargebackked. Ignore transitions that would move backwards. - Insert ledger entries (debit receivable, credit fundraiser liability, record processing fee)
- Insert into
event_outboxwithtopic = donation.succeeded, partition_key = fundraiser_id
Step 8 — Event publishing:
An outbox processor (polling or CDC via Debezium) publishes events to Kafka. Consumers handle:
- Aggregation updates
- Live feed updates
- Receipt email generation (deduplicated by donation_id)
- Fraud analysis and analytics pipelines
Handling failures:
- Gateway timeout: Never generate a new idempotency key. Mark donation
unknownand retry with the same key, or query gateway by idempotency key. A scheduled job reconciles donations stuck inpending/unknownafter 5 minutes. - Duplicate webhooks: Inbox deduplication handles this.
- Out-of-order webhooks: The monotonic state machine ignores invalid transitions. Alternatively, treat webhooks as hints and fetch authoritative state from the gateway API.
5. Real-Time Aggregation Without Lock Contention
Architecture:
- Kafka topics partitioned by
fundraiser_id. Each partition is consumed by exactly one aggregator instance, providing single-writer semantics without distributed locks. - Aggregator accumulates donation deltas in memory and flushes every 200–500ms.
Flush operations:
- Redis: Execute
HINCRBY fundraiser:{id} total_cents <delta>andLPUSH/LTRIMto maintain a capped list of recent donors (~50 entries). - PostgreSQL: Every 5–10 seconds,
UPDATE fundraiser_stats SET total_cents = total_cents + <accumulated_delta>, last_processed_offset = <offset> WHERE last_processed_offset < <offset>. Storing the Kafka offset in the same transaction makes this idempotent during replays.
Broadcasting: On each flush, the aggregator publishes a snapshot to a Redis pub/sub channel for that fundraiser. WebSocket gateway nodes subscribe only to channels for fundraisers their connected clients are watching, then fan out locally.
Read path:
GET /summary reads from Redis, served behind a CDN with 1-second TTL. This also serves as the polling fallback for clients without WebSocket support.
Recovery:
If Redis is lost, rebuild from fundraiser_stats and ledger. If fundraiser_stats drifts, recalculate from SUM(ledger).
End-to-end latency: Webhook delay + Kafka propagation + 500ms flush + push ≈ 1–1.5 seconds.
6. Availability and Resilience
- Database: Multi-AZ deployment with synchronous replication; automated failover.
- Kafka: Replication factor 3,
acks=allfor financial events. - Application tier: Stateless API and WebSocket servers behind autoscaling groups.
- Pre-scaling: Provision extra capacity before scheduled live events based on expected traffic.
- Degradation: If aggregation lags, continue accepting donations (the money path stays operational). Display a "totals updating" message if lag exceeds 5 seconds.
7. Key Trade-offs
| Decision | Benefit | Cost |
|---|---|---|
| Eventual consistency for totals | Eliminates lock contention, enables horizontal scaling | Brief display lag (acceptable per requirements) |
| Asynchronous webhook processing | Fast 200 responses prevent gateway retries | Requires outbox pattern and background workers |
| Client-generated idempotency keys | Works across network partitions and client crashes | Clients must generate and persist keys correctly |
| Kafka partitioning by fundraiser | Single-writer aggregation, simple and correct | Hot fundraisers concentrated on one consumer (mitigate with over-provisioning) |
| Append-only ledger | Immutable audit trail, no update contention | Storage growth (mitigate with time-based partitioning and archival) |
Common Mistakes to Avoid
- Updating fundraiser totals synchronously in the payment transaction: Creates severe lock contention at high throughput.
- Server-generated idempotency keys: Fails when the client retries hit a different server or after server restart.
- Ignoring webhook replay: Duplicate processing causes double-counting and incorrect totals.
- Broadcasting every donation individually: Generates unsustainable message volume at scale.
- Skipping fraud checks: Donation platforms are targets for card testing and money laundering.
Complexity: The payment path is O(1) per donation. Aggregation is O(1) per flush interval. Broadcast is O(viewers) but batched, making it O(viewers / batch_size) per donation.