Fundraising Payments Backend: No Lost or Double Gifts
System DesignModel answerLast updated
Design a charity fundraising service that takes one-time and recurring gifts through a third-party payment processor, with exact amounts, no duplicate charges, and survival of traffic surges.
Problem
Design the backend for a fundraising site where people find charity campaigns and give money to them. Card processing is done by a third-party payment provider (you never touch the card network), but your platform must still make sure that no gift is lost, charged twice, or recorded with the wrong amount.
Assume:
- Millions of registered users.
- Traffic can jump by one to two orders of magnitude during disasters or high-profile fundraising events.
- Money movement and the ledger must be correct and auditable. Notifications and analytics may lag.
What to cover
- Functional and non-functional requirements (correctness, durability, availability, auditability, burst handling), with rough capacity numbers.
- The main APIs for donors, nonprofits and internal admins.
- A data model for campaigns, donations, ledger, recurring gifts and payouts, with money stored as integer minor units (cents).
- A high-level architecture and its components.
- The end-to-end payment flow, including how the provider is called.
- How you guarantee idempotency: double clicks, client and server retries, and a crash that happens after the provider charged the card but before your database was updated.
- Failure handling: provider timeouts, duplicate or out-of-order webhooks, queue or notification outages, and reconciliation.
- One-time and recurring gifts, receipts, donor history, nonprofit payouts and reporting.
- Admin workflows to create, approve, pause and audit campaigns.
- Which data needs strong consistency and which can be eventually consistent.
- Scaling for read-heavy campaign browsing and write-heavy donation surges.
- Security and compliance: no raw card data, tokenization, webhook authentication, RBAC, audit logs, fraud controls.
- Observability and the main trade-offs you made.
Hints
Hint 1
Write the gift record to your own database before you call the provider, and pass a stable idempotency key to the provider. Then a charge can never exist without a local record.
Hint 2
Treat the provider as the source of truth for whether money moved. Model the gift as a forward-only state machine and heal stuck rows with both webhooks and a periodic sweeper that polls the provider.
Hint 3
Separate the money path (strongly consistent, append-only double-entry ledger, transactional outbox) from the display path (cached totals, search, notifications, analytics), which can be eventually consistent.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
Browsing campaigns is an ordinary read-heavy problem. The real challenge is money correctness under failure. My answer rests on three ideas: a forward-only state machine for each gift, idempotency at every hop, and reconciliation against the provider, which is the authority on whether a charge happened.
1. Requirements and scale
Functional: browse and search campaigns; give once or on a schedule; view history and receipts; nonprofits see reports and receive payouts; admins create, approve, pause and audit campaigns.
Non-functional:
- Correctness: no lost, duplicate or wrong-amount gifts; every provider charge maps to exactly one ledger transaction.
- Durability: once we acknowledge a gift, it survives any single failure.
- Availability: about 99.95% for the donate path; browsing may fall back to cached data.
- Auditability: append-only records of money movement and admin actions.
- Bursts: tolerate roughly 100x normal load.
Numbers: ~1M gifts/day is about 12 writes/s on average; a 100x surge is 1-2K writes/s, with maybe 50K reads/s on a few hot campaign pages. At ~1 KB per row, that is about 400 GB/year, which fits comfortably in a sharded relational database.
2. APIs
GET /campaigns?query=&category=&cursor=
GET /campaigns/{id}
POST /donations Idempotency-Key: <uuid>
{campaign_id, amount_cents, currency, payment_token, recurring?: {interval}}
GET /donations/{id} GET /me/donations?cursor= GET /donations/{id}/receipt
DELETE /subscriptions/{id}
POST /webhooks/payments (provider -> us, signed)
GET /orgs/{id}/reports?from=&to= GET /orgs/{id}/payouts
POST /admin/campaigns POST /admin/campaigns/{id}:approve|pause|resume
GET /admin/audit?entity=
The client creates the idempotency key once per checkout attempt and reuses it on every retry. Card details go from the browser straight to the provider's SDK; our servers only see a token.
3. Data model
All money is BIGINT minor units plus a currency code.
- campaigns: id, org_id, title, goal_cents, status (draft, pending, active, paused, closed), version.
- donations: id, user_id, campaign_id, amount_cents, currency, status,
UNIQUE(user_id, idempotency_key), request_hash,UNIQUE provider_payment_id, subscription_id, timestamps. - provider_events: provider_event_id (primary key), donation_id, type, payload, received_at. This is the webhook dedup table.
- ledger_entries: txn_id, account, signed amount_cents, donation_id or payout_id, created_at. Append-only, double-entry, each txn sums to zero. Accounts include provider_clearing, org_payable:{org}, platform_fees and refunds.
- subscriptions: id, user_id, campaign_id, amount_cents, interval, provider_subscription_id, status, next_charge_at.
- payouts: id, org_id, amount_cents, period, status,
UNIQUE provider_transfer_id. - outbox: id, aggregate_id, event_type, payload, published_at.
- audit_log: actor, role, action, entity, before, after, timestamp; append-only, ideally hash-chained.
Gift status moves only forward: CREATED -> PENDING -> SUCCEEDED | FAILED -> REFUNDED. Enforce it with guarded updates such as UPDATE donations SET status='SUCCEEDED' WHERE id=? AND status IN ('CREATED','PENDING').
4. Architecture
- CDN and API gateway (auth, rate limiting, WAF).
- Campaign service on Postgres with a Redis cache and a search index.
- Donation service on a payments database sharded by user_id, with an outbox table, plus a payment adapter wrapping the provider.
- Webhook ingestor that verifies and enqueues events to a durable log (Kafka).
- Ledger service with its own append-only store.
- Background workers: recurring scheduler, payout service, reconciliation job, sweeper.
- Async consumers: receipts and notifications, analytics, fraud scoring, campaign totals aggregator.
5. Payment flow
- The client tokenizes the card with the provider SDK and calls
POST /donationswith an idempotency key. - In one DB transaction, the service validates that the campaign is
activeand inserts the gift asCREATED. The unique key makes this the dedup point. - It calls the provider to create a payment, using the gift id as the provider idempotency key and storing the gift id in the provider metadata. It then records
provider_payment_idand moves toPENDING. - If extra authentication (e.g. 3-D Secure) is needed, the client finishes it with the returned client secret.
- The final result arrives by webhook (or a synchronous response handled by the same code). In one transaction we mark the gift
SUCCEEDED, insert the balanced ledger entries, and write an outbox row. - An outbox relay publishes to Kafka; idempotent consumers send receipts, bump totals, and feed analytics and fraud.
6. Correctness and idempotency
- Double click or client retry: the same key hits the unique constraint, so we return the stored response. We also compare a hash of the request body, and reject a reused key carrying a different amount.
- Server retry to the provider: the same gift id as provider key means the provider will not charge twice.
- Crash after charge, before our update: the row already exists because we wrote it before calling out. Two independent paths repair it: the webhook finalizes it, or a sweeper polls the provider for
PENDINGrows older than a few minutes (by payment id or metadata) and applies the authoritative state. - Wrong amount: only integer cents; the server validates bounds, and on success we assert the provider's amount and currency equal ours. A mismatch pages a human and blocks ledger posting.
- DB and queue dual write: the transactional outbox gives at-least-once publishing; consumers dedupe by event id.
7. Failure handling
- Provider timeout: the outcome is unknown, so never mark it failed. Keep
PENDING, tell the user "processing", and let webhook or sweeper decide. Retry with exponential backoff and jitter using the same key; a circuit breaker fails fast under a sustained outage. - Duplicate webhooks: verify the signature, then insert into
provider_events; if the primary key already exists, acknowledge and stop. - Out-of-order webhooks: guarded transitions make stale events no-ops (e.g. a late "pending" cannot overwrite "succeeded"). When in doubt, fetch the current state from the provider.
- Queue or notification outage: the outbox keeps rows until published; receipts are retried and can be regenerated. None of this blocks payment.
- Reconciliation: a daily job compares the provider's settlement report with our donations and ledger. It flags charges with no gift, gifts with no charge, and amount mismatches. Ledger sums per txn must be zero.
8. Recurring gifts, receipts, payouts, admin
- Recurring: prefer provider-managed subscriptions; each renewal arrives as a webhook and creates a new gift row keyed by the provider invoice id, so renewals are idempotent. Failed renewals follow a retry schedule (dunning) before cancelling.
- Receipts and history: generated asynchronously from
SUCCEEDEDevents, stored as documents, and served from the donor's shard. - Payouts: a scheduled job sums
org_payablefor settled gifts net of fees and refunds, creates a payout row, and calls the provider transfer API with the payout id as idempotency key. Reports read from a warehouse or read replica. - Admins: campaigns have a status workflow; approve/pause are role-gated, versioned (optimistic locking), and written to the audit log. Pausing must block new gifts at step 2 of the flow.
9. Consistency model
Strong: gift state, ledger, payouts, and campaign status checks on the write path (single-shard ACID transactions). Eventual: displayed raised totals, search index, receipts, analytics, notifications. Totals shown on pages may lag seconds; the ledger is the truth.
10. Scaling
- Reads: CDN and Redis for campaign pages, short TTLs with request coalescing, pre-aggregated totals (counter increments from the stream, not
SUMper request), and a search index. - Writes: shard payments by user_id; the hot-campaign problem is avoided because the write path never updates a shared campaign row, only appends rows and publishes events. Put a queue or admission control in front of the provider adapter and rate-limit per provider quota; shed load gracefully with a "waiting room" if needed.
- Pre-scale and load-test before known events.
11. Security and compliance
Tokenization keeps us out of most PCI scope; no card numbers in logs. Verify webhook signatures and timestamps (replay protection). RBAC with least privilege for admins and nonprofits, short-lived credentials, immutable audit logs. Fraud: velocity limits, card-testing detection, risk scoring that can hold or review a gift. Encrypt PII at rest and honor deletion requests without breaking ledger integrity (pseudonymize).
12. Observability and trade-offs
Track: payment success rate, p99 latency, number and age of PENDING gifts, webhook lag, outbox backlog, reconciliation mismatches (alert on any), provider error rates. Use trace ids that include gift id.
Trade-offs: synchronous confirmation is simpler but less robust than webhook-plus-sweeper; a second provider improves availability but complicates reconciliation; cached totals are cheap but briefly stale; sharding scales writes but makes cross-user reports a warehouse job.
Common mistakes
- Calling the provider before persisting anything.
- Marking a gift failed on timeout.
- Using floats for money or mutating ledger rows instead of appending reversals.
- Trusting webhook order or skipping signature checks.
- Updating one hot campaign row on every gift.