Deterministic Financial Services for Out-of-Order Loan Events

Medium · System Design · Backend Engineer · Onsite

Prompt

Design a four-stage financial backend that processes irregular loan-servicing workflows where penny-exact accounting, auditability, and deterministic crash recovery matter far more than raw request throughput:

  1. Typed Sparse In-Memory Store: Maintain tables whose columns declare fixed names and data types in a catalog while individual records leave arbitrary columns unpopulated. Support point mutations plus filtered and aliased projection queries with explicit rules for omitted fields and type mismatches.
  2. Out-of-Order Loan Cycle Processor: Consume borrower payment and fee-assessment events that arrive independently, out of sequence, or duplicated across retries. A billing cycle cannot close until both its payment and fee inputs have arrived, and collected funds always satisfy unpaid fees before reducing principal.
  3. Multi-Investor Payment Splits & Scheduling: Allocate collected funds across fractional co-investors under versioned repayment schedules and mid-life ownership transfers without inventing or losing pennies.
  4. Authenticated, Fault-Isolated API Layer: Expose these operations behind a rate-limited, JWT-secured HTTP boundary that calls flaky external dependencies without exhausting worker threads or duplicating financial side effects.

State your assumptions up front regarding durability and read consistency for the sparse store, unique identifiers for events and billing cycles, and how post-close corrections to finalized cycles are authorized and audited.

Scope & Expectations

  • Sparse Row Layout & Query Semantics: Define the schema catalog, sparse record representation, strict type checking, filter behavior on omitted attributes, projection aliasing, and time/space complexity.
  • Idempotent Cycle State Machine & Replay: Specify deduplication keys, billing-cycle state transitions, arrival-order-independent fee-first waterfalls, batched atomic commits, and audited correction rules.
  • Double-Entry Ledger & Exact Allocation: Model immutable zero-sum ledger postings rather than overwriting mutable balances alone, distribute fractional cent remainders deterministically across co-investors, version schedules and ownership intervals, and reconcile bank settlements.
  • Security, Quotas & Resilient Retries: Enforce JWT verification with object/tenant-level authorization, per-principal and per-tenant rate quotas, bulkhead thread pools, and bounded timeouts, circuit breakers, and idempotency checks that prevent duplicate external transfers.

