Auditable Loyalty Points Engine and Ledger

Medium · System Design · Software Engineer · Technical Screen

Prompt

Architect a Loyalty Points & Ledger Service for a consumer card and housing-rewards platform. Members earn points across diverse settled payment types—such as 1x on fee-free monthly housing payments (subject to annual caps), 3x at restaurants, travel booking bonuses, and 5x during scheduled first-of-month promotional windows—and spend those points on statement/housing credits, travel portal orders, or external airline/hotel transfers.

Because unredeemed points represent a regulated financial liability, every point minted or redeemed must be deterministic, explainable, and auditable:

  • Core capabilities: Ingest settled payment events and evaluate configurable, versioned earning rules; record every credit and debit in an append-only ledger capturing the exact rule version, multipliers, and cap usage; serve current spendable balances and process redemptions without ever permitting negative balances; and run daily reconciliation against processor settlement files to detect and resolve mismatches.
  • Correctness guarantees: Guarantee strict idempotency when upstream payment gateways replay webhooks, enforce strong consistency so concurrent redemptions can never double-spend points, and isolate rule edits so new versions never mutate historical credits or break replay determinism.
  • Target scale & SLAs: Support 5 million active members and 10 million transactions per day (~120 TPS average, spiking to 1,500 TPS during promotional campaigns), < 50 ms p95 latency for balance reads, < 5 seconds end-to-end ingestion-to-credit latency, and ~15–20 million new append-only ledger rows per day retained across multiple years for financial audits.

Scope & Expectations

  • Service APIs: Specify contracts for signed webhook ingestion, low-latency balance and explainable activity reads, idempotent point redemptions, and versioned rule publishing.
  • Storage & ledger schema: Model immutable rule versions, double-entry append-only ledger tables, and materialized user balances, justifying relational versus NoSQL choices alongside read-caching layers.
  • Pipeline & concurrency mechanics: Walk through single-transaction idempotent crediting, pure integer rule evaluation, race-free balance locking, and multi-step coordination for external partner transfers.
  • Reconciliation & lifecycle operations: Cover daily T+N settlement verification, multi-year cold-storage partitioning, and recovery from processor retries or partner timeouts.

