Scalable Startup Loan Origination Platform

Hard · System Design · Software Engineer · Onsite

Prompt

Design an end-to-end credit origination system built for an early-stage fintech lender with room to scale substantially over the next few years. Applicants discover eligible financing options, complete a multi-step submission, undergo automated and human-assisted credit evaluation backed by third-party bureau files and bank-account records, receive a binding credit outcome, and have approved proceeds transferred to their bank account.

Scope & Expectations

  • Product discovery and intake APIs: Model how borrowers browse eligible credit offerings, save progress across sessions, provide required authorizations, and submit verifiable identity and financial records.
  • Underwriting orchestration and external data feeds: Design a durable workflow that coordinates third-party credit-report pulls and bank-statement or transaction ingestion alongside internal human review queues.
  • Replayable decisioning and safe payouts: Detail how automated rules, risk models, and manual underwriters produce auditable credit decisions, and how approved loans move funds to verified accounts without duplicate transfers.
  • Pragmatic startup scalability: Justify architectural boundaries, storage choices, security controls, and failure recovery appropriate for a lean engineering team preparing for multi-fold growth.

Step-by-step walkthrough

  1. Clarify requirements and startup scope

    An early-stage lender's origination pipeline spans product discovery, multi-session submission, external bureau and bank-record collection, automated plus human evaluation, credit decisioning, and payout execution. Before sketching boxes, confirm the business and regulatory rules—because in lending, correctness around money, compliance, and multi-day workflows matters far more than raw HTTP request volume.

    Assumed scope confirmed with the interviewer

    • Target borrowers: US small businesses (sole proprietors up to ~50 employees). An owner applies on behalf of the company and signs a personal guarantee, so underwriting evaluates both business bank cash flow and the owner's personal credit history.
    • Loan products: fixed-term loans ($5k–$250k, 6–24 months) and revolving lines of credit ($5k–$100k). Launching or repricing a product should be a versioned configuration change rather than a code deployment.
    • Channels: our first-party web application today, plus embedded partner platforms calling the exact same public API tomorrow.
    • Funding rails: loans are funded from our credit facility via a partner bank's API using ACH (Automated Clearing House — the US batch bank-to-bank transfer system that settles in hours to days and can bounce later if an account is closed), with wires reserved for manual exceptions.
    • Out of scope: post-funding loan servicing (monthly repayments and collections, handed off via a loan.funded event) and offline ML training infrastructure.

    Functional requirements

    1. Filter and display eligible loan products based on business state, industry, and requested amount.
    2. Support multi-session draft intake: business and owner details, explicit legal consents, live bank-account linking (or PDF bank-statement uploads), and identity documents.
    3. Fetch external underwriting data: KYC (Know Your Customer — verifying the owner's personal identity), KYB (Know Your Business — verifying legal registration and ownership), sanctions watchlists, personal credit reports (soft pull — a score-neutral inquiry — during underwriting; hard pull — a formal inquiry visible to other lenders — only if required at acceptance), and 12 months of bank transactions.
    4. Run automated underwriting when clear; route borderline or flagged files to human underwriters who can approve, decline, or request additional documents.
    5. Present binding offers, capture e-signatures on loan agreements, disburse net proceeds to a verified business bank account, and notify the applicant (including legally mandated adverse-action notices explaining the specific principal reasons for any denial).

    Non-functional requirements

    • Monetary safety: never disburse a loan twice, never fund an unsigned or unverified application, and reconcile every cent daily.
    • Workflow durability: applications can pause for days awaiting documents or signatures without losing state across server restarts or deploys.
    • Latency: automated decision p95 under 2 minutes when a bank account is linked; 90% of manual reviews completed within 1 business day; same-day ACH payout when signed before the daily bank cutoff.
    • Auditability & security: replay any historical decision from frozen inputs and versions years later; encrypt and tokenize SSNs, tax IDs (EINs), and bank account numbers; maintain 99.9% intake API availability.
  2. Back-of-the-envelope numbers

    Sizing for 10x our initial launch volume (roughly 2 years of startup growth) reveals what actually needs engineering focus—and what does not.

    Daily Funnel (10x Startup Target; Today = 1/10th)
      Applications started            5,000 / day      (today ~500 / day)
      Completed & submitted           2,000 / day      40% completion rate
        -> Auto-declined                800 / day      40% of submitted (knockouts or high risk)
        -> Auto-approved                500 / day      25% of submitted
        -> Routed to manual review      700 / day      35% of submitted (~50% approved -> 350)
      Total offers presented           ~850 / day      (500 auto + 350 manual)
      Offers signed & funded           ~500 loans/day  ~60% acceptance rate
      Daily money disbursed           500 x $20k avg   ~$10M / day ($3.6B / year run rate)
    
    Traffic & External Calls
      Submit rate (over 10 biz hrs)   200 / hour (~0.056 / s avg; 10x marketing burst ~0.6 / s)
      Status & workbench reads        ~20 - 50 reads / s at peak
      Vendor calls per submission     KYC(1) + KYB(1) + sanctions(1-2) + soft credit(~1.3 owners)
                                      + bank history(1-2) + fraud(1) -> ~7 calls -> ~14k calls/day
    
    Human Underwriting Workload
      700 manual files x 20 min each  14,000 min = ~233 hours/day -> ~39 underwriters (at 6h/day)
      Today's 1/10th volume           ~23 hours/day -> ~4 underwriters
      10% shift from manual to auto   200 files x 20 min = ~67 hours/day saved (~11 underwriters!)
    
    Annual Storage Footprint
      Bank transactions               12 mo x 300 txns x 250 B = ~0.9 MB/app -> 1.8 GB/day -> ~650 GB/yr
      Uploaded PDFs & ID images       ~3 MB/app avg -> 6 GB/day -> ~2.2 TB/yr in object storage
      Raw credit bureau reports       1,500 apps reaching credit (75%) x 1.3 owners = 1,950 pulls/day
                                      x 100 KB = ~195 MB/day -> ~71 GB/yr
      PostgreSQL structured rows      ~50 KB/app -> ~100 MB/day -> ~36 GB/yr
    

    Three architectural lessons from the math

    1. Write QPS is tiny (< 1 submission/s at peak). A single PostgreSQL primary handles this load effortlessly for years. Splitting day-one code into 15 microservices would burn a small startup team on distributed-transaction bugs for zero scalability benefit.
    2. People and paid vendor APIs dominate operating cost. Raising automation by 10% saves ~11 full-time underwriters, and skipping $1.50–$2.00 soft credit pulls on the 25% of submissions (500 apps x 1.3 owners = 650 pulls/day) that fail free/cheap checks saves ~$1,000–$1,300/day (~$400k/year).
    3. The genuinely hard problems are durable multi-week state management, race-free parallel data collection, explainable/replayable credit decisions, and sending $10M/day out at most once per loan.
  3. API design: product selection, multi-session intake, and workbench

    Applicant & Embedded Partner API (OAuth2 for partners, session auth for web)
    GET   /v1/products?state=TX&industry=5812&amount=50000
          -> [{product_id, version, type, amount_range, term_options, price_range, requirements}]
    POST  /v1/applications                        (Idempotency-Key)
          {product_id, requested_amount, purpose} -> 201 {application_id, status: "DRAFT", required_actions[]}
    PATCH /v1/applications/{id}                   save business/owner fields; SSN/EIN go to PII vault first
    POST  /v1/applications/{id}/consents          {type: "credit_pull" | "bank_data" | "esign", text_version}
    POST  /v1/applications/{id}/bank-links        {aggregator_public_token} -> {link_id, accounts[]}
    POST  /v1/applications/{id}/documents         {type} -> {doc_id, upload_url (15-min pre-signed S3 URL)}
    POST  /v1/applications/{id}/submit            (Idempotency-Key) -> 202 {status: "SUBMITTED"}
    GET   /v1/applications/{id}                   -> {status, required_actions[], offers[], decline_notice?}
    POST  /v1/applications/{id}/offers/{oid}/accept (Idempotency-Key) -> {agreement_signing_url}
    POST  /v1/applications/{id}/withdraw
    
    Internal Underwriter Workbench API (SSO, RBAC, every view audit-logged)
    GET   /internal/review-queue?queue=standard&sort=sla_due -> prioritized tasks with SLA & amount
    POST  /internal/review-tasks/{task_id}/claim             -> 30-minute exclusive lease
    GET   /internal/applications/{id}/file                   -> masked PII, cash-flow summary, decision trace
    POST  /internal/applications/{id}/decisions
          {action: "approve" | "decline" | "request_info", offer_terms?, reason_codes[], note}
    
    Inbound Vendor Webhooks (HMAC-verified, deduplicated by vendor event_id)
    POST  /hooks/bank-data   |   POST /hooks/kyc   |   POST /hooks/esign   |   POST /hooks/bank-partner
    

    Key API design choices

    • Server-driven required_actions[] on drafts: Instead of hard-coding intake steps in frontend JavaScript, the server computes what is still missing (["record_credit_consent", "link_bank_or_upload_statements"]) from the pinned product version, allowing our web app and external partners to share one unified API.
    • Idempotency keys on mutating calls: An idempotency key (a client-generated unique token stored alongside the first response) turns double-clicks and flaky mobile retries on create, submit, and accept into safe replays.
    • Direct PII vaulting: Raw SSNs and EINs go straight to an isolated PII vault (a locked tokenization service that swaps sensitive strings for random lookup tokens like ssn_tok_91c), keeping raw secrets out of application tables and logs.
  4. Data model

    We store transactional state in PostgreSQL (primary + synchronous standby + read replica) and large raw vendor payloads/PDFs in encrypted object storage referenced by URI and SHA-256 digest.

    product            product_id, version, type, states[], industries_excluded[], amount_min, amount_max,
                       terms[], pricing_grid, policy_id, active_from, active_to      PK (product_id, version)
    business           business_id, legal_name, ein_token, state, industry_code, formed_on
    person             person_id, name, dob_token, ssn_token, address_token, email, phone
    application        application_id PK, business_id, product_id, product_version, requested_amount,
                       channel, partner_id, status, version, idempotency_key UNIQUE, submitted_at, decided_at
    application_event  application_id, seq, from_status, to_status, actor, reason, at   PK (application_id, seq)
    consent            consent_id, person_id, application_id, type, text_version, ip, user_agent, at
    task               task_id, application_id, type, status (queued | running | done | failed),
                       run_at, lease_until, attempts, idempotency_key UNIQUE, last_error
    external_report    report_id, application_id, subject_id, vendor, kind (kyc | kyb | sanctions |
                       credit_soft | credit_hard | bank_txns | bank_pdf), request_key UNIQUE,
                       status, raw_uri, raw_sha256, attributes jsonb, schema_version, pulled_at, valid_until
    bank_link          link_id, business_id, aggregator, access_token_ref, account_ids[], owner_names[]
    decision           decision_id, application_id, kind (auto | manual), outcome (approve | decline | refer),
                       policy_version, model_version, features jsonb, score, reason_codes[],
                       input_report_ids[], decided_by, at                              -- append-only
    offer              offer_id, application_id, decision_id, amount, term_months, rate_or_factor,
                       origination_fee, payment, expires_at, status (open | accepted | expired | void)
    review_task        review_id, application_id, queue, priority, sla_due_at, claimed_by,
                       lease_until, status, first_approver
    agreement          agreement_id, offer_id, envelope_id, signed_doc_uri, sha256, signer_person_id, signed_at
    loan               loan_id, application_id UNIQUE, offer_id, principal, fee, net_proceeds,
                       bank_account_token, status (pending_funding | active | funding_failed | cancelled)
    disbursement       disbursement_id, loan_id, amount, rail, bank_account_token, idempotency_key UNIQUE,
                       partner_ref, status (created | submitting | unknown | submitted | settled | returned | failed),
                       lease_until, first_attempt_at, return_code, at
    ledger_entry       entry_id, journal_id, loan_id, account, debit, credit, at   -- sum(debit)=sum(credit)
    outbox             event_id, topic, payload, created_at
    
    • Current status + append-only history: application.status gives fast O(1) indexed lookups, while application_event gives an immutable audit trail and funnel-latency telemetry.
    • Immutable external_report: Every decision stores input_report_ids[], ensuring an audit or model backtest replays the exact vendor snapshot used at decision time.
    • Clean money boundary: loan, disbursement, and ledger_entry interact with intake/underwriting only through IDs and domain events so they can later be extracted into a dedicated treasury service without schema surgery.
  5. High-level architecture and application state machine

    For a small lending startup, we build a modular monolith (a single deployable service divided into strict internal code packages sharing one database, avoiding cross-service distributed transactions while keeping clean boundaries for future extraction):

       Applicant Web App        Partner Platforms                  Underwriters
               |                        |                                |
               v                        v                                v
       [ API Gateway: Auth, WAF, Per-Partner Quotas ]        [ Workbench UI: SSO, RBAC ]
               |                                                         |
               v                                                         v
       +--------------------------- Lending Core (Modular Monolith) ---------------------------+
       |  Product Catalog  |  Intake & Drafts  |  Workflow Engine (State + Tasks + Timers)     |
       |  Review Queues    |  Decision Engine  |  Offers & E-Sign  |  Disbursement & Ledger    |
       +---------------------------------------------------------------------------------------+
           |                 |                      |                        |             |
           v                 v                      v                        v             v
       [ PostgreSQL    ] [ Encrypted S3  ] [ Integration Gateway ]     [ ML Scoring ] [ PII Vault ]
       [ Primary +     ] [ Raw reports & ] [ Per-vendor adapters ]     [ Stateless  ] [ + KMS     ]
       [ Sync Standby  ] [ PDF uploads   ] [ Breakers & retries  ]     [ PD + SHAP  ]
                                                    |
                                                    v
                         Credit Bureau | Bank Aggregator | PDF Parser | KYC/KYB |
                         OFAC Sanctions | E-Sign Vendor | Partner Bank (ACH/Wire)
    
       Outbox Relay -> Event Bus -> Notifications (Email/SMS), Servicing Handoff, Data Warehouse
    

    Application lifecycle state machine

     DRAFT --submit--> SUBMITTED --> COLLECTING_DATA --all required reports ready--> DECIDING
                                          |     ^                                       |
                            missing docs  v     | applicant uploads                     |
                                      NEEDS_INFO (10-day timer -> INCOMPLETE)           |
                                                                                        |
                +-----------------------------------+-----------------------------------+
                | approve                           | refer                             | decline
                v                                   v                                   v
             OFFERED <---------approve--------- IN_REVIEW ----------decline--------> DECLINED (send Reg B notice)
                |                                   |
                |--14-day timer--> OFFER_EXPIRED    +--request info--> NEEDS_INFO
                |
                +--accept--> ACCEPTED --e-sign + pre-funding gate--> FUNDING --settled--> FUNDED
                                                                        |
                                                              ACH return / rejected
                                                                        v
                                                                 FUNDING_FAILED --new verified account--> FUNDING
    
     Interruptions: WITHDRAWN (applicant, pre-FUNDING), SECOND_REVIEW (manual approvals > $100k),
     and COMPLIANCE_HOLD (potential sanctions match; cleared or blocked solely by compliance).
    

    End-to-end walkthrough of a typical $50,000 application

    1. Owner selects a $50,000 term loan after GET /v1/products confirms their state and restaurant NAICS code qualify.
    2. Across two browser sessions, the owner enters business/owner details (SSN tokenized in vault), signs credit/bank consents, and links their business checking account.
    3. On submit, the workflow moves to COLLECTING_DATA and enqueues parallel tasks for KYB, KYC, sanctions, and bank transactions—holding back the paid soft credit pull until cheap checks pass.
    4. As each vendor task completes, it writes an external_report; the final required task transitions the application to DECIDING.
    5. decide() runs knockouts, scores cash-flow and bureau features, and either generates 1–3 term offers (OFFERED), declines with specific reasons (DECLINED), or opens an underwriter review_task (IN_REVIEW).
    6. The owner accepts an offer and e-signs; pre-funding checks pass, creating the loan and disbursement (FUNDING).
    7. When the partner bank confirms settlement, the loan moves to active (FUNDED), ledger cash settles, and loan.funded hands repayment schedules to servicing.
  6. Deep dive 1: Durable underwriting workflow and the join-barrier race

    Because a single application blends sub-second code, multi-minute webhooks, multi-hour human reviews, and 14-day expiration timers, every state transition must be atomic, crash-resilient, and free of race conditions.

    Rule 1: Atomic optimistic state transitions + transactional outbox

    Every state change updates application using optimistic locking (WHERE status = :expected AND version = :version) and inserts its audit row, next task, and outbox event inside one SQL transaction:

    BEGIN;
    UPDATE application
    SET status = 'DECIDING', version = version + 1, updated_at = now()
    WHERE application_id = :id AND status = 'COLLECTING_DATA' AND version = :version;
    -- If 0 rows updated: a webhook, timer, or underwriter moved it first -> ROLLBACK & reload!
    
    INSERT INTO application_event (application_id, seq, from_status, to_status, actor, reason, at)
    VALUES (:id, :version + 1, 'COLLECTING_DATA', 'DECIDING', 'system', 'all_reports_ready', now());
    
    INSERT INTO task (task_id, application_id, type, status, run_at, idempotency_key)
    VALUES (:task_id, :id, 'run_decision', 'queued', now(), :id || ':run_decision:' || (:version + 1))
    ON CONFLICT (idempotency_key) DO NOTHING;
    
    INSERT INTO outbox (event_id, topic, payload) VALUES (:event_id, 'application-events', :payload);
    COMMIT;
    

    Subtle concurrency trap — the parallel join-barrier bug: Suppose KYC and bank-transaction tasks finish at the exact same millisecond. Under PostgreSQL's default READ COMMITTED isolation (where a query only sees rows committed before that statement began), watch what happens if each worker simply inserts its report and checks if all reports are present:

    Without row lock (BROKEN):                           With SELECT ... FOR UPDATE on application (SAFE):
      Worker A (KYC)           Worker B (Bank)             Worker A (KYC)           Worker B (Bank)
      ----------------------   ----------------------      ----------------------   ----------------------
      BEGIN;                   BEGIN;                      BEGIN;                   BEGIN;
      INSERT kyc report;       INSERT bank report;         SELECT app FOR UPDATE;   SELECT app FOR UPDATE;
      SELECT reports:          SELECT reports:             INSERT kyc report;         (waits for A's lock)
       sees KYC only ->         sees Bank only ->          SELECT reports -> only 1
       "missing Bank, stop"     "missing KYC, stop"        COMMIT; (releases lock)
      COMMIT;                  COMMIT;                                              (acquires lock!)
      --> Application stuck in COLLECTING_DATA forever!                             INSERT bank report;
                                                                                    SELECT reports -> BOTH!
                                                                                    Advances to DECIDING!
    

    Optimistic locking on UPDATE cannot save the left side because neither worker ever attempts the UPDATE! Locking the parent application row (SELECT ... FOR UPDATE) before inserting each report serializes completions per application cleanly, backed up by a 10-minute sweeper for stuck COLLECTING_DATA rows.

    Rule 2: Leased worker queue with FOR UPDATE SKIP LOCKED and future timers

    Workers poll PostgreSQL using FOR UPDATE SKIP LOCKED (a SQL row-locking modifier that skips rows already locked by other workers so 20 workers can pull tasks concurrently with zero lock contention):

    UPDATE task
    SET status = 'running', lease_until = now() + interval '2 minutes', attempts = attempts + 1
    WHERE task_id IN (
        SELECT task_id FROM task
        WHERE run_at <= now()
          AND (status = 'queued' OR (status = 'running' AND lease_until < now()))
        ORDER BY run_at
        LIMIT 20
        FOR UPDATE SKIP LOCKED
    )
    RETURNING task_id, application_id, type, idempotency_key;
    
    • Crash recovery: If a worker dies mid-task, lease_until expires after 2 minutes and another worker safely retries the idempotent task using exponential backoff with jitter.
    • Zero-cancellation timers: Presenting an offer inserts a task type = 'expire_offer' with run_at = expires_at (14 days out). When it fires, it tries OFFERED -> OFFER_EXPIRED: if the borrower already accepted, status = 'OFFERED' matches 0 rows and the timer finishes as a harmless no-op.
    • Human review in the same model: Underwriters claim review_task rows with 30-minute renewable leases, and loans above $100,000 enforce a four-eyes rule (approver != first_approver) directly inside the conditional SQL transition.
  7. Deep dive 2: Credit-bureau and bank-statement integrations

    External data calls cost money, carry legal consent rules, fail unpredictably, and return messy vendor-specific schemas. We isolate them behind an Integration Gateway with one adapter per vendor owning timeouts, circuit breakers (pausing calls when a vendor's error rate spikes), and bulkheads (per-vendor concurrency limits so a slow credit bureau cannot starve fast KYC calls).

    Safe, cost-aware pull protocol

    1. Hard consent gate: The gateway refuses any bureau or bank call unless a matching consent row exists for (person_id, application_id, current_text_version).
    2. 30-day reuse window: If a valid soft pull for the same owner is < 30 days old (and allowed by contract + fresh consent), reuse it for zero cost—covering retries and NEEDS_INFO loops automatically.
    3. Pre-call request_key reservation: Insert external_report(request_key = 'credit_soft:' || person_id || ':' || app_id, status = 'requested') before calling out. On an ambiguous network timeout, query the vendor by reference first; never auto-retry a hard credit pull (route unresolved hard-pull timeouts to operations so an owner never gets two inquiries).
    4. Archive raw bytes first: Stream the encrypted raw JSON/XML + SHA-256 to object storage before parsing into attributes (schema_version), so parser bug fixes can re-extract features offline without re-paying vendors.
    5. Cheap-before-paid staging:
    Step 1 (Free)    Form eligibility: supported state, industry, amount, >= 6 months in business
    Step 2 (Cheap)   KYB registration + KYC identity + OFAC sanctions screening on business & owners
    Step 3 (Bank)    Bank transaction pull -> early cash-flow knockout (e.g., avg deposits < $10k/mo)
    Step 4 (Paid)    Soft credit pull on each 25%+ beneficial owner (skipped for the ~25% failing Steps 1-3!)
    Step 5 (Post-sign) Hard credit pull (if required by product), executed only after offer acceptance
    

    Bank statements: linked aggregator vs. PDF fallback, and cash-flow hygiene

    • Linked bank account (preferred): Owner authenticates in the aggregator widget; historical transactions arrive via webhook (backed by a +15 min polling task if the webhook drops) along with verified account-holder names used later at payout.
    • Uploaded PDFs (fallback): Parsed by a document vendor with font/metadata tamper checks. Because PDFs can be doctored, policy routes all PDF-only files to IN_REVIEW—never auto-approving them.
    • Cash-flow normalization trap: Every raw line item is categorized (revenue_deposit, self_transfer, loan_proceeds, loan_repayment, nsf_fee, payroll) before computing avg_monthly_revenue, revenue_volatility, avg_daily_balance, nsf_count_90d (NSF = Non-Sufficient Funds / bounced-payment fees), and existing_debt_payments (recurring debits to rival lenders signaling loan stacking). Filtering out transfers between the owner's own accounts and deposits from other loans is essential—counting them as revenue is the #1 bug that over-sizes small-business loans.
  8. Deep dive 3: Replayable decisioning, affordability math, and adverse-action reasons

    We implement decide() as a pure deterministic function (zero network or database reads inside) over immutable external_report records and versioned policy/model configs:

    def decide(app, reports, policy, model):
        """Pure function: identical app + immutable reports + policy/model versions -> identical Decision."""
        knockout_reasons = []
        for rule in policy.knockout_rules:
            if rule.fails(app, reports):
                knockout_reasons.append(rule.reason_code)
        if knockout_reasons:
            return Decision("DECLINE", reasons=knockout_reasons[:4])
    
        features = build_features(app, reports)          # Normalized cash-flow + bureau vector
        pd_12m, contributions = model.score(features)    # 12-month probability of default + feature impacts
        band = policy.risk_band(pd_12m)
        if band is None:
            return Decision("DECLINE", reasons=policy.top_reasons(contributions, 4), features=features)
    
        offers = policy.build_offers(app, features, band)
        if not offers:
            return Decision("DECLINE", reasons=["CASH_FLOW_INSUFFICIENT"], features=features)
    
        refer_reasons = policy.referral_reasons(app, reports, features, pd_12m)
        if refer_reasons:
            return Decision("REFER", reasons=refer_reasons, offers=offers, features=features)
        return Decision("APPROVE", offers=offers, features=features)
    
    • Cold-start ML progression: A young lending startup lacks thousands of matured defaults, so launch with an interpretable logistic scorecard (or bureau score + cash-flow policy grid) and graduate to monotonic gradient-boosted trees once loan cohorts mature, keeping per-feature contributions for explainability.
    • Concrete affordability sizing: Risk band sets pricing; cash flow caps loan size. For example, if policy caps monthly debt payments at 10% of avg_monthly_revenue, a business earning $80,000/month supports $8,000/month ($96,000 over 12 months). At a factor rate of 1.15 (a small-business pricing convention where total payback equals 1.15 x principal), maximum principal is $96,000 / 1.15 = $83,478 (capped further by requested amount and product max).
    • Regulation B adverse-action compliance: Every knockout rule and model feature maps to human-readable principal reason codes (never "model score too low"), due within 30 days for consumer and <= $1M-revenue small-business applicants. Offering $30,000 when $50,000 was requested is a counteroffer: if OFFER_EXPIRED fires without acceptance, the system automatically sends a counteroffer adverse-action notice within the 90-day regulatory window.
    • Safe policy & model rollouts: Before activating a new policy_version or model_version, backtest-replay the last 5,000 historical applications to inspect approval/amount diffs, run in shadow mode on live traffic, and verify fair-lending parity (zero protected-class inputs and proxy-variable disparity checks).
  9. Deep dive 4: Disbursing funds at most once, net proceeds, and ledger accounting

    Moving $10M/day over external bank APIs requires defending against network timeouts, bounced ACH transfers, and last-second payout-account takeover.

    1. Pre-funding security gate (ACCEPTED -> FUNDING): Verify unexpired offer matching the e-signed PDF hash, fresh sanctions check (<= 7 days), payout bank account identical to the linked underwriting account with matching business legal name (any post-approval account swap forces manual fraud review), refreshed 30-day bank balances on loans > $50k to catch last-minute loan stacking, and available room on our capital facility.

    2. Atomic loan, disbursement, and ledger creation: For a $50,000 loan (5,000,000 cents) with a 2% origination fee ($1,000) withheld from proceeds, net payout is $49,000 (4,900,000 cents):

    BEGIN;
    UPDATE application SET status = 'FUNDING', version = version + 1
    WHERE application_id = :app_id AND status = 'ACCEPTED' AND version = :version;
    -- 0 rows -> already funding or cancelled -> ROLLBACK!
    
    INSERT INTO loan (loan_id, application_id, offer_id, principal, fee, net_proceeds, bank_account_token, status)
    VALUES (:loan_id, :app_id, :offer_id, 5000000, 100000, 4900000, :acct, 'pending_funding');
    
    INSERT INTO disbursement (disbursement_id, loan_id, amount, rail, bank_account_token, idempotency_key, status)
    VALUES (:disb_id, :loan_id, 4900000, 'same_day_ach', :acct, :disb_id, 'created');
    
    INSERT INTO outbox (event_id, topic, payload) VALUES (:event_id, 'loan-events', :payload);
    COMMIT;
    
    -- Partial unique index guarantees at most ONE live disbursement per loan at the database level:
    CREATE UNIQUE INDEX one_live_disbursement ON disbursement (loan_id)
    WHERE status IN ('created', 'submitting', 'unknown', 'submitted', 'settled');
    

    3. Crash-safe payout execution & double-entry ledger: - A worker atomically claims a created (or expired-lease unknown) row by setting status = 'submitting' and lease_until = now() + 2 min before calling the partner bank API with Idempotency-Key = disbursement_id. - On HTTP timeout or 5xx, the worker sets status = 'unknown'—never failed—and queries the partner bank's lookup endpoint by disbursement_id before resending within the bank's idempotency-key window (escalating to finance ops if still unresolved past that window). It never creates a second disbursement row for a timeout retry. - Every money event writes balanced integer-cent rows to our double-entry ledger:

    Event                        Account Debit                    Account Credit
    ---------------------------------------------------------------------------------------------
    Disbursement submitted       loans_receivable     $50,000     cash_clearing          $49,000
                                                                  unearned_fee_income     $1,000
    Partner bank settles         cash_clearing        $49,000     operating_cash         $49,000
    ACH return (R02/R03/R04)     operating_cash       $49,000     cash_clearing          $49,000
                                 cash_clearing        $49,000     loans_receivable       $50,000
                                 unearned_fee_income   $1,000
    

    An hourly invariant check verifies that cash_clearing equals the exact sum of submitted (unsettled) disbursements, and daily three-way reconciliation matches ledger rows, partner-bank settlement files, and bank statements. Only after an ACH return (R02 closed account, R03 no account) marks the prior row returned does the partial unique index permit creating a new disbursement row to a newly verified account.

  10. Scaling, bottlenecks, observability, and failure handling

    • Database & storage longevity: Keep multi-MB JSON/PDFs in S3, partition application_event and task monthly, run workbench search on read replicas, and stream Change Data Capture (CDC) to an analytics warehouse so model training never touches the OLTP primary.
    • Campaign & partner bursts: Intake is a fast local write; SKIP LOCKED queues and per-vendor concurrency caps smooth 10x traffic spikes while per-partner fairness quotas prevent one embedded partner's bulk batch from starving direct web applicants.
    • Service extraction roadmap: Keep the modular monolith until team size or compliance scope justifies extracting Disbursement & Ledger first (tightest security boundary), followed by the Integration Gateway.
    • High-signal observability: Alert on applications stuck past state SLAs, open vendor circuit breakers, manual-review SLA risk, sudden jumps in auto-approval rate, unknown payouts, and cash_clearing or daily reconciliation breaks.
    Failure Scenario                          System Response & Recovery
    ----------------------------------------------------------------------------------------------------
    Bureau or KYC outage                      Breaker opens; tasks backoff on run_at; escalate to manual
                                              review after 24h policy cap (never auto-decline!)
    Lost bank-aggregator or e-sign webhook    Scheduled +15 min polling task fetches latest vendor state
    Worker crashes mid-task                   2-min lease expires; next worker safely replays via keys
    Two parallel reports finish together      SELECT ... FOR UPDATE on application serializes completion
    ML scoring service down                   Hold in DECIDING; route to manual review after 15 min
    Partner bank timeout on ACH credit        Mark unknown -> lookup by idempotency_key before resending
    Production policy bug discovered          Replay affected decisions via immutable input_report_ids
    PII vault temporarily unreachable         Drafts save non-PII; tasks needing raw SSN backoff & wait
    
  11. Summary of key design trade-offs

    • Modular monolith + single PostgreSQL vs. microservices: Gives atomic state/task/outbox transactions and fast startup iteration at < 1 req/s, requiring strict internal package boundaries until disbursement splits out.
    • PostgreSQL SKIP LOCKED tasks + FOR UPDATE barrier vs. external workflow engine: Eliminates extra cluster ops and makes stuck workflows queryable in one SQL statement, trading away built-in workflow engine UIs.
    • Free/cheap checks before paid bureau pulls: Saves ~$400k/year in vendor fees and avoids needless credit inquiries at 10x scale, adding ~2 seconds to the happy path.
    • Linked bank accounts vs. uploaded PDFs: Linked accounts enable <2-minute auto-decisions and payout ownership checks; accepting PDFs broadens customer reach at the cost of mandatory manual underwriting to block doctored statements.
    • Simple interpretable scorecard first vs. complex ML on day one: Avoids overfitting scarce startup default data and produces clean Regulation B adverse-action reasons until enough loan cohorts mature.
    • Strict pre-funding gate + partial unique payout index: Adds brief pre-payout checks and human review on account changes in exchange for eliminating duplicate payouts and mule-account fraud.

Intuition & how it works

Think of a startup's loan application platform like a well-organized single-building workshop (a modular monolith) built around one master ledger clipboard: when a small-business owner applies for a $50,000 loan, the intake desk gives them a checklist (required_actions[]) they can complete across multiple visits, locking sensitive IDs like SSNs inside a separate PII vault (an isolated security service that swaps raw secrets for random lookup tokens). Once submitted, background workers pull tasks off a shared PostgreSQL conveyor belt using FOR UPDATE SKIP LOCKED (a SQL lock modifier that lets workers grab separate queued tasks concurrently without blocking one another), seal every external credit and bank report into an immutable evidence bag, run a pure calculator function decide() that outputs offers or legally compliant denial reasons, and pass signed loans to a payout desk guarded by a database rule allowing at most one live transfer per loan.

Why do the obvious approaches fail? Splitting day-one code into a dozen microservices forces distributed-transaction headaches onto a small startup whose peak load is under 1 submission/second. Worse, running external KYC, credit, and bank calls inside a synchronous submit endpoint times out browsers and double-pulls credit on retries—while running them in parallel background workers without locking the parent application row causes a silent race condition where two simultaneously finishing workers each think the other is still running, leaving the application stuck forever. Finally, counting transfers between an owner's own accounts as business revenue or retrying a timed-out bank transfer with a brand-new ID loses real capital fast.

Let's trace one $50,000 term-loan application (app-101, 2% origination fee) step by step:

1. Product selection & multi-session intake:
   GET /v1/products?state=TX&industry=5812&amount=50000 -> pins product ("term_loan", version=3).
   Owner saves draft, vaults SSN -> "ssn_tok_4a", records consents, links checking account, clicks Submit.
   -> Atomic SQL commit: status = COLLECTING_DATA, version = 1, enqueues free/cheap tasks first.

2. Staged external pulls & the FOR UPDATE join barrier:
   -> KYB + KYC + OFAC sanctions pass -> enqueues soft credit pull + bank-history fetch in parallel.
   -> Credit pull and bank webhook finish at the exact same millisecond:
      Both run SELECT ... FROM application WHERE application_id = 'app-101' FOR UPDATE.
      Worker 1 commits credit_soft first; Worker 2 acquires lock next, sees BOTH reports committed,
      and atomically advances app-101 to DECIDING (version = 2) + enqueues run_decision.

3. Replayable decision & affordability sizing:
   -> Normalized deposits (excluding self-transfers) = $80,000/mo -> 10% payment cap = $8,000/mo.
   -> Over 12 months at 1.15 factor rate, max affordable loan = ($8,000 * 12) / 1.15 = $83,478 >= $50,000.
   -> decide() approves $50,000 -> status = OFFERED (with 14-day expire_offer timer task).

4. Pre-funding gate & at-most-once net payout:
   -> Owner e-signs -> pre-funding gate confirms payout account matches the linked Texas business account.
   -> One SQL transaction creates loan ($50k principal, $1k fee, $49k net) + disbursement "disb-101-1".
   -> Worker leases "disb-101-1" (submitting), sends $49,000 Same-Day ACH with Idempotency-Key="disb-101-1".

5. Double-entry settlement:
   -> Submitted: Debit loans_receivable $50k | Credit cash_clearing $49k + unearned_fee_income $1k.
   -> Settled:   Debit cash_clearing $49k    | Credit operating_cash $49k -> loan status = active (FUNDED).

Key trade-offs

  • Modular monolith with one PostgreSQL database vs. microservices. A modular monolith (one deployable binary organized into strict internal modules sharing one database) lets a state transition, its next queued task, and its outbox row (an event table committed in the same SQL transaction for reliable async publishing) succeed or roll back atomically at < 1 write/s. Microservices would introduce distributed sagas for zero throughput benefit; the trade-off is enforcing strict code boundaries so disbursement and ledger can split out cleanly later.
  • PostgreSQL leased task table vs. an external durable workflow engine. Storing states and future-dated timer rows (run_at) in PostgreSQL requires zero extra infrastructure and lets engineers find every stuck file with one SQL query. A dedicated workflow engine (such as Temporal) provides built-in history UIs and complex branching primitives, at the cost of operating another stateful cluster.
  • Staged free-to-paid checks vs. firing every vendor call at once. Running free eligibility, KYB/KYC, OFAC sanctions screening (US Treasury watchlists), and bank-deposit knockouts before paid credit-bureau pulls saves ~$400k/year at 10x scale and avoids unnecessary credit inquiries, adding only ~2 seconds to passing applications.
  • Linked bank aggregator vs. uploaded PDF bank statements. Live aggregator links verify account ownership for payout and enable < 2 minute automated underwriting. Accepting uploaded PDFs rescues applicants at unsupported small banks, but because PDFs can be tampered with, routing all PDF-only files to manual review trades underwriter hours for wider borrower reach.
  • Interpretable scorecard first vs. complex ML models on day one. With few historical defaults at launch, a logistic scorecard or bureau-plus-cash-flow policy grid avoids overfitting and maps directly to adverse-action reason codes (specific denial explanations mandated by US Regulation B). Gradient-boosted trees improve risk ranking once thousands of loans mature, provided per-feature contributions are preserved for legal notices.
  • Immutable vendor snapshots and pure decide() vs. storing outcomes only. Archiving encrypted raw payloads, feature vectors, and input_report_ids[] costs object-storage space (~3 TB/year), in exchange for exact regulatory auditability and offline policy-diff backtesting before every rule release.
  • Strict pre-funding gate and Same-Day ACH vs. instant payouts. Re-checking account ownership, refreshing 30-day bank balances on loans > $50k, and using Same-Day ACH (cheap batch bank transfers up to $1M, subject to 2-day return codes like R02 closed account) adds minutes to hours before settlement, blocking mule-account takeovers and last-minute loan stacking (borrowing from several lenders simultaneously).

Common mistakes

  • Over-engineering for high QPS while neglecting workflow races and money invariants: Adding database shards and caching layers for 0.6 submissions/s while forgetting idempotency keys, audit trails, or double-entry accounting.
  • Calling credit bureaus and bank aggregators synchronously inside POST /submit: A 45-second bank pull times out HTTP clients, and retries trigger duplicate bureau fees and inquiries.
  • Checking "are all parallel reports finished?" without locking the application row: Under READ COMMITTED isolation, two workers finishing together each miss the other's uncommitted report, leaving the application stranded in COLLECTING_DATA forever.
  • Unconditional status updates (SET status = ... WHERE id = ...): Without AND status = :expected AND version = :version, an offer-expiration timer and an applicant's signature can overwrite each other into contradictory states.
  • Counting self-transfers or other lenders' loan proceeds as business revenue: Raw bank deposits routinely include transfers between checking/savings accounts or rival loan disbursements, dangerously inflating affordability limits if not categorized out.
  • Retrying a timed-out payout or hard credit pull without checking vendor state first: Creating a new disbursement row on timeout risks sending $49,000 twice, and auto-retrying an ambiguous hard pull adds duplicate inquiries that lower the owner's credit score.
  • Vague denial notices or forgotten counteroffer notices: Sending "declined by risk model" violates Regulation B, as does forgetting to send an adverse-action notice when a smaller counteroffer expires unsigned.
  • Storing raw SSNs, EINs, or bank routing/account numbers in PostgreSQL, logs, or analytics tables.

Follow-up questions

  • How would you roll out a daily sales-linked financing product with minimal backend code changes? Add a new versioned product configuration specifying eligible states/industries, required data kinds (card_processor_txns alongside bank_txns), factor-rate pricing grids, and policy_id. The intake checklist and workflow orchestrator already read required data kinds dynamically from the product version, so the only new code needed is a gateway adapter for the card processor API (such as Stripe or Square) and the daily split-settlement schedule in the downstream servicing system. Roll out behind a partner/state allow-list after replaying historical files in shadow mode.
  • How can the team validate and launch a new credit risk model when loan defaults take six to twelve months to surface? Validate offline on matured historical cohorts (checking both ranking AUC and predicted-vs-actual default calibration across risk bands) plus fair-lending disparity audits, then backtest-replay the last several thousand applications to inspect approval-rate and loan-size shifts. Next, score live traffic in shadow mode (recording predictions without affecting real decisions) to verify feature pipeline stability, shift 5–10% of live traffic via canary with instant rollback to the pinned prior model_version, and track early delinquency indicators—such as First Payment Default (FPD) and 30+ days past due at 60–90 days on book—rather than waiting a full year.
  • What layered controls would you add to catch loan stacking, synthetic identities, and doctored PDF bank statements? Catch loan stacking by scanning bank transactions for recurring debits to known lenders or sudden round-number loan deposits, checking recent credit-bureau inquiry velocity, and refreshing the latest 30 days of bank data right before funding loans over $50k. Catch synthetic and stolen identities by cross-checking SSN issuance/DOB history via KYC step-up (ID + live selfie) and flagging shared devices, IPs, phones, or bank accounts across separate business applications. Catch doctored PDFs by preferring live aggregator links, running PDF metadata/font tamper detection plus running-balance arithmetic checks (opening_balance + credits - debits == closing_balance), and routing every PDF-only or fraud-flagged file to human review rather than auto-approving.

Follow-up questions

Similar questions

More Parafin interview questions

All 2 Parafin questions →