Build a Loyalty Points Engine with an Immutable Ledger
System DesignModel answerLast updated
Design a service that turns settled payments into loyalty points using versioned earning rules, an append-only ledger, safe redemptions, and daily reconciliation.
Context
A payments and rewards platform lets members earn loyalty points on card spend and on rent payments. Earning depends on rules that change over time, for example a higher multiplier for dining, a lower one for rent, a temporary boost during a promotional window, and limits on how many points a category can yield per period.
You are asked to design the points service that receives payment events, decides how many points each one is worth, records the result, and lets members spend those points on travel, rent credits, or partner transfers.
Because points have monetary value, every credit and debit must be explainable after the fact, safe against repeated deliveries, and never lost.
Requirements
Functional
- Accept settled-payment events and evaluate them against configurable, versioned earning rules.
- Store earnings and spends in an append-only ledger that records which rule version, multiplier, and cap produced each amount.
- Let a member read their spendable balance and redeem points, never allowing the balance to go below zero.
- Run a daily reconciliation that finds and repairs differences between source payments and ledger credits.
Non-functional
- Upstream systems may redeliver the same event; duplicates must never produce extra points.
- Balance changes must be strongly consistent so the same points cannot be spent twice.
- Publishing a new rule version must never change past credits, and re-processing an event must give the same answer.
Scale
- 5 million active members.
- 10 million transactions per day (about 120 TPS average, 1,500 TPS on promotion peaks).
- Balance read p95 under 50 ms; an event should be reflected in the ledger within 5 seconds of arrival.
- Roughly 15-20 million ledger rows per day, kept for several years for compliance.
What to deliver
- The main APIs (event ingestion, balance, redemption).
- A data model separating rule definitions, ledger records, and balances.
- A high-level architecture covering ingestion, rule evaluation, and reconciliation.
- A discussion of relational vs. non-relational storage for the ledger, and where caching fits.
Hints
Hint 1
Start with the numbers: about 3,000 inserts per second at peak is modest for a partitioned relational store, so the difficult parts are correctness and idempotency rather than raw throughput.
Hint 2
Make duplicates harmless at the database level with a unique key on (source transaction id, event type), and update the balance in the same transaction as the ledger rows.
Hint 3
Never evaluate rules using the current clock. Select the rule version by the event's own settlement time and store a resolved explanation with each ledger entry, so replays are deterministic.
Hint 4
Treat the cache as a read accelerator only. Spend decisions should run against the authoritative balance row with a lock or a version check.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify the contract
- Only settled payments earn points; authorizations do not.
- Refunds and chargebacks produce reversals. These can push a balance negative, so define a policy (allow a negative balance and block redemptions until it recovers, or claw back from future earnings).
- Rules support multipliers, per-category or per-period caps, promo windows, and member tiers.
2. Capacity estimate
- Ingest: ~1,500 TPS peak, around 2 ledger rows per earn, so ~3,000 inserts/s at peak.
- Ledger: ~20M rows/day at ~250 B including indexes is ~5 GB/day, ~2 TB/year, roughly 15 TB over seven years.
- Balance reads: assume 10 per user per day, so ~600 QPS average and ~5k QPS peak.
- Redemptions: tens per second, but the most correctness-sensitive path.
Conclusion: a relational store sharded by user_id handles this comfortably. Effort should go into idempotency, consistency, and data lifecycle.
3. APIs
POST /internal/v1/transactions/eventsreturns 202. The body carriesevent_id,source_transaction_id,event_type(SETTLED, REFUNDED, CHARGEBACK),user_id, amount, currency, merchant category, andsettled_at.GET /v1/users/{id}/points/balancereturns available, pending, and the ledger sequence it reflects.GET /v1/users/{id}/points/activity?cursor=returns entries with their explanations.POST /v1/users/{id}/redemptionswith anIdempotency-Keyheader. Returns 201, or 409 if funds are insufficient.POST /internal/v1/rulescreates a new version; existing versions are never edited. Asimulateendpoint lets operators preview impact.
4. Data model
Relational (Postgres-class), sharded by user_id.
- rule_version: immutable once published. Holds the definition (predicates, multiplier, cap spec), priority, effective window, status (draft, shadow, active, retired), and a checksum.
- source_event (inbox): unique on (
source_transaction_id,event_type). - journal: one business event (earn, redeem, reversal, adjustment, expiry), the rule version used, and a resolved
explanation_json(base points, multiplier, cap consumed, promo applied). Unique on (source_transaction_id,event_type). - ledger_entry: append-only, double-entry. Each entry has a signed amount and a sequence number, and the entries of a journal sum to zero (for example +N to the member account, -N to a program liability account).
- account_balance: materialized available and pending points, a version, and the last applied ledger sequence. It lives on the same shard as the ledger.
- cap_usage: points consumed per user, rule, and period, so caps are evaluated deterministically.
- redemption: status (reserved, committed, released) and a per-user unique idempotency key.
Never update or delete ledger rows. Corrections are new compensating journals.
5. Architecture
- The ingestion API authenticates, validates, writes the raw event to the inbox (conflicts ignored), and publishes to Kafka partitioned by
user_id, then returns 202. - Rule-evaluation workers consume per user in order. This matters because cap accounting depends on order. They keep an in-memory cache of rule snapshots, choose rules by the event's
settled_at, compute points, and consume caps. - In one database transaction, the worker inserts the journal, the ledger entries, and updates the balance and
cap_usage. - Change data capture feeds a Redis balance cache, an activity/search store, and a data lake.
- The redemption path goes straight to the ledger database. Reconciliation and backtest jobs read from the lake.
6. Key deep dives
Idempotency. Kafka delivers at least once. The unique constraint on the journal turns that into effectively-once: if the insert violates uniqueness, the worker acknowledges and skips. No distributed transaction is needed.
Rule versioning. Selecting a version based on event time, not processing time, makes results replayable. Because each journal stores the version and the fully resolved explanation, retiring a rule later cannot alter history. New rules can run in shadow mode first and be compared before activation.
Strong balances. The authoritative balance changes in the same transaction as the ledger insert. A redemption locks the balance row (or uses an optimistic version check), verifies sufficiency, and writes a reservation, then commits or releases after the partner call. This prevents double-spend. The cache only serves reads. The balance response includes the ledger sequence, and after a user's own redemption or on a cache miss, read the primary for read-your-writes.
Reconciliation. A daily job compares the processor's settlement file with the inbox and journals by transaction ID. It classifies:
- missing credits (re-enqueue; idempotency makes this safe),
- extra or duplicate credits (post a compensating reversal),
- amount mismatches (post an adjustment journal),
- unmatched refunds.
Also verify that every journal sums to zero and that each balance equals the sum of its entries.
7. Trade-offs
- Relational vs. NoSQL for the ledger: Relational gives multi-row ACID transactions, unique constraints, and easy audit queries, which are exactly what a ledger needs. A key-value store scales writes further but pushes atomicity and uniqueness into application code. At ~3k writes/s, relational wins.
- Cache: Fast reads but potentially stale; never use it for spend decisions.
- Partitioning by user: Serializes per-user work and keeps everything on one shard, but a very hot user can skew load (rare here).
- Storage lifecycle: Partition the ledger by month, move old partitions to cheaper storage, and keep the balance table small.
8. Common mistakes
- Using wall-clock time for rule selection, which breaks replays.
- Relying on cache or eventual consistency for redemption checks.
- Updating or deleting ledger rows instead of writing compensating entries.
- Idempotency only at the API layer, not enforced by a database constraint.
- Ignoring refunds that arrive after points were already spent.
- Processing a user's events out of order, corrupting cap usage.