Step-by-step walkthrough

  1. Clarify requirements and core assumptions

    Reward points behave like money: users spend them on rent credits, flights, and hotels, and the company carries unredeemed points as a financial liability on its balance sheet. That means financial accuracy and explainability come first, and low latency comes second. Before drawing boxes, clarify the domain rules with the interviewer.

    Key terms we will use throughout this design:

    • Webhook: an automated HTTP POST notification sent by an external payment processor whenever a transaction changes state (such as settling or being refunded).
    • Idempotency: the property that processing the exact same event once or ten times produces the exact same system state, never crediting or debiting points twice.
    • Double-entry ledger: an append-only accounting log where every point movement is recorded as balanced positive and negative entries across accounts whose sum is always zero.

    Questions to confirm and assumptions for this design:

    • Which payment events earn points? Only settled card purchases and cleared rent payments earn points; temporary card authorizations are ignored. Later lifecycle events (full or partial refunds, disputes opened, disputes resolved) create new adjustment entries.
    • How are fractional points rounded? Points are whole integers, rounded down per transaction using integer math on cents (never floating-point decimals).
    • Which clock selects the earning rule? Always the purchase's own transaction timestamp (transaction_time) converted to a fixed program time zone (for example, America/New_York), never the time our server processes the webhook. A dinner bought at 11:45 PM on the 1st of the month ("First-of-Month Bonus Day" 5x promo) still earns 5x even if the card network settles it two days later.
    • Are there earning caps? Yes, rules can enforce per-user period caps (for example, 1x on housing payments capped at 100,000 points per calendar year).
    • How do redemptions work? Statement/housing credits and internal travel bookings complete inside our platform, whereas airline/hotel partner transfers call slow external partner APIs that can fail or time out.

    Summary of requirements:

    • Functional: (1) ingest settled transactions and evaluate configurable, versioned rules; (2) write an append-only, explainable ledger recording rule versions, multipliers, and caps; (3) serve usable balances and execute redemptions without ever allowing negative balances; (4) run daily reconciliation to detect and fix discrepancies against processor settlement files.
    • Non-functional: strict idempotency under webhook retries; strong consistency on redemptions (zero double-spending); immutable historical credits when rules change; < 50 ms p95 balance reads; < 5 s event-to-credit ingestion latency; 7-year compliant audit retention.
  2. Back-of-the-envelope capacity estimates

    Let's translate the user and transaction numbers into concrete database, cache, and storage targets so we know where the real bottlenecks sit.

    • Average and peak transaction rate: 10,000,000 transactions / 86,400 seconds per day ≈ 116 TPS (~120 TPS average), spiking ~13x to 1,500 TPS on promotional bonus days.
    • Ledger rows per day: Every settled transaction writes 1 journal header and 2 double-entry posting lines (one credit to the user, one debit to a funding account). Including ~700,000 daily redemptions and refunds, the ledger grows by ~10.7M journal entries and ~21.4M posting rows per day (matching the 15–20M daily ledger entries scale).
    • Peak database row writes: One point-earning transaction writes ~6 rows (source_event + journal_entry + 2 posting rows + user_balance + cap_usage), giving 1,500 * 6 = 9,000 row writes/s at peak.
    • Storage over 7 years: Daily new data is ~3 GB of postings (20M * 150 B), ~6 GB of journal entries (10.5M * 550 B including JSON explanations), and ~11 GB of raw webhook payloads (10.5M * 1 KB), totaling ~20 GB/day, or 7.3 TB/year, or ~51 TB over 7 years.
    • Balance read load and memory footprint: 5,000,000 active users * 100 B per balance row = 500 MB (0.5 GB), which fits completely in RAM. Assuming 4 balance views per active user per day gives 20M reads/day (~230 QPS average, ~5,000 QPS peak).
    Metric                      Estimate                         Design implication
    --------------------------  -------------------------------  -------------------------------------------
    Active users                5,000,000                        Balance table is ~0.5 GB -> fits in RAM
    Ingestion TPS               120 avg / 1,500 peak             Buffer bursts with a partitioned log broker
    Peak DB row writes          ~9,000 writes/s (6 rows/txn)     Fits comfortably on 4 PostgreSQL shards
    Balance read QPS            230 avg / 5,000 peak (< 50 ms)   Serve display reads from Redis + replicas
    Daily ledger growth         ~20 GB/day (~20M posting rows)   ~51 TB over 7 yrs -> tier old months to S3
    

    What these numbers tell us: 9,000 row writes/s is well within reach of a small sharded relational database. Raw throughput is not the hardest problem here; idempotency, concurrent balance locking, deterministic rule versioning, and 7-year auditability are.

  3. API design

    We separate internal processor ingestion APIs, user-facing balance and redemption APIs, and internal operator rule-management APIs. Two security and reliability headers appear below:

    • HMAC signature (X-Signature): a cryptographic hash of the timestamp and request body using a shared secret, proving the webhook genuinely came from the payment processor and was not forged or replayed.
    • Idempotency key (Idempotency-Key): a unique UUID generated by the client before sending a request so retrying after a dropped mobile connection returns the original result instead of redeeming points twice.
    1. Transaction Webhook Ingestion (Internal / Processor-facing)
    POST /v1/webhooks/{source_system}
    Headers: X-Signature: HMAC-SHA256(secret, timestamp + raw_body)
             X-Timestamp: <unix_epoch_seconds>   (reject if > 300s old)
    Body:    {
               "source_txn_id": "txn_60418",
               "event_type": "SETTLED",          // SETTLED | REFUNDED | DISPUTE_OPENED | DISPUTE_RESOLVED
               "adjustment_key": "",             // empty for SETTLED; refund_id or dispute_id otherwise
               "user_id": "usr_7190",
               "amount_cents": 6500,
               "currency": "USD",
               "mcc": "5812",
               "channel": "CARD",                // CARD | HOUSING
               "transaction_time": "2026-06-01T23:45:10Z"
             }
    Responses:
      202 Accepted  {"status": "queued"}         (returned only after durable write to Kafka + archive)
      400 Bad Request / 401 Unauthorized         (malformed payload or bad HMAC; sender stops retrying)
      503 Service Unavailable                    (temporary outage; sender retries with backoff)
    
    2. Balance & Explainable Activity (User-facing)
    GET  /v1/users/{user_id}/balance
      -> 200 {"available_points": 31200, "held_points": 10000, "as_of_entry_id": "ent_514", "updated_at": "..."}
    
    GET  /v1/users/{user_id}/ledger?limit=25&cursor=<opaque_token>
      -> 200 {"items": [{"entry_id": "ent_514", "points": 325, "ruleset_id": "rs_2026_06",
                         "explanation": [...]}], "next_cursor": "..."}
    
    3. Point Redemptions (User-facing)
    POST /v1/users/{user_id}/redemptions
    Headers: Idempotency-Key: <client-generated UUID>
    Body:    {"points": 10000, "kind": "PARTNER_TRANSFER", "partner_id": "airline_x", "member_no": "99120"}
    Responses:
      201 Created   {"redemption_id": "red_409", "status": "HELD"}   (or "CAPTURED" for instant housing credit)
      409 Conflict  {"error": "INSUFFICIENT_POINTS"}
      422 Unprocessable Entity                                       (same Idempotency-Key, different body)
    
    4. Versioned Rule Administration (Internal operators)
    POST /v1/rules/{rule_id}/versions             -> create immutable DRAFT rule version
    POST /v1/rule-versions/{version_id}/approve   -> second operator approves (maker-checker)
    POST /v1/rulesets                             -> publish immutable bundle; effective_from >= now + 60s
    

    Notice the rule effective_from >= now + 60s: operators can never publish a ruleset in the past, which guarantees historical transactions never change retroactively and gives every worker 60 seconds to preload the new ruleset before its activation timestamp arrives.

  4. Data model: versioned rules, double-entry ledger, and balance snapshots

    Relational vs. non-relational storage choice: We store the core ledger and authoritative balances in sharded PostgreSQL (partitioned by hash(user_id)), and use Redis purely as a read-only display cache. Why? Crediting or redeeming points modifies 5–6 rows across multiple tables that must commit together inside an ACID transaction (a database guarantee that a multi-row write happens all-or-nothing, safely isolated from concurrent requests, and survives power loss). PostgreSQL enforces UNIQUE constraints for idempotency and CHECK (available >= 0) constraints right inside the storage engine, and gives financial auditors full SQL. Building those multi-table guarantees manually on top of a NoSQL key-value store adds serious bug risk for a workload of only ~9,000 writes/s.

    Here are the three storage groups on each user shard:

    A. Immutable Rule Definitions (replicated to all shards & cached in worker RAM)
    -------------------------------------------------------------------------------
    rule_version
      rule_version_id  TEXT PK            -- e.g. "bonusday_dining_v1"
      rule_id          TEXT NOT NULL
      stack_group      TEXT NOT NULL      -- "RATE" (pick best match) | "BONUS" (additive)
      priority         INT NOT NULL       -- higher wins inside stack_group
      conditions       JSONB NOT NULL     -- e.g. {"channel": ["CARD"], "category": ["DINING"], "day": [1]}
      rate_bp          INT NOT NULL       -- basis points: 10000 = 1x, 15000 = 1.5x, 50000 = 5x
      cap_key          TEXT NULL          -- e.g. "HOUSING_ANNUAL"
      cap_limit        BIGINT NULL        -- e.g. 100000
      created_by       TEXT, approved_by TEXT
    
    ruleset
      ruleset_id          TEXT PK         -- e.g. "rs_2026_06_01"
      effective_from      TIMESTAMPTZ NOT NULL
      rule_version_ids    TEXT[] NOT NULL -- immutable list of active rule_version_ids
      mcc_map_version     TEXT NOT NULL   -- pins Merchant Category Code -> category lookup
    
    B. Append-Only Double-Entry Ledger (INSERT + SELECT only; UPDATE/DELETE blocked by DB permissions)
    --------------------------------------------------------------------------------------------------
    account
      account_id       TEXT PK            -- e.g. "usr_7190:AVAILABLE", "SYS:ISSUANCE_CARD:shard_03"
      owner_id         TEXT NOT NULL      -- user_id or "SYSTEM"
      account_kind     TEXT NOT NULL      -- AVAILABLE | HELD | OWED | ISSUANCE | REDEMPTION
    
    source_event
      source_event_id  UUID PK
      source_system    TEXT NOT NULL      -- "CARD_PROCESSOR" | "HOUSING_PROCESSOR"
      source_txn_id    TEXT NOT NULL      -- upstream transaction ID
      event_type       TEXT NOT NULL      -- SETTLED | REFUNDED | DISPUTE_OPENED | DISPUTE_RESOLVED
      adjustment_key   TEXT NOT NULL      -- "" for SETTLED; upstream refund_id/dispute_id otherwise
      user_id          TEXT NOT NULL
      amount_cents     BIGINT NOT NULL
      transaction_time TIMESTAMPTZ NOT NULL
      raw_payload      JSONB NOT NULL
      UNIQUE (source_system, source_txn_id, event_type, adjustment_key)
    
    journal_entry
      entry_id         UUID PK
      user_id          TEXT NOT NULL
      entry_type       TEXT NOT NULL      -- EARN | REVERSAL | REDEEM_HOLD | REDEEM_CAPTURE | REDEEM_RELEASE | ADJUSTMENT
      source_txn_id    TEXT NULL          -- direct link to upstream transaction ID for auditability
      ruleset_id       TEXT NULL          -- exact ruleset snapshot evaluated
      redemption_id    UUID NULL
      explanation      JSONB NOT NULL     -- [{"rule_version_id": "...", "rate_bp": 50000, "raw": 325, "granted": 325, ...}]
      prev_hash        TEXT NOT NULL      -- SHA-256 chain per user so tampered rows are detectable
      entry_hash       TEXT NOT NULL
      created_at       TIMESTAMPTZ NOT NULL
    
    posting
      posting_id       UUID PK
      entry_id         UUID NOT NULL REFERENCES journal_entry(entry_id)
      account_id       TEXT NOT NULL REFERENCES account(account_id)
      amount_points    BIGINT NOT NULL    -- signed integer; SUM(amount_points) per entry_id MUST equal 0
    
    C. Materialized Balance & Operational State (mutable, always re-derivable from postings)
    ----------------------------------------------------------------------------------------
    user_balance
      user_id          TEXT PK
      available        BIGINT NOT NULL CHECK (available >= 0)
      held             BIGINT NOT NULL CHECK (held >= 0)
      lifetime_earned  BIGINT NOT NULL DEFAULT 0
      version          BIGINT NOT NULL DEFAULT 0
      last_entry_id    UUID NULL
      updated_at       TIMESTAMPTZ NOT NULL
    
    cap_usage
      (user_id, cap_key, period_label) PK -- e.g. ("usr_7190", "HOUSING_ANNUAL", "2026")
      used_points      BIGINT NOT NULL DEFAULT 0
    
    redemption
      redemption_id    UUID PK
      user_id          TEXT NOT NULL
      idempotency_key  UUID NOT NULL
      request_hash     TEXT NOT NULL
      points           BIGINT NOT NULL
      status           TEXT NOT NULL      -- HELD | CAPTURED | RELEASED | UNKNOWN
      UNIQUE (user_id, idempotency_key)
    

    Notice two crucial details here: - Pinning mcc_map_version: an MCC (Merchant Category Code) is the 4-digit card-network code identifying a merchant's business type (for example, 5812 for restaurants). Reclassifying an MCC from "Other" to "Dining" changes points just like changing a multiplier, so ruleset pins both the rule versions and the MCC dictionary version. - Materialized balance snapshot (user_balance): instead of summing years of posting rows on every read, user_balance stores the pre-computed available and held totals for instant O(1) lookup.

  5. High-level system architecture

    Let's connect the ingestion pipeline, rule evaluator, sharded PostgreSQL ledger, Change Data Capture (CDC) (a process that tails PostgreSQL's transaction log and streams committed row updates downstream in near real time), Redis display cache, redemption coordinator, and nightly reconciliation jobs.

     Payment Processors (Card / Housing)                            External Airline / Hotel APIs
            |  signed webhooks                                                    ^
            v                                                                     | (idempotency = redemption_id)
     +-----------------------+        +----------------------------+      +-------+-------------------+
     | Webhook Ingestion API |------->| Kafka Topic "tx-events"    |      | Redemption API & Saga     |<-- User App
     | verify HMAC, archive  |        | key = user_id (64 parts)   |      | Hold -> Partner -> Settle |    (POST)
     +-----------+-----------+        +-------------+--------------+      +-------+-------------------+
                 | raw JSON                         | per-user order              |
                 v                                  v                             | direct SQL on Primary
     +-----------------------+        +----------------------------+              | (never trusts Redis!)
     | Raw Event Archive     |        | Earning Workers            |<-- Rulesets  |
     | (S3 Object Lock 7 yr) |        | 1. Dedupe source_event     |    (cached   |
     +-----------+-----------+        | 2. Evaluate pinned ruleset |     in RAM)  |
                 |                    | 3. Write entry + postings  |              |
                 |                    |    + user_balance atomically|             |
                 |                    +-------------+--------------+              |
                 |                                  |                             v
                 |                    +-------------v-----------------------------------------+
                 |                    | Sharded PostgreSQL Ledger (16 logical shards / 4 DBs) |
                 |                    | Sync standby in AZ2 + async read replicas             |
                 |                    +-------------+-----------------------------+-----------+
                 |                                  | CDC (Debezium)              | CDC / Snapshot
                 |                                  v                             v
                 |                    +----------------------------+    +---------------------+
                 |                    | Redis Balance Cache        |    | Analytics Warehouse |
                 |                    | < 5 ms display reads       |    | + Recon Workers     |<-- Daily Processor
                 |                    +-------------+--------------+    +---------+-----------+    Settlement CSVs
                 |                                  ^                             |
                 |                                  | GET /balance (< 50 ms p95)  v
                 +----------------------------------+-------------------+  Auto Re-ingest MISSING
                                                                        |  or Maker-Checker ADJUSTMENT
    
  6. Deep dive 1: Strictly idempotent ingestion and atomic point crediting

    Upstream payment processors retry webhooks whenever an acknowledgment times out, and our own workers can crash mid-processing. Checking Redis first ("have I already processed txn_60418?") is not enough on its own: if a worker crashes after crediting the database but before marking Redis, the retry double-credits points; if it marks Redis first and crashes before crediting, the points are lost forever.

    We guarantee exact-once point crediting by enforcing a database UNIQUE constraint inside the exact same SQL transaction that writes the ledger postings and updates user_balance:

    • Why (source_system, source_txn_id, event_type, adjustment_key)? A constraint on (source_txn_id, event_type) alone catches duplicate SETTLED webhooks, which is the core pattern. Adding source_system avoids ID collisions between card and rent processors, and adding adjustment_key (empty "" for SETTLED, or the processor's refund_id for REFUNDED) allows a single 100 USD purchase to have two legitimate partial refunds (30 USD and 20 USD) without rejecting the second refund as a duplicate!
    • Why not deduplicate by webhook delivery ID? When a processor's retry scheduler creates a fresh webhook delivery attempt for the same settled purchase, it often assigns a new delivery UUID. Always deduplicate on the business event key, not the HTTP delivery envelope.

    Here is the single-shard SQL transaction executed by an Earning Worker:

    BEGIN;
    
    -- Phase 1: Atomic idempotency gate. If 0 rows return, this exact event already committed.
    INSERT INTO source_event (
        source_event_id, source_system, source_txn_id, event_type, adjustment_key,
        user_id, amount_cents, transaction_time, raw_payload
    )
    VALUES (
        :event_uuid, :src_sys, :txn_id, 'SETTLED', '',
        :user_id, :amount_cents, :txn_time, :payload
    )
    ON CONFLICT (source_system, source_txn_id, event_type, adjustment_key) DO NOTHING
    RETURNING source_event_id;
    -- If no row was returned -> COMMIT immediately, commit Kafka offset, and stop!
    
    -- Phase 2: Ensure user_balance row exists (vital for a user's very first transaction!)
    -- and lock it so concurrent redemptions or cap checks serialize cleanly.
    INSERT INTO user_balance (user_id, available, held, lifetime_earned, version, updated_at)
    VALUES (:user_id, 0, 0, 0, 0, now())
    ON CONFLICT (user_id) DO NOTHING;
    
    SELECT available FROM user_balance WHERE user_id = :user_id FOR UPDATE;
    SELECT cap_key, used_points FROM cap_usage WHERE user_id = :user_id AND period_label = :year;
    
    -- (Worker evaluates pure rule function in memory -> :points, :ruleset_id, :explanation_json)
    
    -- Phase 3: Append immutable journal entry and balanced zero-sum postings.
    INSERT INTO journal_entry (
        entry_id, user_id, entry_type, source_txn_id, ruleset_id,
        explanation, prev_hash, entry_hash, created_at
    )
    VALUES (
        :entry_id, :user_id, 'EARN', :txn_id, :ruleset_id,
        :explanation_json, :prev_hash, :entry_hash, now()
    );
    
    INSERT INTO posting (posting_id, entry_id, account_id, amount_points)
    VALUES (:post_user_id, :entry_id, :user_available_acct,  :points),
           (:post_sys_id,  :entry_id, :shard_issuance_acct, -:points);
    
    -- Phase 4: Update materialized balance snapshot and cap counter in the same transaction.
    UPDATE user_balance
    SET available = available + :points,
        lifetime_earned = lifetime_earned + :points,
        version = version + 1,
        last_entry_id = :entry_id,
        updated_at = now()
    WHERE user_id = :user_id;
    
    INSERT INTO cap_usage (user_id, cap_key, period_label, used_points)
    VALUES (:user_id, :cap_key, :year, :capped_points)
    ON CONFLICT (user_id, cap_key, period_label)
    DO UPDATE SET used_points = cap_usage.used_points + EXCLUDED.used_points;
    
    COMMIT;
    -- Phase 5: Only AFTER PostgreSQL COMMIT succeeds do we commit the Kafka offset.
    

    Trace what happens if the worker crashes right after COMMIT (before telling Kafka it finished):

    Attempt 1: INSERT source_event (1 row) -> INSERT postings (+325) -> UPDATE balance (+325) -> COMMIT -> CRASH!
    Attempt 2: Kafka redelivers txn_60418 -> INSERT source_event hits UNIQUE conflict (0 rows returned)
               -> Worker skips Phases 2-4 -> COMMIT -> Commits Kafka offset -> Done (0 extra points!)
    
  7. Deep dive 2: Versioned, deterministic rule evaluation

    Historical credits must never shift when operators publish new rules. Four design rules guarantee that:

    1. Immutable rulesets selected by transaction_time: Workers pick the latest ruleset where effective_from <= transaction_time. Because new rulesets require effective_from >= now + 60s, the active ruleset for any timestamp in the past is permanently frozen.
    2. Basis-point integer arithmetic: A basis point is 1/100th of a percent (10,000 bp = 1.0x, 15,000 bp = 1.5x, 30,000 bp = 3.0x, 50,000 bp = 5.0x). Floating-point binary numbers cannot represent most decimal fractions accurately (0.29 * 100 evaluates to 28.999999999999996 in Python, rounding down to 28 instead of 29!). With integer cents and basis points, amount_cents * rate_bp // 1_000_000 is exact for both whole and fractional multipliers like 1.5x.
    3. Explicit stacking groups: Rules belong to a stack_group. Within "RATE", only the highest-priority matching rule wins (so First-of-Month Dining 5x overrides everyday Dining 3x, rather than accidentally paying 8x). Within "BONUS", matching promos add on top. Ties break deterministically by rule_version_id.
    4. Pure evaluation with recorded inputs: The evaluator makes zero network, clock, or database calls. Every input (ruleset_id, enriched category, cap_used_before) is saved inside journal_entry.explanation.
    from dataclasses import dataclass
    from typing import Dict, List, Tuple
    
    
    @dataclass(frozen=True)
    class RuleVersion:
        rule_version_id: str
        stack_group: str             # e.g. "RATE" (pick highest priority) or "BONUS"
        priority: int                # higher number wins inside stack_group
        conditions: Dict[str, list]  # field -> allowed values, e.g. {"category": ["DINING"]}
        rate_bp: int                 # basis points: 10_000 = 1x, 30_000 = 3x, 50_000 = 5x
        cap_key: str = ""            # empty string means uncapped
        cap_limit: int = 0
    
    
    def matches_rule(rule: RuleVersion, enriched_txn: Dict) -> bool:
        """Check whether every condition key on the rule matches the enriched transaction."""
        for field_name, allowed_values in rule.conditions.items():
            if enriched_txn.get(field_name) not in allowed_values:
                return False
        return True
    
    
    def evaluate_rules(
        enriched_txn: Dict,
        active_rules: List[RuleVersion],
        cap_used_snapshot: Dict[str, int],
    ) -> Tuple[int, List[Dict]]:
        """Pure function: identical inputs always produce identical points and explanation."""
        # Phase 1: Pick the single highest-priority matching rule per stack_group.
        winning_rule_by_group: Dict[str, RuleVersion] = {}
        for rule in active_rules:
            if not matches_rule(rule, enriched_txn):
                continue
            incumbent = winning_rule_by_group.get(rule.stack_group)
            # Break priority ties deterministically by rule_version_id string order.
            if incumbent is None or (rule.priority, rule.rule_version_id) > (
                incumbent.priority,
                incumbent.rule_version_id,
            ):
                winning_rule_by_group[rule.stack_group] = rule
    
        # Phase 2: Compute integer points and apply per-period caps in sorted group order.
        total_points = 0
        explanation_items: List[Dict] = []
        working_caps = dict(cap_used_snapshot)
    
        for group_name in sorted(winning_rule_by_group):
            rule = winning_rule_by_group[group_name]
            # 1 dollar = 100 cents and 1x = 10,000 bp -> divide by 100 * 10,000 = 1,000,000.
            raw_points = (enriched_txn["amount_cents"] * rule.rate_bp) // 1_000_000
            granted_points = raw_points
            cap_used_before = None
    
            if rule.cap_key:
                cap_used_before = working_caps.get(rule.cap_key, 0)
                remaining_cap = max(0, rule.cap_limit - cap_used_before)
                granted_points = min(raw_points, remaining_cap)
                working_caps[rule.cap_key] = cap_used_before + granted_points
    
            total_points += granted_points
            explanation_items.append({
                "rule_version_id": rule.rule_version_id,
                "rate_bp": rule.rate_bp,
                "raw_points": raw_points,
                "granted_points": granted_points,
                "cap_key": rule.cap_key,
                "cap_used_before": cap_used_before,
            })
    
        return total_points, explanation_items
    

    Trace three concrete transactions through evaluate_rules:

    Transaction                                     Winning rule           Math (integer)                  Granted
    ----------------------------------------------  ---------------------  ------------------------------  -------
    65.00 USD dining on June 5 (6,500 cents)        dining_3x_v2           6500 * 30,000 // 1,000,000      195 pts
    65.00 USD dining on June 1 Bonus Day            bonusday_dining_5x_v1  6500 * 50,000 // 1,000,000      325 pts
    2,200 USD housing, 99,200 / 100,000 cap used    housing_1x_capped_v4   min(2200, 100000 - 99200)       800 pts
    
  8. Deep dive 3: Double-entry balances, locking, and partner redemption sagas

    Let's connect the three pieces of safe point balances and redemptions:

    1. Double-entry postings + materialized balance transitions Every point movement shifts points between accounts so the postings of every journal_entry sum to 0, and updates user_balance (available and held) inside the same transaction:

    Entry type       Account A posting             Account B posting               user_balance delta
    ---------------  ----------------------------  ------------------------------  ----------------------------
    EARN (+195)      usr:AVAILABLE     +195        SYS:ISSUANCE_CARD   -195        available +195
    REDEEM_HOLD      usr:AVAILABLE  -10,000        usr:HELD         +10,000        available -10000, held +10000
    REDEEM_CAPTURE   usr:HELD       -10,000        SYS:REDEMPTION_AIR +10,000      held -10000
    REDEEM_RELEASE   usr:HELD       -10,000        usr:AVAILABLE    +10,000        held -10000, available +10000
    REVERSAL (-195)  usr:AVAILABLE     -195        SYS:ISSUANCE_CARD   +195        available -195
    

    Updating user_balance via explicit SQL in the same transaction (or via a PostgreSQL AFTER INSERT ON posting database trigger — an automatic SQL procedure run by the database inside the same transaction) guarantees the primary database's user_balance never drifts from posting. Meanwhile, CDC streams user_balance updates into Redis in < 100 ms so GET /balance runs in < 5 ms without touching the primary. Redemptions never read Redis; they always check and debit user_balance on the PostgreSQL primary.

    2. Pessimistic vs. optimistic vs. conditional-update locking for redemptions - Pessimistic locking (SELECT available FROM user_balance WHERE user_id = :u FOR UPDATE): acquires an exclusive row lock immediately so any second redemption waits in line, then checks available >= :pts in application code and issues UPDATE. Safe, though it holds the lock across an extra app-to-DB network round trip. - Optimistic locking (UPDATE user_balance SET available = available - :pts, version = version + 1 WHERE user_id = :u AND version = :read_version AND available >= :pts): reads without locking first and checks at write time that nobody changed version. Great when contention is rare, though concurrent earns force retries. - Atomic conditional UPDATE (best of both here): checks and debits directly inside one SQL UPDATE statement on PostgreSQL (WHERE user_id = :u AND available >= :pts). PostgreSQL acquires the row-level lock during the UPDATE, evaluates available >= :pts against the latest committed value, and holds the lock only until COMMIT a millisecond later:

    BEGIN;
    
    -- 1. Idempotency check on (user_id, idempotency_key).
    INSERT INTO redemption (redemption_id, user_id, idempotency_key, request_hash, points, status)
    VALUES (:red_id, :user_id, :idem_key, :req_hash, :points, 'HELD')
    ON CONFLICT (user_id, idempotency_key) DO NOTHING
    RETURNING redemption_id;
    -- If 0 rows returned -> SELECT existing row; return stored response (or 422 if request_hash differs).
    
    -- 2. Atomic check-and-debit on PostgreSQL primary (backed by CHECK (available >= 0)).
    UPDATE user_balance
    SET available = available - :points,
        held = held + :points,
        version = version + 1,
        updated_at = now()
    WHERE user_id = :user_id AND available >= :points
    RETURNING available;
    -- If 0 rows returned -> ROLLBACK (which also removes the redemption row) and return 409 INSUFFICIENT_POINTS!
    
    -- 3. Record REDEEM_HOLD journal entry and zero-sum postings.
    INSERT INTO journal_entry (entry_id, user_id, entry_type, redemption_id, explanation, prev_hash, entry_hash, created_at)
    VALUES (:entry_id, :user_id, 'REDEEM_HOLD', :red_id, :hold_json, :prev_hash, :entry_hash, now());
    
    INSERT INTO posting (posting_id, entry_id, account_id, amount_points)
    VALUES (:p1, :entry_id, :user_available_acct, -:points),
           (:p2, :entry_id, :user_held_acct,       :points);
    
    COMMIT;
    

    3. Two-step Saga for slow external partner transfers Never call an external airline HTTP API while holding an open PostgreSQL transaction (a slow 10-second partner response would exhaust database connections and lock rows). Instead, use a saga — a sequence of short, local database transactions coordinated around the external call: 1. Transaction 1 (REDEEM_HOLD): Atomically move points from AVAILABLE to HELD and commit. Those points cannot be spent twice while the transfer is in flight. 2. External HTTP Call: Call the airline API outside any DB transaction, passing redemption_id as the partner's idempotency key. 3. Transaction 2 (CAPTURE or RELEASE): - Partner returns 200 OK -> write REDEEM_CAPTURE postings and UPDATE user_balance SET held = held - :points, marking status CAPTURED. - Partner returns a definite rejection (e.g., invalid frequent-flyer number) -> write REDEEM_RELEASE postings and UPDATE user_balance SET held = held - :points, available = available + :points, marking status RELEASED. - Partner times out or returns 500 -> mark status UNKNOWN and keep the points in HELD! Never auto-release on a timeout, because the airline may have actually credited the miles. A background reconciliation worker polls the airline's status API by redemption_id until it gets a definitive yes or no.

  9. Daily reconciliation, scaling, and failure handling

    Daily reconciliation (T+2 window) Internal ledger invariants cannot detect a webhook that was never delivered. Every night, batch SQL jobs in the analytics warehouse compare the processors' daily settlement CSVs against a point-in-time CDC snapshot of the ledger (allowing a 48-hour grace window for in-flight settlements):

    1. Completeness check on (source_system, source_txn_id, event_type, adjustment_key):
      • MISSING (in processor file, absent from source_event): automatically re-publish into the tx-events Kafka topic. Because ingestion is idempotent, auto-replay is completely safe.
      • EXTRA or AMOUNT_MISMATCH: open an audit ticket in recon_case; once investigated, an operator creates a maker-checker approved ADJUSTMENT journal entry (never editing or deleting existing ledger rows).
    2. Deterministic rule audit: Re-run the pure evaluate_rules function over the day's 10M EARN entries using their recorded ruleset_id and cap_used_before. Any mismatch immediately pages engineering for a code bug.
    3. Accounting invariants: Verify that every journal_entry sums to 0, every user's SUM(posting.amount_points) equals user_balance.available and user_balance.held, and per-user SHA-256 hash chains are unbroken.

    Scaling to 51 TB and promotional spikes - Sharding without cross-shard transactions: 16 logical shards mapped onto 4 PostgreSQL clusters by hash(user_id) (~2,250 row writes/s per cluster at bonus-day peak). Each shard has its own system sub-accounts (SYS:ISSUANCE_CARD:shard_03) so every EARN and REDEEM stays 100% single-shard. - Eliminating hot system rows: Notice user_balance only tracks users, never system accounts! If SYS:ISSUANCE_CARD had a mutable balance row updated on every earn, all 1,500 TPS would contend on one row lock. System totals are summed asynchronously in daily finance rollups. - Cold storage tiering: Partition source_event, journal_entry, and posting by month. Detach partitions older than 13 months and archive them as immutable Parquet files in S3 Object Lock for 7-year compliance queries; active balances remain instant via user_balance.

    Failure handling - Kafka or Ingestion API down: Return 503 so payment gateways retry with exponential backoff; anything missed past gateway retry limits is caught and re-ingested by nightly reconciliation. - Poison event: If one malformed event repeatedly crashes evaluation, park that user's events into a per-user dead-letter queue (a holding queue for unprocessable messages) so that user's cap ordering stays accurate while all other 5M users proceed unaffected. - PostgreSQL primary crash: Automatic failover to the synchronous standby in a second availability zone loses zero committed transactions; Kafka buffers events during the ~20–30 s failover. - Redis cache crash: GET /balance falls back to PostgreSQL read replicas; a primary-key lookup on a 0.5 GB table in RAM still comfortably meets < 50 ms p95. - Misconfigured promo rule (e.g., 30x instead of 3x): Real-time anomaly alerts track points minted per minute; operators activate a kill-switch ruleset (effective_from = now + 60s) and post audited ADJUSTMENT reversals if required.

  10. Summary of architectural trade-offs

    Design area Chosen approach Main alternative Why this trade-off fits
    Core ledger database Sharded PostgreSQL (ACID + constraints) DynamoDB / Cassandra Multi-row atomic writes + DB-enforced idempotency and available >= 0 outweigh manual sharding at 9k writes/s
    Balance read path Sync user_balance in DB + CDC to Redis Sum posting rows on read, or Redis-only < 5 ms display reads (accepting ~100 ms display lag) while redemptions hit exact primary state
    Redemption concurrency Single conditional UPDATE ... WHERE available >= :pts Optimistic retry loop or app-level locks Zero race-condition window, 1 DB round trip, zero wasted retries
    Partner transfers Hold -> Partner API -> Capture/Release Saga Distributed 2PC or DB lock across HTTP Never holds DB locks over external networks; UNKNOWN state prevents double-gifting on timeouts
    Rule versioning Immutable rulesets pinned by transaction_time Mutable rules evaluated by processing time Guarantees replay determinism and clean audits; fixes require explicit adjustment entries

Intuition & how it works

Think of a reward points service like a bank checkbook paired with a dated rulebook. Instead of keeping each user's points as a single number on a whiteboard that gets erased and overwritten whenever a webhook arrives, every point earned, held, spent, or refunded is written in permanent ink as a balanced pair of lines in an append-only double-entry ledger (an accounting table where rows can only be inserted, never edited or deleted, and every transaction's credits and debits sum to zero). Each entry also stamps which exact page of the rulebook (ruleset_id and rule_version_id) was in force at the moment the purchase occurred, while a separate summary row — a materialized balance snapshot — tracks the user's current usable total for instant lookups.

The naive approach is a single users table with a points_balance integer column updated by balance = balance + amount * current_multiplier whenever a payment webhook arrives. That design fails quickly in production: when a payment gateway retries a timed-out webhook, the user silently gets paid twice; when a user taps "Redeem" on a phone and laptop at the same instant, two requests read the same balance before either writes back and spend the same points twice; and when a business operator edits a dining rule from 3x to 2x, nobody can prove or reproduce why last month's transactions earned 3x.

Walk through four concrete events for Maya starting from 0 points to see how all pieces cooperate:

Event                                     What happens inside PostgreSQL & Redis                       Maya's balance
----------------------------------------  -----------------------------------------------------------  -------------------------
1. Maya spends 60.00 USD on dining        Insert source_event (txn_305, SETTLED). Match ruleset by     available: 300, held: 0
   on June 1 (Bonus Day 5x rule)          transaction_time -> 5x -> +300 pts (+300 user / -300 sys).   (CDC updates Redis <0.1s)

2. Payment gateway retries txn_305        INSERT INTO source_event ... ON CONFLICT DO NOTHING          available: 300, held: 0
   webhook 8 seconds later                returns 0 rows -> worker commits Kafka offset immediately.   (duplicate safely ignored)

3. Phone & laptop both request a          Phone runs UPDATE user_balance ... WHERE available >= 250    Phone -> 201 Created
   250-pt airline transfer at once        -> locks row, moves 250 to HELD (available = 50), commits.   available: 50, held: 250
   (two distinct Idempotency-Keys)        Laptop wakes up, checks 50 >= 250 (false -> 0 rows) -> 409.  Laptop -> 409 Conflict

4. Airline API confirms transfer          Saga posts REDEEM_CAPTURE (-250 HELD / +250 PARTNER_AIR)     available: 50, held: 0
   outside the DB transaction             and decrements held by 250.                                  (transfer complete)

Key trade-offs

  • Sharded relational ledger (PostgreSQL) vs. NoSQL wide-column or key-value store. Crediting or holding points updates up to six rows across five tables (source_event, journal_entry, posting, user_balance, cap_usage) inside one ACID transaction (an all-or-nothing, crash-safe database transaction), backed by database-enforced UNIQUE and CHECK (available >= 0) constraints. At ~9,000 row writes/s at peak, 4 sharded PostgreSQL clusters handle the load comfortably while giving auditors full SQL. A NoSQL store scales writes with less sharding work, but forces application code to emulate multi-row atomicity and non-negative balance invariants — a dangerous trade for money-like balances.
  • Synchronous user_balance + Change Data Capture (CDC) Redis cache vs. reading from the ledger directly. Updating the user_balance snapshot row inside the ledger transaction keeps the primary database 100% exact for redemptions at the cost of one extra row write per event, while Change Data Capture (CDC) (streaming committed database log events downstream) feeds Redis so GET /balance answers in < 5 ms. Display balances in Redis can lag by ~100 ms, which is harmless because every spending decision bypasses Redis and queries the PostgreSQL primary.
  • Single-statement conditional UPDATE vs. pessimistic SELECT FOR UPDATE vs. optimistic version retries. Running UPDATE user_balance SET available = available - :pts ... WHERE user_id = :u AND available >= :pts checks and debits under PostgreSQL's row lock in a single database round trip, avoiding both the longer lock hold time of reading into app memory with pessimistic locking (locking rows upfront before checking logic) and the wasted retry loops of optimistic locking (checking a version counter at write time without locking upfront).
  • Two-step Hold-Capture Saga vs. holding a transaction across partner APIs. External airline transfers use a saga (a sequence of short local transactions coordinated around an external network call) that moves points to HELD first, calls the partner with redemption_id, and then captures or releases. This prevents slow partner APIs from exhausting database locks, at the cost of managing an UNKNOWN timeout state resolved asynchronously by polling the partner.
  • Immutable rulesets pinned by transaction_time vs. mutable in-place rules. Requiring every rule change to create a new immutable ruleset with effective_from in the future makes historical audits and replays 100% deterministic, at the operational cost that urgent fixes cannot rewrite past transactions silently and must post explicit, two-person approved ADJUSTMENT entries.
  • Per-shard system issuance accounts without mutable balance rows. Posting system debits to shard-local accounts like SYS:ISSUANCE_CARD:shard_03 without maintaining a live balance row eliminates a global hot-row lock that all 1,500 TPS would otherwise fight over, trading real-time global liability queries for fast daily warehouse rollups.

Common mistakes

  • Read-then-write balance checks in application code: Running SELECT available in code, checking if available >= points, and then running an unconditional UPDATE allows two concurrent requests to pass the if check simultaneously and drive the balance negative.
  • Trusting the Redis cache during redemptions: Checking a slightly stale cached balance lets a user spend the same points twice within the ~100 ms CDC replication window.
  • Deduplicating in Redis or memory outside the ledger transaction: Any crash between marking an event "seen" in Redis and committing the database transaction either permanently drops the user's points or double-credits on retry.
  • Using the wrong idempotency key: Deduplicating on webhook HTTP delivery ID misses retries sent with fresh delivery envelopes, while deduplicating only on (source_txn_id, event_type) without an adjustment_key wrongly drops a legitimate second partial refund on the same purchase.
  • Evaluating rules using server processing time or floating-point math: Using wall-clock time breaks late-settling promotional transactions and replays, while IEEE-754 floats introduce 1-point rounding bugs (0.29 * 100 == 28.999999999999996) that fail audit checks.
  • Auto-releasing held points when an external partner transfer times out: A timeout means the outcome is unknown, not failed; releasing points immediately risks giving the user free airline miles AND keeping their points.
  • Reconciling the ledger only against itself: Verifying that postings sum to zero proves internal consistency, but only joining against external processor settlement files catches webhooks that were dropped completely.

Follow-up questions

  • How should the ledger handle post-settlement reversals when a cardholder partially refunds or disputes a purchase several weeks after earning points? Never edit or delete the original EARN entry; instead, ingest the REFUNDED event and append a new REVERSAL journal entry linked to the original entry's ruleset_id and granted points rather than today's rules. For partial refunds, compute a cumulative target (original_points * total_refunded_cents // original_amount_cents - points_already_reversed) so multiple partial refunds never lose or invent a point to rounding, and return any reversed capped points to that original period's cap_usage counter. If the user already spent the points and available is smaller than the clawback, deduct available down to 0 and post the remaining deficit to the user's OWED ledger account so future point earnings automatically pay down the negative obligation before adding to available. For disputes, DISPUTE_OPENED freezes the disputed points by moving them from AVAILABLE to HELD, and DISPUTE_RESOLVED either releases them back to AVAILABLE (user/merchant won) or converts the hold into a permanent REVERSAL.
  • Suppose a member holds 10,000 points and submits two distinct 10,000-point redemption requests from two devices at the exact same millisecond. How do you guarantee only one succeeds? Because the phone and laptop are two separate user actions, each device sends its own client-generated Idempotency-Key, and both requests bypass the Redis cache to execute UPDATE user_balance SET available = available - 10000, held = held + 10000, version = version + 1 WHERE user_id = :u AND available >= 10000 directly on the user's PostgreSQL primary shard. PostgreSQL's row-level lock serializes the two UPDATE statements: Device A acquires the row lock first, reduces available from 10000 to 0, writes its REDEEM_HOLD postings, and commits (201 Created). Device B blocks on Device A's row lock until commit, then re-evaluates WHERE available >= 10000 under READ COMMITTED isolation against the freshly committed 0 balance, updates zero rows, rolls back, and returns 409 INSUFFICIENT_POINTS — with CHECK (available >= 0) standing guard at the schema level against any future code bug.
  • Before launching a new status-tier multiplier structure, product managers want to quantify point cost and catch rule bugs safely. How would you build offline backtesting and live shadow evaluation? Because evaluate_rules is a deterministic, side-effect-free function, the exact same rule engine runs in production, historical backtesting (replaying past data offline), and live shadow evaluation (running a candidate rule alongside production on live traffic without affecting real balances). First, store tier changes in a temporal user_tier_history (user_id, tier, valid_from, valid_to) table so any historical timestamp resolves the exact tier the user held at transaction_time. For backtesting, a batch job replays 90 days of archived source_event records in per-user chronological order (so annual and monthly caps fill realistically) and reports total point liability deltas, cap hit rates, and per-tier distributions before approval. For live shadow mode, mark the candidate ruleset SHADOW and run an isolated Kafka consumer group that evaluates live events in parallel using its own separate shadow_cap_usage table, writing side-by-side diffs to the analytics warehouse while leaving user_balance and the real ledger untouched.

Follow-up questions

Similar questions

More Bilt Rewards interview questions

All 4 Bilt Rewards questions →