Step-by-step walkthrough

  1. Clarify requirements and financial invariants

    This prompt spans four components—a sparse in-memory store, an out-of-order loan event processor, an investor payment scheduler, and an API boundary—that all serve one overarching goal. In loan-servicing and financial ledger backends, the central challenge is not raw request throughput; it is deterministic correctness—producing the exact same penny-accurate books even when inputs arrive late, out of order, duplicated, or interrupted by crashes.

    Start by stating clear assumptions for the clarifying questions:

    • Durability and consistency of the sparse store: Each shard has a single leader that appends every mutation to a write-ahead log (WAL)—an append-only disk file written before acknowledging a change so a process crash never loses committed data—replicated synchronously to one standby follower, plus periodic snapshots every 10 minutes for fast restarts. Leader reads are strongly consistent (linearizable).
    • Event and period identity: Every incoming event carries a source-generated event_id acting as its idempotency key (a unique identifier ensuring that processing the same message twice has the exact same effect as processing it once). Each business slot is uniquely keyed by (loan_id, period_number, kind) where kind is FEE or PRINCIPAL, and period_number = 1, 2, 3, ... counts monthly billing cycles.
    • Zero-amount events are explicit: A month with no assessed fee still emits FEE = 0 cents, and a missed borrower payment emits PRINCIPAL = 0 cents. Why? Because payments pay fees before principal—until the FEE event arrives, we cannot tell whether $0 or $50 of a borrower's payment must go to fees first!
    • Audited corrections: Finalized periods are never mutated or deleted in place. Fixing a finalized period requires an explicit correction record citing the superseded event, recording the requester and reason (plus dual approval above $1,000), and posting compensating ledger entries.
  2. Estimate scale with back-of-the-envelope math

    Let's size a realistic mid-to-large mortgage servicer managing 1,000,000 active loans across 1,000 institutional investors (averaging 3 co-investors per loan):

    • Loan event rate: 2 events per loan per month (FEE + PRINCIPAL) plus 10% network retries = 2.2M events/month. Even if 60% (1.32M) land inside a 5-day billing window during 8 business hours/day (144,000 seconds), average flow is ~9 events/s, and a 10× burst is ~90 events/s.
    • Ledger volume: Finalizing one period writes ~11 ledger lines (cash, suspense, fee assessment, fee payment, principal reduction, investor claim reduction, and ~3 investor payable splits). That is 11M lines/month, or ~132M lines/year × 150 B ≈ 20 GB/year (~200 GB across a 10-year audit retention window, ~500 GB with indexes).
    • Sparse store memory: 10M loan attribute rows with 200 declared columns in the catalog, but only ~30 populated columns per row on average. Storing only present (col_id, value) pairs takes ~600 B/row ≈ 6 GB RAM (~20 GB if stored densely with 170 empty slots per row).
    • API and remote vendor traffic: 500 requests/s peak (90% reads), where 20% (100 requests/s) fetch live property/tax data from a flaky external vendor (p50 = 200 ms, mean = 300 ms, p99 = 2.0 s, ~1% transient failures).
    Component              Scale Calculation                               Architectural Takeaway
    ----------------------------------------------------------------------------------------------------------
    Loan event processor   ~9 events/s avg, ~90 events/s peak              Tiny CPU load; optimize for clarity
    Financial ledger DB    ~132M rows/yr -> ~20 GB/yr (~500 GB / 10 yrs)   Fits 1 PostgreSQL primary; DO NOT
                                                                           shard ACID financial transactions
    Sparse in-memory store 10M rows x 30/200 cols -> ~6 GB RAM             Fits in memory on 1 leader+follower
    External vendor calls  100 calls/s x 0.3s mean = 30 concurrent calls   Needs isolated thread bulkhead,
                                                                           strict timeouts & circuit breaker
    
  3. Design the HTTP APIs and data models

    Every mutating endpoint requires Authorization: Bearer <JWT>, Idempotency-Key, and (for updates) If-Match: <version> to provide optimistic concurrency control (rejecting an update with 412 Precondition Failed if another writer changed the record's version first).

    1. Sparse Store
      POST   /v1/tables                              { name, columns: { loan_id: "int", rate: "decimal" } }
      POST   /v1/tables/{t}/rows                     { values: {...} }                 -> 201 { row_id, version }
      PATCH  /v1/tables/{t}/rows/{row_id}            { set: {...}, unset: [...] }      (requires If-Match)
      POST   /v1/tables/{t}/query                    { where: [[col, op, val]], select: [[col, alias]] }
    
    2. Loan Events & Periods
      POST   /v1/loans/{loan_id}/events              { event_id, period, kind: "FEE"|"PRINCIPAL", amount_cents }
                                                     -> 202 { status: "queued" | "duplicate" }
      GET    /v1/loans/{loan_id}/events/{event_id}   -> 200 { status: "queued" | "accepted" | "conflict" }
      POST   /v1/loans/{loan_id}/periods/{n}/corrections  { corrects_event_id, new_amount_cents, reason }
    
    3. Schedules & Investor Remittances
      POST   /v1/loans/{loan_id}/schedules           { effective_from_period, lines: [...] }
      POST   /v1/loans/{loan_id}/ownership-transfers { from_investor, to_investor, units, effective_date }
      GET    /v1/investors/{id}/distributions?from=&to=
    

    Notice two deliberate API behaviors: 1. POST /events returns 202 even on duplicate retries, so an upstream service retrying after a network drop succeeds cleanly instead of paging an operator. 2. Conflicting inputs are never "last write wins." If an upstream feed sends a second, different FEE with a new event_id for the same (loan_id, period), the asynchronous processor marks it conflict and routes it to an operations review queue rather than silently overwriting financial state.

    Core PostgreSQL financial schema (all money stored as int64 integer cents, never binary float):

    loan_event     event_id PK, loan_id, period, kind, amount_cents (bigint), payload_hash,
                   status ('accepted' | 'conflict' | 'superseded')
                   UNIQUE (loan_id, period, kind) WHERE status = 'accepted'   -- DB-enforced slot guard!
    period_state   (loan_id, period) PK, status ('OPEN'|'HAS_FEE'|'HAS_PRINCIPAL'|'READY'|'FINALIZED'),
                   fee_cents, principal_input_cents, schedule_version, revision
    loan_balance   loan_id PK, principal_cents, unpaid_fee_cents, overpayment_cents,
                   next_open_period, version                                  -- verified cache of ledger
    ledger_txn     txn_id PK, loan_id, period, source_event_id, correction_id, actor, created_at
    ledger_line    txn_id FK, account, signed_cents (bigint), investor_id     -- SUM(signed_cents) = 0
    schedule       (loan_id, version) PK, effective_from_period, created_by, reason
    ownership      loan_id, investor_id, units (int), effective_from, effective_to
    outbox         outbox_id PK, destination, idempotency_key, payload, sent_at
    idempotency    (tenant_id, principal_id, idem_key) PK, req_hash, state, http_status, resp_body
    
  4. Connect the end-to-end architecture

                     Partner Systems / Internal Ops / Investor Portal
                                        |  HTTPS + JWT + Idempotency-Key
                                        v
            [ API Gateway: TLS, JWT signature check, Redis token-bucket quotas ]
                                        |
                                        v
            [ Stateless API Service ] ===================> [ External Data Vendor ]
              - resource-level tenant check                 (64-thread bulkhead pool,
              - idempotency table check                      2.5s timeout, circuit breaker)
               |                 |                      |
               | CRUD/query      | enqueue by loan_id   | reads, schedules, transfers
               v                 v                      v
      [ Sparse Store ]   [ Kafka: loan_events ]    [ PostgreSQL Primary + Sync Standby ]
       in-memory dicts     32 partitions by          loan_event, period_state, ledger_txn,
       + WAL + follower    hash(loan_id)             ledger_line, ownership, outbox
                                 |                        ^          |
                                 v                        |          v
                         [ Loan Event Workers ] ----------+   [ Outbox Relay ]
                           1 worker per partition              idempotent ACH/wire
                           batches <=500 events in 1 DB txn          |
                                                                     v
                         [ Nightly Reconciler ] <------------ [ Bank API & Statements ]
    

    Two architectural choices keep recovery simple: - Per-loan single-writer ordering: Hashing loan_id to a Kafka partition ensures one worker processes all events for loan 90 sequentially, avoiding lock contention while scaling across 32 workers. - Transactional outbox: Never call an external bank API inside an open database transaction. Instead, write outgoing bank transfer instructions into the outbox table inside the same PostgreSQL commit as the ledger lines; a background relay then sends them with an idempotency key and marks sent_at.

  5. Deep dive 1: Typed sparse store and missing-value semantics

    In the sparse store, each table declares a schema catalog (column_name -> type_name), while each row stores a Python/C++ hash map containing only populated columns. Omitting 170 empty columns costs zero bytes per row, and adding a new optional column updates only the catalog in O(1) time.

    The trickiest design rule is predicate behavior on missing columns. Suppose row 2 omits state completely, and a user filters WHERE state != 'TX'. Should row 2 match? No! Following SQL's three-valued logic (where comparing against an UNKNOWN missing value yields UNKNOWN, which filters treat as false), every value comparison (=, !=, <, <=, >, >=) against an omitted column evaluates to False. Callers who want omitted rows ask explicitly using ("state", "missing", None). Meanwhile, projecting an omitted column in SELECT outputs None under the requested alias.

    Catalog: { "loan_id": "int", "state": "text", "rate": "decimal", "escrow": "bool" }
    Rows:
      r0: { "loan_id": 101, "state": "TX", "rate": Decimal("6.250") }
      r1: { "loan_id": 102, "rate": Decimal("5.750") }               # "state" is omitted
      r2: { "loan_id": 103, "state": "WA" }                          # "rate" is omitted
    
    Query: where = [("rate", ">", Decimal("5.5"))], select = [("loan_id", "id"), ("state", "st")]
      -> r0 matches (6.250 > 5.5)  -> projects {"id": 101, "st": "TX"}
      -> r1 matches (5.750 > 5.5)  -> projects {"id": 102, "st": None}
      -> r2 skipped (missing rate) -> comparison on omitted column is False
    
    import operator
    from decimal import Decimal
    
    # Map declared catalog type names to exact Python runtime types.
    DECLARED_TYPES = {
        "int": int,
        "text": str,
        "decimal": Decimal,
        "bool": bool,
    }
    
    COMPARISON_OPS = {
        "=": operator.eq,
        "!=": operator.ne,
        "<": operator.lt,
        "<=": operator.le,
        ">": operator.gt,
        ">=": operator.ge,
    }
    
    
    class SparseTable:
        """In-memory typed sparse table storing only present columns per row."""
    
        def __init__(self, schema_columns):
            self.columns = dict(schema_columns)       # col_name -> type_name
            self.rows = []                            # list of sparse dicts {col_name: val}
    
        def insert(self, row_data):
            for col_name, value in row_data.items():
                if col_name not in self.columns:
                    raise KeyError(f"Undeclared column: {col_name}")
                expected_type = DECLARED_TYPES[self.columns[col_name]]
                # Use exact `type(value) is` because isinstance(True, int) is True in Python!
                if type(value) is not expected_type:
                    raise TypeError(f"Column {col_name} expects {self.columns[col_name]}")
            self.rows.append(dict(row_data))
    
    
    def validate_query(table, where_clauses, select_aliases):
        """Fail fast in O(P + K) before scanning any of the N rows."""
        for col_name, op_name, literal in where_clauses:
            if col_name not in table.columns:
                raise KeyError(f"Unknown filter column: {col_name}")
            if op_name in ("present", "missing"):
                continue
            if op_name not in COMPARISON_OPS:
                raise ValueError(f"Unsupported operator: {op_name}")
            expected_type = DECLARED_TYPES[table.columns[col_name]]
            if type(literal) is not expected_type:
                raise TypeError(f"Filter literal for {col_name} must be {table.columns[col_name]}")
    
        seen_aliases = set()
        for col_name, alias in select_aliases:
            if col_name not in table.columns:
                raise KeyError(f"Unknown projected column: {col_name}")
            if alias in seen_aliases:
                raise ValueError(f"Duplicate output alias: {alias}")
            seen_aliases.add(alias)
    
    
    def row_matches(row, where_clauses):
        """Evaluate conjunction (AND) of predicates with three-valued missing semantics."""
        for col_name, op_name, literal in where_clauses:
            if op_name == "missing":
                if col_name in row:
                    return False
            elif op_name == "present":
                if col_name not in row:
                    return False
            elif col_name not in row:
                # Any comparison (=, !=, <, >) on an omitted column evaluates to False.
                return False
            else:
                comparator = COMPARISON_OPS[op_name]
                if not comparator(row[col_name], literal):
                    return False
        return True
    
    
    def run_query(table, where_clauses, select_aliases):
        validate_query(table, where_clauses, select_aliases)
        results = []
        for row in table.rows:
            if row_matches(row, where_clauses):
                projected = {}
                for col_name, alias in select_aliases:
                    # Missing columns project cleanly as None under the target alias.
                    projected[alias] = row.get(col_name, None)
                results.append(projected)
        return results
    

    Complexity: Query validation takes O(P + K) time for P predicates and K projected aliases. A full table scan takes O(N × P + M × K) for N rows and M matches. Adding an optional hash index (col_name -> {val -> set(row_id)}) speeds up selective col = literal filters to O(1 + matches) while naturally skipping omitted values.

  6. Deep dive 2: Deterministic loan event state machine and replay

    In the loan cycle processor, each (loan_id, period) progresses through an explicit state machine:

                            [ OPEN ]
                     FEE   /        \   PRINCIPAL
                          v          v
                   [ HAS_FEE ]    [ HAS_PRINCIPAL ]
                          \          /
                PRINCIPAL  \        /  FEE
                            v      v
                           [ READY ]   (both inputs present; waits if any period < n is not FINALIZED)
                               |
                               | all earlier periods 1..(n-1) are FINALIZED
                               v
                         [ FINALIZED ] ---(approved correction)---> [ FINALIZED (revision + 1) ]
    

    Why must period n wait for period n - 1? Suppose period 1 has $9.00 (900 cents) in fees and only $4.00 (400 cents) in payment: the unpaid 500 cents of fees carry forward into period 2! Therefore, period 2's fee-first waterfall cannot compute its split until period 1 closes. Enforcing strict sequential closure (1, 2, 3, ...) plus rejecting conflicting slot inputs guarantees commutativity: all N! arrival permutations of valid events (with arbitrary duplicates mixed in) produce the exact same final balances and ledger postings.

    def allocate_fee_first(payment_cents, unpaid_fee_cents, principal_balance_cents):
        """Waterfall split: pay unpaid fees first, then loan principal, then borrower overpayment."""
        if payment_cents < 0 or unpaid_fee_cents < 0 or principal_balance_cents < 0:
            raise ValueError("Financial amounts must be non-negative integer cents")
        paid_to_fee = min(payment_cents, unpaid_fee_cents)
        remaining_after_fee = payment_cents - paid_to_fee
        paid_to_principal = min(remaining_after_fee, principal_balance_cents)
        overpayment = remaining_after_fee - paid_to_principal
        return paid_to_fee, paid_to_principal, overpayment
    
    
    class LoanEventProcessor:
        """Deterministic single-loan state machine handling duplicates and out-of-order periods."""
    
        def __init__(self, initial_principal_cents):
            self.principal_cents = initial_principal_cents
            self.unpaid_fee_cents = 0
            self.overpayment_cents = 0
            self.next_period = 1                  # lowest period not yet FINALIZED
            self.pending_inputs = {}              # period -> {"FEE": cents, "PRINCIPAL": cents}
            self.seen_events = {}                 # event_id -> (period, kind, amount_cents)
            self.postings = []                    # audit trail: (period, to_fee, to_principal, overpay)
    
        def process_event(self, event):
            event_id = event["event_id"]
            fingerprint = (event["period"], event["kind"], event["amount_cents"])
    
            # 1. Idempotency check: exact retry is a safe no-op; mutated payload is a source bug.
            if event_id in self.seen_events:
                if self.seen_events[event_id] != fingerprint:
                    raise ValueError("Idempotency violation: event_id reused with different payload")
                return "duplicate"
    
            # 2. Reject normal events targeting an already-closed period (must use correction API).
            period = event["period"]
            if period < self.next_period:
                return "conflict_period_already_finalized"
    
            # 3. Quarantine conflicting second events for the same (period, kind) slot.
            period_slot = self.pending_inputs.setdefault(period, {})
            kind = event["kind"]
            if kind in period_slot:
                return "conflict_slot_already_filled"
    
            self.seen_events[event_id] = fingerprint
            period_slot[kind] = event["amount_cents"]
            self._advance_ready_periods()
            return "accepted"
    
        def _advance_ready_periods(self):
            # Close consecutive READY periods starting strictly from self.next_period.
            while True:
                slot = self.pending_inputs.get(self.next_period)
                if not slot or "FEE" not in slot or "PRINCIPAL" not in slot:
                    break
    
                self.unpaid_fee_cents += slot["FEE"]
                to_fee, to_principal, extra = allocate_fee_first(
                    slot["PRINCIPAL"],
                    self.unpaid_fee_cents,
                    self.principal_cents,
                )
                self.unpaid_fee_cents -= to_fee
                self.principal_cents -= to_principal
                self.overpayment_cents += extra
                self.postings.append((self.next_period, to_fee, to_principal, extra))
    
                del self.pending_inputs[self.next_period]
                self.next_period += 1
    

    Concrete out-of-order trace (initial_principal = 200,000 cents):

    Arrival           Status      next_period   State & Explanation
    ------------------------------------------------------------------------------------------------
    P2 = 400c         accepted    1             Period 2 -> HAS_PRINCIPAL (waits for F2 & Period 1)
    F2 = 900c         accepted    1             Period 2 -> READY (both P2, F2 here, but Period 1 open!)
    P1 = 2500c        accepted    1             Period 1 -> HAS_PRINCIPAL
    P1 = 2500c        duplicate   1             Same event_id + payload -> safe no-op
    F1 = 500c         accepted    3             Period 1 closes: fee=500, principal=2000 (unpaid_fee=0)
                                                Period 2 immediately unblocks & closes: fee=400,
                                                principal=0, unpaid_fee=500 carried into Period 3!
    

    Batched DB commits and replay: Each Kafka worker drains up to 500 events (or 20 ms), advances affected loans in memory, and commits loan_event rows, period_state, loan_balance (with WHERE version = old_version to fence zombie workers during Kafka rebalances), ledger_line entries, and outbox rows in one single PostgreSQL transaction—paying only one disk fsync per batch. Only after PostgreSQL commits does the worker commit Kafka offsets. If a worker crashes in between, Kafka redelivers the batch and the event_id check turns already-committed events into harmless duplicates.

  7. Deep dive 3: Double-entry ledger, exact cent splits, and investor schedules

    For investor distributions, overwriting principal_cents = 198000 in place cannot answer why a balance changed or prove no penny vanished. A double-entry ledger records every financial action as an immutable group of signed integer-cent lines whose sum is strictly zero (SUM(signed_cents) == 0), just like conservation of energy: money moves from one bucket to another, never appearing out of thin air.

    Period 1 Ledger Trace (Loan 90: 200,000c principal; Owners: Inv A 50%, Inv B 30%, Inv C 20%)
    Event                      Account                        Signed Cents   Meaning
    ---------------------------------------------------------------------------------------------------
    1. Cash received (P1)      asset:cash_custodial                 +2,500   Custodial bank holds $25
                               liability:borrower_suspense:90       -2,500   Unapplied until finalized
    2. Period 1 finalized      asset:fees_receivable:90               +500   $5 fee billed to loan
       (F1=500, P1=2500;       revenue:servicer_fees                  -500   Servicer fee earned
        fee=500, prin=2000)    liability:borrower_suspense:90       +2,500   Consume $25 suspense
                               asset:fees_receivable:90               -500   Pay off $5 fee first
                               asset:loan_principal:90              -2,000   Borrower owes $20 less
                               liability:investor_pool:90           +2,000   Reduce pool claim by $20
                               liability:payable:investor_A         -1,000   Owe Investor A 50% ($10.00)
                               liability:payable:investor_B           -600   Owe Investor B 30% ($6.00)
                               liability:payable:investor_C           -400   Owe Investor C 20% ($4.00)
       (Check sum of txn #2: +500 -500 +2500 -500 -2000 +2000 -1000 -600 -400 = 0 cents!)
    

    (If a borrower overpays beyond remaining principal, the extra cents stay credited in liability:borrower_overpayment:90 so the sum still equals zero.)

    Exact cent allocation without rounding drift: Suppose 50,000 cents of principal must be split across three equal 1/3 co-investors (1 unit each out of 3 total units). Rounding each share independently (16,666.67 -> 16,667) sums to 50,001 cents—inventing an unbacked penny! Instead, represent ownership as exact integer units (Fraction(units, total_units)) or exact Decimal shares summing to Decimal("1"), floor every investor's share, and distribute the remaining pennies (leftover < num_investors) one by one to the largest fractional remainders (breaking ties deterministically by investor_id):

    import math
    from fractions import Fraction
    
    
    def split_cents_exact(total_cents, unit_holdings):
        """Split integer cents across {investor_id: integer_units} with zero penny drift.
    
        Uses exact rational arithmetic (Fraction) and the largest-remainder rule.
        """
        total_units = sum(unit_holdings.values())
        if total_units <= 0:
            raise ValueError("Total ownership units must be positive")
    
        allocated = {}
        remainders = []
    
        for investor_id, units in unit_holdings.items():
            # Exact rational product: zero binary floating-point rounding error.
            exact_cents = Fraction(total_cents * units, total_units)
            whole_cents = math.floor(exact_cents)
            fractional_part = exact_cents - whole_cents
    
            allocated[investor_id] = whole_cents
            # Negate fractional_part so ascending sort places largest remainders first;
            # investor_id breaks exact ties deterministically (e.g. 1/3 vs 1/3 vs 1/3).
            remainders.append((-fractional_part, investor_id))
    
        remainders.sort()
        leftover_cents = total_cents - sum(allocated.values())
        for idx in range(leftover_cents):
            winner_id = remainders[idx][1]
            allocated[winner_id] += 1
    
        return allocated
    

    For 50,000 cents across {"A": 1, "B": 1, "C": 1}, floors give 16,666 each (49,998), leaving 2 pennies awarded deterministically to "A" (16,667) and "B" (16,667), while "C" gets 16,666—summing to 50,000 exactly.

    Schedule versioning, ownership intervals, and settlement: - Loan modifications create immutable schedule version v + 1 with effective_from_period = k; finalized periods store the schedule_version they used. - Ownership is stored as non-overlapping date intervals [effective_from, effective_to). Each period specifies a contractual record date; finalization snapshots the active owners as of that record date onto the transaction. - On monthly remittance day, a scheduler sums unpaid payable:investor_X lines into a batch keyed deterministically as remit:{investor_id}:{yyyy_mm_dd} and writes an outbox transfer using that batch ID as the bank's idempotency key.

  8. Deep dive 4: API security, quotas, bulkheads, and safe retries

    The HTTP boundary protects the service from unauthorized access, noisy tenants, and cascading vendor slowdowns:

    • JWT authentication + resource-level authorization: Verify signatures against an explicit allowlist of asymmetric algorithms (RS256 or ES256, blocking alg: none spoofing), check iss, aud, and exp (15-minute token lifetime), then enforce object-level ownership: every handler loads the target loan_id or investor_id and verifies record.tenant_id == jwt.tenant_id. Return 404 Not Found (not 403) on cross-tenant mismatches so attackers cannot probe valid loan IDs.
    • Hierarchical quotas: Enforce Redis token buckets (counters that refill at R tokens/second up to a burst cap, spending 1 token per request) at both the user principal level (20 req/s, burst 40) and the tenant level (100 req/s, burst 200, capped at 20% of our 500 req/s total capacity), returning 429 Too Many Requests with Retry-After before one partner's batch script starves other tenants.
    • Thread-pool bulkhead via Little's Law: Never let slow external vendor calls run on the main HTTP worker pool. By Little's Law (average concurrency = arrival rate × mean latency), 100 calls/s × 0.3 s mean = 30 calls in flight on average. (Sizing from the 0.2 s median would give 20 threads and saturate immediately because of the 2.0 s p99 tail!) Isolate vendor calls in a dedicated 64-thread bulkhead pool with a bounded queue of 32; if full, fail fast with 503 on vendor-dependent routes while core ledger APIs stay completely unaffected.
    • Bounded retries, circuit breaker, and zero duplicate side effects:
    Control                     Configuration & Why
    ---------------------------------------------------------------------------------------------------
    Per-attempt timeout         2.5 s (above vendor's 2.0 s p99 so slow healthy calls aren't killed)
    End-to-end request deadline 5.0 s total; attempt k gets min(2.5 s, remaining_deadline)
    Max attempts & backoff      <= 3 attempts; exponential backoff (100 ms, 200 ms) + full random jitter
    Retryable vs fatal errors   Retry timeouts, 5xx, 429; NEVER retry 400/401/403/404/422 client errors
    Retry budget & breaker      Cap retries <= 10% of vendor traffic; open circuit breaker for 30 s if
                                >= 50% of last 20 calls fail, then allow 3 half-open probe requests
    Side-effect safety          Inbound writes deduplicate via PostgreSQL `idempotency` table (409 while
                                IN_PROGRESS, cached response when DONE, 422 on body mismatch). Outbound
                                bank transfers query status by idempotency key after timeouts before retry.
    
  9. Scale bottlenecks, failure recovery, and nightly audit

    Scaling and operational resilience: - Database growth: Partition ledger_line by month in PostgreSQL so closed months become read-only tables backed up cheaply, and serve investor portal reads from read replicas. - Database-enforced immutability: Revoke UPDATE and DELETE privileges from the application database role on ledger_txn and ledger_line (GRANT INSERT, SELECT only). - Stuck-period alerting: If a period stays in HAS_PRINCIPAL (payment received, FEE missing) for > 48 hours, alert operations—later periods for that loan intentionally wait in READY, so a broken fee feed surfaces immediately instead of producing wrong principal splits.

    Failure Scenario                         Deterministic Recovery Behavior
    ---------------------------------------------------------------------------------------------------
    Worker crashes mid-batch                 DB txn rolls back automatically; Kafka redelivers events
    Worker crashes after DB commit           Kafka redelivers; seen `event_id` returns "duplicate" no-op
    Two workers process same loan (rebalance)Optimistic `version` check on `loan_balance` aborts loser
    Sparse store leader crashes              Synchronous WAL follower promotes with zero acked-write loss
    Bank transfer HTTP call times out        Outcome unknown -> query bank transfer status by batch_id
                                             before ever resending; never blindly re-POST money transfers
    Finalized period had wrong upstream fee  Approved correction replays periods n..latest in memory,
                                             computes net delta, and posts balanced adjustment lines
    

    Four nightly reconciliation invariants: Every night, an automated audit job verifies (1) every ledger_txn sums to 0, (2) loan_balance equals SUM(ledger_line) per loan, (3) replaying accepted loan_event history from scratch reproduces loan_balance, and (4) asset:cash_custodial matches the bank's settled statement—freezing remittances on any loan that fails until resolved.

  10. Summarize key design trade-offs

    Design Decision            Chosen Approach                             Cost / Trade-Off Accepted
    ---------------------------------------------------------------------------------------------------
    Accounting storage         Append-only zero-sum ledger + balance cache More rows; requires nightly audit
    Conflicting slot events    Quarantine as `conflict` for ops review     Manual review on upstream bugs
    Period closing order       Strict sequential order (1, 2, 3...)        Missing period-1 fee blocks period 2
    Monetary & share math      int64 cents + exact Fraction/Decimal        Explicit largest-remainder code
    Sparse store missing cols  SQL 3-valued False on all comparisons       `col != x` skips missing rows
    Database topology          Single ACID PostgreSQL primary + standby    Vertical ceiling (~thousands/s),
                                                                           ideal for ~90/s financial events
    External side effects      Transactional outbox + status-before-retry  Slight async delay + relay worker
    

Intuition & how it works

Think of this system like an accountant's ink-only ledger paired with a two-key monthly lockbox for each loan. You never erase a number with pencil: every payment, fee, investor split, or correction is recorded as a new permanent row of signed integer cents whose entries sum to zero (an append-only double-entry ledger). Meanwhile, each month's billing cycle acts like a lockbox that waits until both its FEE event and its PRINCIPAL payment event have arrived (an explicit period state machine), closing months strictly in sequence (1, 2, 3...) regardless of what order the network delivers the messages.

The naive approach—updating a mutable principal_balance float as events stream in and calling external APIs directly inside request handlers—breaks under every real-world failure mode. Network retries double-count payments unless guarded by an idempotency key (a unique client-generated ID per event), closing period 2 before period 1 ignores unpaid period-1 fees that should carry forward, and binary floating-point rounding (0.1 + 0.2 != 0.3) invents or loses pennies across co-investors. Worse, letting slow third-party vendor calls share the main request thread pool or retry blindly turns a brief upstream hiccup into hung API servers and duplicate bank wires.

Walk through a concrete 5-message trace for loan L90 (200,000 cents principal; investors A 50%, B 30%, C 20%) when inputs arrive scrambled: 1. P2 = 400 cents and F2 = 900 cents arrive first: period 2 has both inputs and enters READY, but waits because period 1 is still open. 2. P1 = 2,500 cents arrives, followed by an exact network retry of P1 = 2,500 with the same event_id: the first moves period 1 to HAS_PRINCIPAL, and the retry is acknowledged as a harmless duplicate no-op. 3. Finally F1 = 500 cents arrives: period 1 closes immediately (500 cents pay fees first, 2,000 cents reduce principal and split cleanly as 1,000 / 600 / 400 cents to investors A/B/C), which immediately unblocks period 2 to close right behind it (400 cents pay part of F2, leaving 500 cents of unpaid fee carried into period 3).

Key trade-offs

  • Append-only double-entry ledger vs. mutable balance columns. Storing immutable zero-sum ledger_line entries makes every penny auditable and lets corrections append compensating entries without erasing history, at the cost of more database rows and a nightly reconciliation job verifying that the cached loan_balance table matches SUM(ledger_line).
  • Quarantining conflicting inputs vs. last-write-wins. Routing a second, different FEE for an already-populated (loan_id, period) slot to a conflict review queue guarantees arrival-order independence and surfaces upstream bugs, trading away fully automated recovery when an upstream system sends contradictory numbers.
  • Strict sequential period finalization vs. independent periods. Closing periods strictly in order (1, 2, 3...) accurately rolls unpaid fees from period n into period n + 1 and makes replays deterministic, at the cost that one missing FEE event in period 1 holds period 2 in READY (mitigated by 48-hour stuck-period alerts).
  • Integer cents + largest-remainder Fraction splits vs. independent rounding. Representing money as int64 cents and ownership as exact integer-unit fractions (units / total_units) distributed via the largest-remainder rule guarantees investor payouts always sum to the exact penny collected, trading off a tiny deterministic tie-break bias toward lower-sorted investor IDs on exact fractional ties (such as 1/3 each).
  • SQL three-valued missing semantics vs. default values in the sparse store. Evaluating any comparison (= and != alike) on an omitted column as False prevents silently fabricating financial attributes and lets equality indexes skip absent fields naturally, though query authors must use explicit missing / present operators when searching for omitted columns.
  • Single PostgreSQL primary + transactional outbox vs. distributed shards. At ~90 peak events/s and ~20 GB/year, keeping the financial ledger on one ACID PostgreSQL primary with a synchronous standby gives rock-solid multi-table transactions without distributed two-phase commit overhead, while pushing external bank calls to an asynchronous transactional outbox (a database queue committed atomically alongside ledger rows).

Common mistakes

  • Using IEEE-754 float for money or rounding each investor's share independently, causing cumulative penny mismatches where debits and credits fail to sum to zero.
  • Finalizing a period as soon as a payment arrives or assuming a missing FEE event means $0, which misallocates principal when a delayed fee arrives minutes later.
  • Using isinstance(val, int) when validating typed sparse columns in Python, forgetting that bool is a subclass of int (isinstance(True, int) is True!).
  • Treating col != 'TX' as True when col is missing, violating three-valued logic and returning unpopulated rows as false positives.
  • Checking event_id existence without verifying the payload hash, silently masking severe upstream bugs where a sender reuses an ID for a completely different event.
  • Calling a bank transfer API inside an open database transaction or blindly retrying a timed-out payment POST without first querying transfer status by idempotency key.
  • Checking only JWT scopes (loans:read) without checking resource tenant ownership (loan.tenant_id == token.tenant_id), opening an Insecure Direct Object Reference (IDOR) vulnerability across tenants.
  • Sizing external vendor thread pools from median latency instead of mean latency, under-provisioning workers when a 2-second p99 tail pushes average concurrency higher via Little's Law (L = rate × mean_latency).

Follow-up questions

  • If the typed sparse store grows beyond the memory of one leader-follower pair, how would you partition it across multiple nodes? Hash rows consistently on tenant_id (or loan_id for cross-tenant workloads) into ~256 fixed virtual shards assigned across physical leader-follower pairs so cluster expansions migrate whole virtual shards without rehashing individual rows. Every shard manages its own in-memory hash maps, synchronous WAL, and local equality indexes, while the small schema catalog replicates to every node with a monotonic catalog_version checked before applying writes. Single-tenant or single-loan lookups route directly to one shard, whereas cross-shard scans push both where predicates and select projections down to all shards in parallel (scatter-gather) so the coordinator merges only compact projected results.
  • Suppose an upstream payment error in a closed billing period is discovered after one co-investor has already sold its stake to another—how do you book the correction? Never mutate historical ledger entries or apply today's ownership split to an earlier period's adjustment. Instead, an authorized correction replays periods n through the latest closed period in memory with the amended figure while allocating each period's principal delta across the historical ownership snapshot recorded on that period's original record date. Diffing the recomputed distributions against the previously posted lines produces one zero-sum compensating transaction tied to correction_id. If seller A received an overpayment prior to transferring units to buyer B, B's balances stay untouched while A's payable account is debited (or converted into an investor_receivable clawback claim if A has no pending remittances left to offset).

Follow-up questions

Similar questions

More Valon interview questions

All 8 Valon questions →