Loyalty Ledger: Building a Transaction-to-Points Rewards System
System DesignModel answerLast updated
Design a service that converts card transactions to loyalty points, ensuring exactly-once processing, precise arithmetic, and safe redemptions.
You're building a rewards platform that converts customer purchases into loyalty points. Every dollar spent earns 1.5 points. The system must ingest card transaction events (settlements, refunds, reversals), maintain accurate point balances, and allow customers to redeem points for rewards.
Your design should address:
- API contracts for ingesting transactions, querying balances, and processing redemptions
- Precision and rounding to avoid drift when converting fractional points across millions of transactions
- Idempotency and deduplication so replayed or duplicate events never double-credit accounts
- Consistency guarantees appropriate to each operation (earning, redeeming, querying)
- Data model that supports auditability, corrections, and historical analysis
- Fraud and abuse prevention including velocity limits and negative balance detection
- Scaling strategy to handle peak transaction volumes and read traffic
- Observability to detect discrepancies, lag, and system health issues
- Backfill and correction flows for fixing historical data or rate changes
Assume 10 million accounts, 50 million transactions per day (average 600 TPS, peak 5k TPS), and redemptions roughly 100× less frequent than earns.
Walk through your architecture, explain trade-offs between consistency models, and describe how you'd test and roll out the system safely.
Hints
Hint 1
Think of this as a financial ledger problem, not just a multiplication task—immutability and auditability are key
Hint 2
Store points as milli-points (integer × 1000) to eliminate floating-point rounding errors entirely
Hint 3
Partition everything by account_id so transactions for a single account stay ordered and single-shard
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem looks like simple arithmetic but is really about correctness in a distributed ledger. The core challenges are guaranteeing exactly-once credit, preventing overspend during redemption, and maintaining an auditable history. Treat the points system as an append-only ledger with a materialized balance view.
1. Requirements and Scale
Functional scope
- Ingest transaction events: settlements (earn points), refunds (claw back), and reversals
- Convert USD to points at a fixed 1:1.5 ratio
- Provide balance queries and transaction history
- Process redemptions atomically, preventing overdraft
- Support admin corrections and backfills when upstream data changes
Non-functional requirements
- Correctness over latency: money-adjacent systems cannot lose or duplicate credits
- Auditability: every change must be traceable
- Low-latency reads: balance queries under 100ms
- Near real-time earns: points appear within a few seconds of settlement
Scale assumptions
- 10M accounts, 50M transactions/day (~600 TPS average, 5k peak)
- Redemptions 100× rarer than earns
- Daily ledger growth: 50M rows × 200 bytes ≈ 10 GB/day, ~3.6 TB/year
Clarifying questions
- When do points post? On settlement, not authorization (auths can be voided)
- Do refunds reverse points? Yes, and balances can go negative
- Is the rate fixed forever? Version the conversion rule for future flexibility
2. API Design
POST /v1/transactions
Idempotency-Key: <uuid>
Body: { source_txn_id, account_id, amount_cents, currency,
event_type: "SETTLED"|"REFUNDED"|"REVERSED", timestamp }
Response: 202 { entry_id, points_awarded_milli }
GET /v1/accounts/{id}/balance
Response: { available_milli, pending_milli, as_of_entry_id }
GET /v1/accounts/{id}/history?cursor=<id>&limit=50
Response: { entries: [...], next_cursor }
POST /v1/accounts/{id}/redemptions
Idempotency-Key: <uuid>
Body: { points_whole, reward_id }
Response: 201 { redemption_id } | 409 INSUFFICIENT_POINTS
POST /v1/admin/adjustments
Body: { account_id, points_milli, reason, approver_id }
3. Precision: Milli-Points to Avoid Drift
Never use floating-point math. Store currency as integer cents and points as milli-points (points × 1000):
- 1 cent = 0.015 points = 15 milli-points
- Conversion:
points_milli = amount_cents × 15 - Every operation is exact integer arithmetic, eliminating rounding drift
Display and redemption rules:
- Display: floor to whole points (user never sees fractional points they can't spend)
- Redemptions: whole points only (multiples of 1000 milli)
- Refunds: reverse exact milli-points from the original transaction
4. Data Model
ledger_entries (append-only, source of truth)
| Column | Type | Notes |
|---|---|---|
| entry_id | ULID | Time-sortable primary key |
| account_id | UUID | Partition key |
| idempotency_key | VARCHAR | UNIQUE (account_id, idempotency_key) |
| entry_type | ENUM | EARN, CLAWBACK, REDEEM, REDEEM_REVERSAL, ADJUSTMENT |
| points_milli | BIGINT | Signed; negative for debits |
| source_txn_id | VARCHAR | Nullable (null for redemptions) |
| amount_cents | INT | Original transaction amount |
| rule_version | VARCHAR | e.g., "rate_v1_15milli" |
| reverses_entry_id | ULID | For corrections |
| created_at | TIMESTAMP | |
| occurred_at | TIMESTAMP | Business timestamp |
balances (materialized view per account)
| Column | Notes |
|---|---|
| account_id | Primary key |
| available_milli | Current spendable balance |
| pending_milli | Authorizations not yet settled |
| version | Optimistic lock counter |
| last_entry_id | Last processed ledger entry |
transactions_seen
Tracks state machine per source_txn_id (SETTLED → REFUNDED, reject duplicate settles).
redemptions
Status tracking (PENDING, COMPLETED, FAILED) and fulfillment references.
5. Architecture
Card Processor → Kafka (txn-events, partitioned by account_id)
↓
Points Consumer → Postgres (sharded by account_id)
↓ ├─ ledger_entries (insert)
↓ └─ balances (update in same txn)
DLQ ↓
CDC (Debezium)
↓
Kafka (ledger-events)
↓
┌─────┴─────┬─────────────┐
Redis Data Warehouse Fraud ML
(cache) (analytics) (scoring)
API Gateway → Points API (balance reads, redemptions)
Ingest flow:
- Consumer reads event from Kafka
- Computes
points_milli = amount_cents × 15 - Single DB transaction:
- Insert ledger entry with idempotency key
- Update balance:
available = available + points_milli
- Commit Kafka offset only after DB commit
Why partition by account_id:
- Kafka partitioning ensures per-account ordering (refunds can't race ahead of earns)
- Postgres sharding by same key keeps all account writes single-shard (no distributed transactions)
6. Idempotency and Deduplication
Defense in depth:
-
Deterministic idempotency key:
{source_txn_id}:{event_type}- Database UNIQUE constraint prevents duplicate inserts
- Replayed events return the original ledger entry (Kafka at-least-once becomes exactly-once)
-
Transaction state machine: Track each
source_txn_idthrough states- Allowed: SETTLED → REFUNDED, SETTLED → REVERSED
- Reject: second settlement, refund exceeding original amount
-
Award on settlement only: Authorizations appear as non-spendable
pending_milli -
Redemption idempotency: Client supplies UUID; retries return same
redemption_id
7. Consistency Model
Choose per operation based on business requirements:
Redemptions: Strong Consistency
Within the account's shard, execute:
UPDATE balances
SET available_milli = available_milli - :points
WHERE account_id = :id AND available_milli >= :points
Insert REDEEM entry in same transaction. If zero rows updated, return 409. No distributed locks needed.
Fulfillment saga (external reward provider):
- Debit points, mark redemption PENDING
- Call vendor API with idempotency key
- On success: mark COMPLETED
- On failure: write REDEEM_REVERSAL entry
Earning: Asynchronous
Event-driven processing allows seconds of latency. Business accepts eventual consistency for earns.
Balance reads: Eventual Consistency
Serve from Redis cache (5s TTL) or read replicas. Return as_of_entry_id so clients understand freshness. Redemption flow reads from primary.
8. Fraud and Abuse Prevention
- Velocity checks: Alert on >N redemptions/day or abnormally high earns
- Negative balance monitoring: Flag accounts exceeding threshold
- Immutable audit trail: Every entry includes source transaction, timestamp, rule version
- Two-person integrity: Admin adjustments require approver signature
- ML scoring: CDC stream feeds real-time fraud models
9. Scaling Strategy
Horizontal scaling
- Kafka: Partition by account_id hash; add partitions to increase throughput
- Postgres: Shard by account_id (hash or range); each shard is a replica set
- Consumers: Scale with Kafka partitions (each consumer handles multiple partitions)
Hotspot mitigation
- High-volume accounts get dedicated consumer instances
- Separate shard tier for VIP accounts
Read scaling
- Balance queries hit Redis cache → Postgres replicas on miss
- History queries use cursor pagination on replicas
- CDC keeps cache warm
10. Backfill and Corrections
Backfill scenario: Rate changed or missed transactions discovered
- Publish correction events to separate Kafka topic
- Consumer writes ADJUSTMENT entries with updated
rule_version - Include correction reason and approver in metadata
- Adjustments appear in user history with explanation
Daily reconciliation batch:
- Sum ledger entries per account, compare to materialized balance
- Compare source transactions in data warehouse to ledger
- Alert on discrepancies
11. Observability
Key metrics:
- Kafka consumer lag per partition
- Ledger write latency (p50, p99) and throughput
- Balance discrepancy rate (recon job findings)
- Redemption success/failure ratio
- DLQ depth
Structured logging:
- Every ledger entry: entry_id, account_id, points_milli, rule_version
- Idempotency retries (expected) vs. state violations (alert)
Dashboards:
- Real-time earn/redeem rates
- Balance read and redemption latency
- Error rate by operation type
12. Testing and Rollout
Testing strategy:
- Unit: Idempotency key collisions, state machine transitions, arithmetic precision
- Integration: Kafka → DB → cache pipeline with simulated replays
- Load: 10× peak TPS with chaos (kill consumers, inject Kafka lag)
- Reconciliation: Seed known discrepancies, verify detection
Rollout plan:
- Dark launch: Ingest events, write ledger, but don't expose balances
- Shadow mode: Compare ledger balances to legacy system
- Phased migration: 1% → 10% → 50% → 100% of accounts
- Feature flag redemptions separately from earning
Complexity
Write path: O(1) per transaction (single-shard insert + update)
Balance read: O(1) from cache or materialized view
History query: O(page_size) with indexed cursor pagination
Storage: O(transactions) append-only; ~3.6 TB/year at given scale
Common Mistakes
- Using floats for points (accumulates rounding errors)
- Missing idempotency (double-crediting on retries)
- Weak consistency for redemptions (allows overdraft)
- Mutable ledger (lose audit trail)
- Ignoring event ordering (refunds processed before earns)
- No backfill mechanism (can't correct historical data)