Online Loan Origination and Disbursement Architecture

Hard · System Design · Software Engineer · Onsite

Prompt

Architect a complete loan origination platform for a growing digital lender. Prospective borrowers browse several credit offerings, pick one that fits their needs, and submit an application. Behind the scenes, the platform evaluates creditworthiness by combining proprietary underwriting logic with external data feeds—specifically credit-bureau reports and linked bank-ledger histories—before issuing a decision and moving capital.

Walk through how the platform takes an application from initial draft to funded loan or formal rejection, how internal human reviewers step in on borderline files, and how the system stays reliable, auditable, and compliant when external vendors slow down or traffic spikes.

Scope & Expectations

  • System boundaries, schemas, and execution model: Define core services, database entities, external/internal APIs, queue pipelines, and the lifecycle state machine, explicitly contrasting which stages run synchronously versus asynchronously and why.
  • Decision outcomes and money movement: Trace both approval and decline workflows along with downstream obligations—offer acceptance, regulatory denial disclosures, and safe disbursement of loan proceeds to the borrower's bank account.
  • Third-party resilience and traffic management: Cover idempotency guarantees, timeout tiers, retry policies, rate limiting, partial-failure recovery across external vendor calls, horizontal scaling, and backpressure during demand surges.
  • Risk controls, data security, and operations: Explain identity and anti-money-laundering (KYC/AML) verification, fraud detection, PII protection, immutable compliance auditing, internal manual-review tooling, and production observability.

Step-by-step walkthrough

  1. Clarify requirements and frame the problem

    At first glance, a loan application looks like a web form that ends in "yes" or "no". In production, it is a long-running financial workflow that coordinates external vendors, human reviewers, and real money: identity and credit bureaus that can be slow or down, bank-statement pulls that take minutes, human underwriting queues measured in hours, and bank transfers that settle over days and can bounce later. Our core engineering job is making every step safe to retry, every credit decision reproducible years later, and every dollar accounted for.

    Assumptions to confirm with the interviewer

    • Borrowers: US small businesses applying through an owner who personally guarantees the loan. This requires both KYB (Know Your Business — verifying that the company legally exists and identifying its owners) and KYC (Know Your Customer — verifying each owner's personal identity). A consumer-only lender drops KYB, while keeping the exact same workflow architecture.
    • Loan products: fixed-term loans (6–24 months), lines of credit, and revenue-based financing (repaid as a fixed percentage of daily sales). Because products differ in eligibility, pricing, and repayment rules, products are stored as immutable versioned configurations, not hard-coded if statements.
    • Underwriting inputs: a personal credit report on the owner (soft pull — a credit check that does not affect the applicant's credit score — during underwriting, and a hard pull — a formal credit inquiry visible to other lenders — only after consent at offer acceptance), a business credit report, and 12–24 months of bank transactions from a bank-data aggregator.
    • Money movement: the platform holds an operating account at a partner bank and uses a payment provider API supporting ACH (Automated Clearing House — the US batch bank-transfer network that settles in hours to days and can return funds later if an account is closed) as well as instant payment rails. Capital sourcing and post-funding loan servicing (monthly collections) are out of scope after the initial handoff.

    Functional requirements

    • Browse loan products, run an instant self-reported eligibility pre-check, and save/resume a draft application across sessions.
    • Link a business bank account (or upload PDF statements as a fallback), record legal consents, upload documents, and submit.
    • Run automated KYC/KYB, sanctions watchlist screening, fraud checks, credit and bank-transaction collection, and underwriting.
    • Auto-approve, auto-decline, or route borderline/flagged applications to a manual review workbench where underwriters can approve (within authority limits), decline with structured reasons, or request extra documents.
    • Present binding offers, collect an electronic signature, disburse funds to a verified bank account, and hand the funded loan to servicing.
    • Send applicant notifications, including legally required adverse-action notices (written disclosures telling a declined applicant the specific principal reasons their application was denied).

    Non-functional requirements

    • Zero duplicate payouts and zero lost dollars: at most one active disbursement per loan, backed by a balanced ledger and daily bank reconciliation.
    • Zero accidental duplicate vendor charges or credit inquiries: bureau calls cost money, and duplicate hard pulls hurt the borrower's credit score.
    • Full decision reproducibility: given the stored input snapshot, policy version, and model version, re-running a decision years later must produce the exact same outcome and reason codes.
    • Latency targets: automated decisions within 5 minutes at p90 (dominated by bank-history fetching); manual reviews within 1 business day; same-day ACH payout when signed before the daily bank cutoff.
    • Security and compliance: PII (Personally Identifiable Information — sensitive data such as Social Security numbers and bank account numbers) encrypted and tokenized, least-privilege access audited, and capacity for 10x growth via graceful queueing rather than errors.
  2. Back-of-the-envelope numbers

    Let's size the platform for both a realistic starting point today and a 10x growth target so we can see where the real bottlenecks sit.

    Metric                                            Today              10x Target
    ------------------------------------------------------------------------------------
    Applications started per day                      10,000             100,000
    Applications submitted per day                    2,000              20,000
    Average submissions/s (submitted / 86,400 s)      ~0.023 / s         ~0.23 / s
    Peak submissions/s (marketing campaign = 5x avg)  ~0.12 / s          ~1.2 / s
    Status poll reads/s (active applicants + UI)      ~5 / s             ~50 / s
    
    External API calls per submitted application:
      KYC + KYB (owner + business)                    2
      Sanctions screening (business + beneficials)    2 - 4
      Credit bureaus (owner soft pull + business)     2
      Bank aggregator (token, accounts, txns)         3  (history arrives 10 s - 5 min later)
      Fraud & device intelligence                     1
      E-signature + payment rails (accepted offers)   4  (only for the ~21% that fund)
      Upper-bound total per submission                ~15 calls -> ~300k/day, ~18-20/s at 10x peak
    
    Assumed vendor rate limits (contract quotas):
      Credit bureau                                   10 requests/s
      KYC vendor                                      20 requests/s
      Bank-data aggregator                            25 requests/s
    
    Storage:
      Bank history + raw reports per submission       2k-10k txns -> ~4 MB raw JSON (~0.8 MB compressed)
      Daily raw archive at 10x (20,000 x 4 MB)        ~80 GB/day raw -> ~16 GB/day compressed
      5-year compliance archive (16 GB x 365 x 5)     ~29.2 TB (~30 TB compressed in object storage)
    
    Human manual review:
      20% manual review rate x 15 min (0.25 h) each   Today:  2,000 x 0.20 x 0.25 h = 100 h/day (~13 staff)
                                                      Target: 20,000 x 0.20 x 0.25 h = 1,000 h/day (~125 staff)
    
    Money disbursed:
      35% approved x 60% offer accepted = 21% funded  Today:  420 loans/day x $20k avg = $8.4M/day
                                                      Target: 4,200 loans/day x $20k avg = $84M/day
    

    What these numbers tell us about the architecture

    1. Database write QPS is tiny. Even at 10x peak, 1.2 submissions/s fits comfortably on a single relational primary database. Sharding the database or splitting into 20 microservices for throughput would add complexity for zero benefit; we separate modules strictly for security boundaries, ownership, and failure isolation.
    2. Applications spend 99% of their lifetime waiting: minutes for bank history, hours for an underwriter, and days for ACH settlement. Holding open an HTTP request across those waits would time out on mobile networks and deploys, so the system must run as an asynchronous, database-backed workflow.
    3. Vendor quotas bite during outage recovery, not steady state. At 10x peak, steady credit pulls use 1.2 submissions/s x 2 calls = 2.4 calls/s against a 10 calls/s bureau cap. However, a 1-hour bureau outage at peak queues 2.4 x 3,600 = 8,640 credit calls. If we cap our recovery rate at 8.0 calls/s (80% of quota) while 2.4 calls/s of new peak traffic keeps arriving, the net drain rate is 8.0 - 2.4 = 5.6 calls/s, taking 8,640 / 5.6 = 1,543 s (~26 minutes) to clear—and nightly portfolio re-pulls must yield priority during that window.
    4. Every duplicate side effect is costly. One duplicate payout risks $20,000, and one duplicate hard credit pull damages an owner's credit file. Strict idempotency is mandatory at every boundary.
    5. Underwriter time scales linearly with volume. At 20,000 submissions/day, improving the auto-decision rate by just 1 percentage point saves 200 cases x 0.25 h = 50 reviewer-hours/day. Model quality and review UI ergonomics are first-class scaling levers.
  3. API design and abuse rate limiting

    We expose three clean API surfaces: public endpoints for applicants, internal endpoints for reviewers, and inbound webhook endpoints (HTTP callbacks that external vendors call when slow tasks finish).

    Applicant API (authenticated; all mutating calls require an Idempotency-Key header)
    GET   /v1/products                              -> active product versions and terms
    POST  /v1/eligibility                           -> instant pre-check on self-reported inputs (no vendor calls)
    POST  /v1/applications                          -> 201 {application_id, state: "DRAFT"}
    PATCH /v1/applications/{id}                     -> save draft sections; raw SSN/EIN go straight to PII vault
    POST  /v1/applications/{id}/bank-links          -> exchange aggregator public_token for vaulted access token
    POST  /v1/applications/{id}/documents           -> pre-signed upload URL directly to encrypted object storage
    POST  /v1/applications/{id}/consents            -> record {type, text_version} with timestamp and IP
    POST  /v1/applications/{id}:submit              -> 202 {state: "SUBMITTED"}
    GET   /v1/applications/{id}                     -> {state, next_action, estimated_decision_at}
    GET   /v1/applications/{id}/offers              -> binding offer options once approved
    POST  /v1/offers/{offer_id}:accept              -> 202 {state: "OFFER_PRESENTED", next_action: "sign", esign_url}
    POST  /v1/applications/{id}:withdraw            -> cancel before funds move
    
    Internal Reviewer API (corporate SSO, role-based access, audit-logged)
    POST  /internal/review/queues/{queue}:claim     -> lease highest-priority case to this reviewer for 30 min
    GET   /internal/review/cases/{case_id}          -> structured evidence with sensitive PII masked by default
    POST  /internal/review/cases/{case_id}/reveal   -> {field, reason} unmasks one PII field and writes audit log
    POST  /internal/review/cases/{case_id}:decide   -> {outcome, reason_codes[], amount, notes}
    POST  /internal/review/cases/{case_id}:request-info -> {items[]} creates applicant task and pauses review
    
    Provider Webhooks (HMAC signature verified, deduplicated, answered immediately)
    POST  /webhooks/bank-data                       -> historical bank transactions ready
    POST  /webhooks/esign                           -> loan agreement signed or declined
    POST  /webhooks/payments                        -> payout submitted, settled, or returned (with ACH return code)
    

    Why each API choice matters

    • 202 Accepted on :submit and :accept: Persist the intent, enqueue background work, and return immediately. Clients poll GET /v1/applications/{id} (or subscribe via Server-Sent Events). Fast applications still show an offer on the same screen within 30–60 seconds; slow ones fall back cleanly to an email notification.
    • Idempotency keys on every write: An idempotency key is a unique client-generated UUID sent in the request header. The gateway stores (user_id, key, request_hash, response) for 24 hours: a network retry replays the original response, while reusing the same key with a different payload returns 422 Unprocessable Entity.
    • Explicit consent records: Storing text_version, timestamp, and IP proves years later which exact authorization wording the owner agreed to before a credit pull or ACH debit/credit.
    • Fast, deduplicated webhooks: Webhook handlers verify the vendor's cryptographic signature and timestamp, insert the raw payload keyed by provider_event_id (ON CONFLICT DO NOTHING), enqueue a worker job, and return 200 OK in milliseconds so vendors do not time out and flood us with retries.
    • Abuse-focused rate limiting: Using a token bucket (a counter per key that refills steadily and blocks excess bursts with 429 Too Many Requests + Retry-After), we enforce limits such as 5 new applications per device/IP per day, 10 bank-link attempts per user per day (blocking attackers from testing stolen bank logins), and 60 status polls per user per minute. Heavy rate-limit hits also emit a fraud signal onto the application.
  4. Data model and the application state machine

    A relational database (PostgreSQL) is our single source of truth because money and workflow state transitions require ACID transactions and uniqueness constraints. Multi-megabyte raw vendor responses and uploaded PDFs live in encrypted object storage, referenced from PostgreSQL by URI and SHA-256 hash.

    loan_product      product_id, version, kind (term_loan | line_of_credit | revenue_based),
                      min_amount, max_amount, terms[], eligibility_rules, pricing_rules,
                      effective_from, effective_to                  -- immutable once published
    business          business_id, legal_name, ein_token, formation_state, naics, start_date
    person            person_id, name_token, dob_token, ssn_token, address_token
    business_owner    business_id, person_id, ownership_pct, is_controller, is_guarantor
    application       application_id, business_id, product_id, product_version,
                      amount_requested, term_requested, state, held_from, version,
                      submitted_at, decided_at
    application_event application_id, seq, from_state, to_state, actor, reason, at   -- append-only
    consent           consent_id, application_id, person_id, type, text_version, ip, at
    external_call     call_id, application_id, provider, purpose, idempotency_key UNIQUE,
                      status (pending | ok | failed | unknown), attempts, response_ref, cost_cents
    kyc_result        application_id, subject_id, cip_status, watchlist_status, matches_ref, checked_at
    bank_connection   connection_id, business_id, provider, access_token_ref, account_mask,
                      owner_name_on_account, verified_at
    bank_features     application_id, months_covered, avg_monthly_revenue, revenue_volatility,
                      avg_daily_balance, nsf_count, existing_debt_payments, computed_at
    decision          decision_id, application_id, outcome, amount, price, term,
                      reason_codes[], policy_version, model_version, features_snapshot_ref,
                      decided_by (system | reviewer_id), decided_at
    review_case       case_id, application_id, queue, priority, assignee, lease_until, sla_due, status
    offer             offer_id, decision_id, amount, price, term, expires_at, status,
                      esign_envelope_id, signed_doc_hash
    loan              loan_id, offer_id UNIQUE, principal_cents, status, servicing_ref
    disbursement      disbursement_id (<offer_id>-<attempt>), loan_id, amount_cents, rail,
                      account_token, provider_payment_id, status, lease_until, first_attempt_at, return_code
                      UNIQUE (loan_id) WHERE status NOT IN ('FAILED', 'RETURNED', 'CANCELLED')
    ledger_entry      entry_id, txn_id, account, debit_cents, credit_cents, at   -- balanced per txn_id
    outbox            id, topic, payload, created_at, published_at
    

    State machine lifecycle

    Only the orchestrator module may mutate application.state:

    DRAFT
      -> SUBMITTED
      -> SCREENING (eligibility, KYC/KYB, sanctions, fraud)
           -> COMPLIANCE_HOLD (possible sanctions match)
           -> MANUAL_REVIEW   (weak identity match or fraud flag)
           -> AUTO_DECLINED   (hard eligibility knockout)
      -> DATA_COLLECTION (credit bureau + bank history in parallel)
      -> UNDERWRITING (policy rules + risk model)
           -> AUTO_APPROVED ---------------------------------------------+
           -> MANUAL_REVIEW -> APPROVED ---------------------------------+
                            -> DECLINED ---------------+                 |
                            -> INFO_REQUESTED -> DATA_COLLECTION         |
           -> AUTO_DECLINED ---------------------------+                 |
                                                       v                 v
                                           ADVERSE_ACTION_SENT     OFFER_PRESENTED
                                                                     -> OFFER_EXPIRED (14-day timer)
                                                                     -> ACCEPTED (e-signature confirmed)
                                                                     -> FUNDING_PENDING (pre-funding checks pass)
                                                                          -> FUNDING_FAILED (ACH return)
                                                                               -> FUNDING_PENDING (new verified acct)
                                                                          -> FUNDED -> handed to servicing
    
    Interruptions from any pre-funding active state:
      -> WITHDRAWN (by applicant)
      -> FRAUD_HOLD or COMPLIANCE_HOLD (saves interrupted state in held_from; releasing restores held_from)
    

    To prevent race conditions when two events arrive at the same millisecond (for instance, an applicant clicking "Withdraw" right as underwriting finishes), we use optimistic locking (a conditional UPDATE ... WHERE state = expected that succeeds for exactly one caller) combined with a transactional outbox (inserting the outbound queue message inside the same database transaction as the state update so events are never lost or emitted prematurely):

    import json
    
    ALLOWED = {
        "DRAFT": {"SUBMITTED", "WITHDRAWN"},
        "SUBMITTED": {"SCREENING"},
        "SCREENING": {"DATA_COLLECTION", "MANUAL_REVIEW", "AUTO_DECLINED"},
        "DATA_COLLECTION": {"UNDERWRITING", "MANUAL_REVIEW"},
        "UNDERWRITING": {"AUTO_APPROVED", "AUTO_DECLINED", "MANUAL_REVIEW"},
        "MANUAL_REVIEW": {"APPROVED", "DECLINED", "INFO_REQUESTED", "DATA_COLLECTION"},
        "INFO_REQUESTED": {"DATA_COLLECTION"},
        "AUTO_APPROVED": {"OFFER_PRESENTED"},
        "APPROVED": {"OFFER_PRESENTED"},
        "AUTO_DECLINED": {"ADVERSE_ACTION_SENT"},
        "DECLINED": {"ADVERSE_ACTION_SENT"},
        "OFFER_PRESENTED": {"ACCEPTED", "OFFER_EXPIRED"},
        "ACCEPTED": {"FUNDING_PENDING"},
        "FUNDING_PENDING": {"FUNDED", "FUNDING_FAILED"},
        "FUNDING_FAILED": {"FUNDING_PENDING"},
    }
    
    # Before funds are in flight (FUNDING_PENDING), the applicant can withdraw and compliance/risk can hold.
    HOLDABLE = [
        "SUBMITTED", "SCREENING", "DATA_COLLECTION", "UNDERWRITING", "MANUAL_REVIEW",
        "INFO_REQUESTED", "AUTO_APPROVED", "APPROVED", "OFFER_PRESENTED", "ACCEPTED", "FUNDING_FAILED",
    ]
    for active_state in HOLDABLE:
        ALLOWED[active_state] = ALLOWED[active_state] | {"WITHDRAWN", "FRAUD_HOLD", "COMPLIANCE_HOLD"}
    
    HOLDS = {"FRAUD_HOLD", "COMPLIANCE_HOLD"}
    for hold_state in HOLDS:
        ALLOWED[hold_state] = set(HOLDABLE) | {"DECLINED"}
    
    
    def transition(db, application_id, expected, new_state, actor, reason):
        """Atomically advance state, record audit history, and enqueue the next workflow event."""
        if new_state not in ALLOWED.get(expected, set()):
            raise ValueError(f"illegal transition {expected} -> {new_state}")
    
        with db.transaction():
            if expected in HOLDS and new_state != "DECLINED":
                # Releasing a hold may ONLY return to the exact state stored in held_from,
                # so a hold placed in SCREENING can never jump forward to ACCEPTED.
                row = db.execute(
                    "UPDATE application SET state = %s, held_from = NULL, version = version + 1 "
                    "WHERE application_id = %s AND state = %s AND held_from = %s RETURNING version",
                    (new_state, application_id, expected, new_state),
                ).fetchone()
            else:
                held_from = expected if new_state in HOLDS else None
                row = db.execute(
                    "UPDATE application SET state = %s, held_from = %s, version = version + 1 "
                    "WHERE application_id = %s AND state = %s RETURNING version",
                    (new_state, held_from, application_id, expected),
                ).fetchone()
    
            if row is None:
                return False  # Another worker changed state first; caller reloads and re-evaluates.
    
            seq = row[0]
            db.execute(
                "INSERT INTO application_event (application_id, seq, from_state, to_state, actor, reason) "
                "VALUES (%s, %s, %s, %s, %s, %s)",
                (application_id, seq, expected, new_state, actor, reason),
            )
            db.execute(
                "INSERT INTO outbox (topic, payload) VALUES (%s, %s)",
                ("application.state_changed",
                 json.dumps({"id": application_id, "state": new_state, "seq": seq})),
            )
        return True
    

    Because the background outbox relay can crash after publishing a message to the queue and before setting published_at, queue delivery is at-least-once. Consumers ignore any event whose seq is older than application.version, and every downstream step is idempotent.

  5. High-level architecture: synchronous vs. asynchronous boundaries

       Applicant (Web / Mobile)              Reviewers (Workbench)            External Vendors
                  |                                    |                             |
       [ Edge: TLS, WAF, Bot Defense ]       [ Corporate SSO + MFA ]     [ Webhook Receiver: verify HMAC,
                  |                                    |                   dedupe event_id, store raw, 200 ]
       [ API Gateway: Auth, Token-Bucket Rate Limits, Idempotency Keys ]             |
                  |                                    |                             |
       ========= SYNCHRONOUS BOUNDARY (validate, write DB + outbox, return 202) =====|==============
                  |                                    |                             |
       [ Application Service ]   [ Product Catalog ]  [ Review Service ]             |
         drafts, submit, status    versioned rules      queues, 30m leases           |
                  |                     |                    |                       |
                  +---------------------+--------------------+-----------------------+
                                        | (outbox relay -> durable queue with delayed retries)
       ========= ASYNCHRONOUS BOUNDARY (workers driven by state machine & timers) ==================
                                        v
                 [ Workflow Orchestrator: owns application.state & SLA timers ]
                   |              |               |                 |                  |
                   v              v               v                 v                  v
             [ KYC / AML ] [ Data Fetch ]   [ Fraud Svc ]   [ Decision Engine ] [ Funding Service ]
               CIP, KYB,     bureaus +        device, IP,     knockouts, PD       pre-funding gate,
               sanctions     bank history     graph links     model, reasons      payouts, ledger
                   |              |               |                                    |
                   +--------------+---------------+                                    v
                                  v                                       [ Payment Provider ] -> ACH / RTP
                  [ Vendor Adapter Layer (1 per provider) ]               [ Double-Entry Ledger ]
                    token bucket, circuit breaker, timeouts,
                    idempotency, raw S3 archive, cost meter
    
       Shared Security & Data Plane:
         [ PII Vault + KMS ]   [ Encrypted Object Store (raw JSON/PDFs) ]
         [ Hash-Chained Audit Log (WORM storage) ]   [ Pseudonymized Analytics Warehouse ]
    

    Synchronous vs. asynchronous processing — justified step by step

    Workflow stage Execution mode Justification
    Product list & self-reported eligibility pre-check Synchronous Uses only user-typed fields; instant feedback keeps conversion high
    Draft edits & document uploads Synchronous (direct signed-URL upload to object storage) Local validation is sub-50 ms and user is waiting on form step
    Bank account linking Synchronous UI token exchange; asynchronous history pull Linking takes seconds, while pulling 24 months of transactions takes up to minutes
    Application submit Synchronous durability (202 Accepted); asynchronous execution Locks in submission safely without tying a request thread to slow vendors
    KYC, sanctions, fraud, credit & bank pulls Asynchronous workers Absorbs vendor latency spikes, rate limits, and retries cleanly
    Underwriting model & policy evaluation Asynchronous trigger, sub-second execution Fires automatically as soon as all required data steps complete
    Manual review Asynchronous human queue Takes minutes to hours; leased cases survive browser closes
    Offer e-signature Interactive user signing + asynchronous webhook confirmation Prevents spoofed client-side "signed" claims; vendor webhook is authoritative
    Funds disbursement & settlement Asynchronous state machine + daily reconciliation ACH settlement and returns take 1–3+ business days

    Why not all synchronous? One slow bureau or bank aggregator would hold threads for minutes, mobile timeouts would cause duplicate credit inquiries on retry, deploys would drop in-flight applications, and vendor rate limits could not be smoothed via queues. Why not all asynchronous? Putting form validation or product pre-checks behind a queue forces unnecessary polling lag onto interactive user actions.

    Database state machine vs. durable workflow engine: At ~1.2 peak submissions/s, storing state, outbox events, and timers in PostgreSQL keeps operational moving parts minimal and lets compliance inspect everything with standard SQL. A dedicated workflow engine (such as Temporal or AWS Step Functions) is a valid alternative if product branching grows complex, trading an extra infrastructure cluster and workflow-versioning discipline for built-in timers and retry state.

  6. Deep dive 1: External provider calls, retries, timeouts, and partial failures

    Every vendor call is uniquely keyed by (application_id, purpose)—for example, ("app-42", "credit_owner_soft")—backed by one external_call row. Before touching the network, a worker checks if status == "ok" and reuses the cached response. When an error occurs, retrying safely depends on distinguishing two failure modes:

    • Definitely not processed (NotProcessedError): TCP connection refused, DNS failure, or HTTP 429 Too Many Requests. Safe to retry freely.
    • Ambiguous outcome (MaybeProcessedError): Read timeout after sending bytes, connection reset, or HTTP 5xx. The vendor might have executed the request. Crucially, the worker writes status = "unknown" before opening the network call so a worker process crash mid-request leaves the exact same durable footprint as a read timeout.
    import random
    
    
    class NotProcessedError(Exception):
        """Vendor definitely did not execute the call (e.g., connection refused, HTTP 429)."""
    
        def __init__(self, message, retry_after=0.0):
            super().__init__(message)
            self.retry_after = retry_after
    
    
    class MaybeProcessedError(Exception):
        """Vendor may have executed the call (e.g., read timeout, connection reset, HTTP 500)."""
    
    
    def backoff_delay(attempt, base=1.0, cap=60.0):
        """Exponential backoff with full jitter so recovering vendors are not slammed in sync."""
        max_sleep = min(cap, base * (2 ** (attempt - 1)))
        return random.uniform(0.0, max_sleep)
    
    
    def retry_or_escalate(job, adapter, scheduler, reason, retry_after=0.0):
        if job.attempt >= adapter.max_attempts or scheduler.past_deadline(job):
            # Never auto-decline an applicant because our vendor integration timed out!
            scheduler.escalate_to_review(job, reason=reason)
        else:
            delay = max(retry_after, backoff_delay(job.attempt))
            scheduler.enqueue_delayed(job, delay=delay)
    
    
    def run_step(job, store, adapter, scheduler):
        """Idempotent wrapper for one (application_id, purpose) external vendor call."""
        call = store.get_call(job.application_id, job.purpose)
        if call.status == "ok":
            return call.result
    
        # If a prior attempt timed out and this vendor does not deduplicate by key,
        # query the vendor by reference before ever resending (critical for hard credit pulls).
        if call.status == "unknown" and not adapter.dedupes_by_key:
            scheduler.resolve_unknown(job)
            return None
    
        # Circuit breaker: if vendor is failing >50%, pause on a durable timer instead of piling up timeouts.
        if not adapter.breaker.allows():
            scheduler.enqueue_delayed(job, delay=adapter.breaker.seconds_until_probe())
            return None
    
        # Acquire a token from the shared per-vendor rate limiter (prioritizing live applicants over batch jobs).
        adapter.quota.acquire(priority=job.priority)
        store.set_status(job.application_id, job.purpose, "unknown")
    
        try:
            result = adapter.call(
                job.request,
                idempotency_key=job.idempotency_key,
                timeout=adapter.timeout_seconds,
            )
        except NotProcessedError as err:
            store.set_status(job.application_id, job.purpose, "failed")
            adapter.breaker.record_failure()
            retry_or_escalate(job, adapter, scheduler, str(err), err.retry_after)
            return None
        except MaybeProcessedError as err:
            # Keep status as "unknown" so the next attempt knows a prior packet escaped.
            adapter.breaker.record_failure()
            retry_or_escalate(job, adapter, scheduler, str(err))
            return None
    
        adapter.breaker.record_success()
        store.save_result(job.application_id, job.purpose, result)  # Marks status = "ok"
        return result
    

    Operational safeguards around external calls

    • Three-tier timeouts:
      1. Per HTTP attempt: 1 s TCP connect, 10 s read for KYC/credit; bank history uses async webhooks plus a 2 min polling fallback if a webhook drops.
      2. Per workflow stage: 30 min deadline for DATA_COLLECTION before escalating to operations/manual review.
      3. Per application: 24 h max wait for automated decisioning; 14 days before an unsigned offer expires.
    • Rate limits, concurrency, and retry budgets: Each adapter enforces a shared token bucket set to ~80% of contract quota (8 req/s on a 10 req/s bureau) with priority lanes (live applicants > manual re-pulls > nightly monitoring). Worker concurrency is sized by Little's law (average items in flight = arrival rate × average latency: 8 req/s x 2 s = 16 concurrent calls). A retry budget caps retries at 10% of total requests per minute so a degraded vendor is not hit by a retry storm.
    • Circuit breakers and partial failures: A circuit breaker (an automatic state switch that opens when >50% of the last 20 calls fail within 30 seconds, blocking calls briefly and sending one probe every 30 seconds) converts vendor outages into polite applicant wait estimates rather than declines. Because each step saves its external_call row independently, a bank-aggregator failure retries only the bank step without re-pulling or re-paying for the bureau report.
    • Staged check ordering (cheapest first):
    Stage 0 (free, <10 ms)    Product eligibility: supported state, industry, time in business, amount range
    Stage 1 (cheap, ~1 s)     KYC + KYB + OFAC sanctions screening (policy gate before pulling credit)
    Stage 2 (cheap, ~1 s)     Device, velocity, and cross-application fraud graph signals
    Stage 3 (paid & slow)     Credit bureau reports + bank transaction history (fetched in parallel)
    Stage 4 (local, <200 ms)  Underwriting knockout rules + probability-of-default model
    

    Gating Stage 3 behind Stages 0–2 avoids paying bureau fees on applicants who fail basic eligibility, identity, or fraud checks.

  7. Deep dive 2: KYC/AML, fraud detection, underwriting, and manual review

    KYC, KYB, and AML compliance

    • Identity & beneficial ownership: Verify owner name, DOB, address, and SSN against a KYC vendor (stepping up weak matches to government ID + live selfie verification). Verify business state registration, EIN, and every beneficial owner (anyone owning 25% or more of the company, plus one controlling officer).
    • Sanctions screening: Screen the business and all owners against OFAC lists (US Treasury watchlists of sanctioned individuals and entities). High-similarity fuzzy matches enter COMPLIANCE_HOLD for trained compliance officers—underwriters cannot override them. Re-screen before funding if >30 days elapsed, and continuously as sanctions lists update.
    • Post-funding AML & SAR secrecy: Monitor repayments for money-laundering typologies (third-party payors, rapid lump-sum payoffs from unverified accounts). If compliance files a SAR (Suspicious Activity Report — a confidential report to financial crime authorities), federal law strictly forbids tipping off the applicant: SAR flags and notes live in isolated compliance tables that can never map to customer-visible status or decline reasons.

    Fraud detection

    • Session and velocity signals: Device fingerprint, IP-to-business-address distance, email/phone domain age, copy-paste speed on identity fields, and recent bureau inquiries (loan stacking — taking multiple loans simultaneously before bureaus reflect the new debt).
    • Entity-link graph: Flag shared SSNs, phones, devices, or bank accounts across ostensibly unrelated businesses to catch synthetic identity rings.
    • Payout account binding: Verify that the bank account owner name returned by the aggregator matches the business or guarantor, and lock disbursement to the exact account analyzed during underwriting unless a new account passes full re-verification and fraud review.

    Deterministic decision engine & adverse-action compliance

    def decide(application, features, model, policy):
        """Pure, deterministic underwriting function: identical inputs + versions -> identical result."""
        knockouts = policy.knockouts(features)  # e.g., < 12 months in business, active bankruptcy
        if knockouts:
            return "AUTO_DECLINED", {"reasons": knockouts[:4]}
    
        if features.fraud_flags or features.kyc_status != "VERIFIED":
            return "MANUAL_REVIEW", {"reasons": features.fraud_flags or ["KYC_STEP_UP_REQUIRED"]}
    
        p_default = model.probability_of_default(features)
        if p_default > policy.decline_above:
            return "AUTO_DECLINED", {"reasons": model.top_adverse_factors(features, limit=4)}
    
        if p_default > policy.review_above or application.amount_requested > policy.auto_approve_max:
            return "MANUAL_REVIEW", {"reasons": ["RISK_OR_AMOUNT_REVIEW"]}
    
        approved_amount = policy.max_amount(features, p_default)  # Capped by free cash flow
        return "AUTO_APPROVED", {"amount": approved_amount, "price": policy.price(p_default)}
    
    • Every decision row persists the exact features_snapshot_ref, policy_version, model_version, and controlled reason_codes[].
    • Under the US Equal Credit Opportunity Act (Regulation B), declined applicants must receive specific principal reasons (typically within 30 days). Approving a lower amount than requested is a counteroffer: if it expires unaccepted, our timer still triggers an adverse-action notice. New ML models (such as monotonic gradient-boosted trees) run in shadow mode (scoring live traffic silently without affecting decisions) and undergo fair-lending disparity checks before rollout.

    Manual review tooling

    • Specialized queues (credit, fraud, compliance, info_received) ordered by SLA urgency and loan size.
    • 30-minute claim leases so two reviewers never work the same file, while abandoned tabs automatically return to the queue.
    • Single-screen evidence view (categorized monthly cash flow, NSF/overdraft highlights, bureau summary, explained fraud links) with PII masked until explicitly revealed with an audited reason, plus four-eyes dual approval above authority limits (for example, loans over $100,000).
  8. Deep dive 3: Approval, disbursement, ledger, and reconciliation

    Once an applicant signs an approved offer, the system runs a pre-funding gate right before moving money: offer unexpired, signed agreement hash recorded, payout account matches the verified underwriting account, sanctions check still fresh, zero suspicious post-approval account/device changes, dual approval present if required, and room remaining under treasury's daily funding cap.

    Guaranteeing at-most-once payouts over an unreliable network

    No network protocol offers true end-to-end "exactly-once" execution across two companies. Instead, we guarantee at most one live payout per loan and complete ledger visibility through four layers: 1. A deterministic disbursement_id (<offer_id>-<attempt>, e.g., off_99-1) created in PostgreSQL before any network call and passed to the payment provider as both idempotency_key and external reference. 2. A partial unique index UNIQUE (loan_id) WHERE status NOT IN ('FAILED', 'RETURNED', 'CANCELLED') blocking duplicate active payouts in SQL. 3. A short row lease (lease_until) when entering SUBMITTING so two workers never fire concurrent HTTP calls for the same disbursement. 4. Recording timeouts as UNKNOWN—never FAILED—and querying find_by_reference before resending within the provider's 24-hour idempotency window:

    from datetime import timedelta
    
    KEY_WINDOW = timedelta(hours=24)       # Provider's contractual idempotency-key retention window
    CLAIM_LEASE = timedelta(minutes=2)     # Prevents two workers from calling the bank concurrently
    
    
    class PaymentRejectedError(Exception):
        """Provider definitively rejected the transfer before moving funds (e.g., invalid routing number)."""
    
    
    def submit_disbursement(db, payments, disbursement_id, now):
        """Idempotent payout sender: safe across worker crashes, retries, and network timeouts."""
        # Atomically claim the disbursement row only if no other worker holds an active lease.
        d = db.claim_disbursement(disbursement_id, now=now, lease=CLAIM_LEASE)
        if d is None or d.status in ("SUBMITTED", "SETTLED", "RETURNED", "CANCELLED", "FAILED"):
            return None if d is None else d.status
    
        if d.status in ("SUBMITTING", "UNKNOWN"):
            # A previous worker crashed or timed out mid-call; check the provider before resending.
            existing = payments.find_by_reference(disbursement_id)
            if existing is not None:
                db.mark_submitted(disbursement_id, existing.payment_id)
                return "SUBMITTED"
            if now - d.first_attempt_at > KEY_WINDOW:
                # Past 24h the provider may have evicted our idempotency key; escalate to a human!
                db.open_finance_case(disbursement_id, reason="ambiguous payout past key window")
                return "UNKNOWN"
    
        if d.first_attempt_at is None:
            db.set_first_attempt_at(disbursement_id, now)
        db.set_status(disbursement_id, "SUBMITTING")
    
        try:
            payment = payments.create_credit(
                amount_cents=d.amount_cents,
                account_token=d.account_token,
                reference=disbursement_id,
                idempotency_key=disbursement_id,
            )
        except TimeoutError:
            db.set_status(disbursement_id, "UNKNOWN")
            raise
        except PaymentRejectedError:
            db.set_status(disbursement_id, "FAILED")  # Triggers reversing ledger journal
            return "FAILED"
    
        db.mark_submitted(disbursement_id, payment.payment_id)
        return "SUBMITTED"
    

    Double-entry ledger and three-way reconciliation

    We track every cent in an append-only double-entry ledger (an accounting table where every event writes integer-cent debit and credit rows whose sum is equal, and mistakes are fixed by new reversing rows rather than UPDATEs):

    Lifecycle Event                  Account Debit                  Account Credit
    -----------------------------------------------------------------------------------------------
    1. Payout submitted ($20,000)    loans_receivable  $20,000      funds_in_transit  $20,000
    2. Bank confirms settlement      funds_in_transit  $20,000      operating_cash    $20,000
    3. ACH return (e.g., closed acct)operating_cash    $20,000      funds_in_transit  $20,000
                                     funds_in_transit  $20,000      loans_receivable  $20,000
    

    Every night, automated three-way reconciliation matches (1) our ledger entries, (2) the payment provider's settlement report, and (3) our partner bank's account statement by disbursement_id and amount_cents. Any discrepancy, any funds_in_transit balance aged past 3 banking days, or any UNKNOWN disbursement older than 1 hour pages finance operations.

    Payment rails: Standard ACH is low-cost and settles next business day; Same-Day ACH settles within hours before cutoff (up to Nacha's $1M per-payment cap) but can still return within 2+ banking days (R02 closed account, R03 no account), so a loan can return to FUNDING_FAILED and issue a fresh <offer_id>-2 disbursement only after the return settles. Instant rails (RTP / FedNow) settle in seconds and are irrevocable, so we restrict instant payouts to lower-risk tiers after all fraud gates clear.

  9. PII protection, compliance, and tamper-evident audit logs

    We classify every field into three tiers (restricted: SSN, EIN, bank numbers, ID photos, aggregator tokens; confidential: names, emails, credit reports, cash-flow summaries; internal: states, product configs, metrics) and enforce defense in depth:

    • PII Vault Tokenization: Tokenization replaces sensitive fields (SSN, EIN, bank routing/account numbers) with random non-reversible tokens (ssn_tok_8f2a...) at intake. Application tables, queues, and analytics only ever store tokens; only specific vendor adapters (such as KYC or ACH payout) hold narrow IAM permissions to detokenize, logging caller, application, and purpose on every call.
    • Envelope Encryption & Cohort Crypto-Shredding: Large JSON/PDF files in object storage use envelope encryption (each file is encrypted with a unique data key, and that data key is encrypted by a Key Management Service master key). Because backups also contain the wrapped data key, deleting live rows alone leaves backups readable. Grouping master keys by (data_class, retention_month) enables crypto-shredding: destroying one expired monthly KMS key renders both live files and all historical backups permanently unreadable at once (for example, after 12–25 months for Regulation B records or 5 years for AML records).
    • Zero-PII Observability & Scoped Access: Structured logs enforce field allow-lists plus a regex PII scrubber; traces carry application_id only. Engineers have zero standing read access to production PII, and analytics warehouses use pseudonymized IDs for model training and fair-lending audits.
    • Tamper-Evident Audit Trail: Every state transition, decision, PII reveal, and policy/model config change writes an append-only hash-chained record (entry_hash = SHA256(prev_hash || payload)). Because a database superuser could theoretically rewrite a chain tail in place, we ship logs continuously to write-once-read-many (WORM / S3 Object Lock) storage and anchor the latest chain hash there every few minutes.
  10. Scaling, backpressure, observability, and failure handling

    Scaling and 5-step backpressure under 10x bursts

    1. Absorb intake spikes in durable queues: :submit only writes to PostgreSQL (<20 ms), easily handling 10x marketing spikes while queues buffer downstream work.
    2. Per-vendor priority lanes: Live applicant calls pre-empt manual re-pulls and nightly batch monitoring inside each adapter's token bucket.
    3. Dynamic applicant expectations: When queue_depth / drain_rate exceeds 4 hours, status endpoints automatically shift UI messaging from "decision in minutes" to "decision within 1 business day".
    4. Upstream campaign throttling: Alert growth/marketing systems to pause outbound campaigns if manual review backlog exceeds 1 business day of capacity.
    5. Treasury funding cap: Queue accepted payouts for the next banking window rather than overdrawing operating cash. (Crucially, we never tighten credit-approval thresholds to clear an ops queue—credit policy is strictly a risk/compliance decision.)

    Observability & Failure Matrix

    Every log, metric, and span carries application_id. Key alerts watch stuck applications exceeding state SLAs, open circuit breakers, queue age, sudden shifts in auto-approval rates, ACH return spikes, reconciliation breaks, and UNKNOWN payouts.

    Failure scenario System impact Automated mitigation & recovery
    Credit bureau or KYC outage Screening / data collection stalls Circuit breaker opens; jobs wait on durable timers; escalate to manual review after deadline—never auto-decline
    Lost vendor webhook (e.g., bank history) Step stays pending Scheduled polling fallback after 2 min + 15 min in-flight sweeper queries vendor state
    Duplicate or out-of-order webhooks Stale "submitted" arrives after "settled" Deduplicate provider_event_id; conditional transition() rejects backward state moves
    Payout API read timeout Ambiguous whether $20,000 moved Mark UNKNOWN, query find_by_reference before resend within 24h key window, page ops at 1 h
    ACH return 2 days after settlement Funds bounced back from borrower's bank Write reversing ledger entries, move to FUNDING_FAILED, require fraud-checked new account for <offer_id>-2
    Bad model or policy deployment Approval rate jumps or drops abnormally Shadow scoring first, 5% canary rollout, automated rollback on approval-rate / score-drift bounds
    Full cloud region outage Primary region unreachable Promote warm standby in secondary region; pause payouts briefly until recent provider transfers are reconciled by deterministic disbursement_id so async replication lag cannot double-pay
  11. Summary of key design trade-offs

    • Synchronous intake (202 Accepted) vs. asynchronous execution: Trades an instant blocking HTTP response for a progress/polling UI so slow vendors, human reviews, and deploys never drop applications or double-pull credit.
    • PostgreSQL state machine + outbox vs. external workflow engine: Keeps transactions atomic and SQL-auditable with minimal infrastructure at ~1.2 req/s, trading away the built-in history UI of a separate cluster like Temporal.
    • Staged checks (cheap first) vs. full parallelism: Adds ~2 seconds before paid calls (invisible next to multi-minute bank pulls) while saving substantial bureau spend and unnecessary credit inquiries.
    • Explicit UNKNOWN state + lookup-before-resend vs. naive retries: Adds schema and adapter lookup logic, eliminating duplicate hard credit inquiries and duplicate $20,000 disbursements.
    • Delays vs. declines on infrastructure failure: Risks minor applicant drop-off during vendor outages in exchange for zero unlawful or unfair infrastructure-induced loan denials.
    • PII vault tokenization + cohort crypto-shredding vs. inline columns: Adds a vault hop for the few adapters needing raw SSNs/accounts, drastically shrinking breach blast radius and making backup retention compliance tractable.

Intuition & how it works

Think of an online loan application system like an airport security and bank-escrow assembly line where every folder carries stamped coat-check tickets: when a small-business owner clicks "Submit", the front desk immediately stamps their folder SUBMITTED and hands back a tracking receipt (202 Accepted) instead of making them stand at the counter for hours. Behind the scenes, an orchestrator (a state-machine controller that advances each application one legal step at a time) routes the folder through cheap identity and fraud gates first, then paid credit-bureau and bank-history pulls, then an underwriting scorecard or human reviewer, and finally an escrow payout desk. Every external call carries a deterministic idempotency key (a unique ticket ID reused across retries so a vendor recognizes duplicate requests and runs the action at most once), and every dollar moved is recorded in an append-only double-entry ledger (an accounting log where balanced debit and credit entries in integer cents must always sum to zero).

Why does the naive approach fail? Putting KYC, credit-bureau pulls, bank-statement fetching, and decisioning inside one synchronous POST /submit HTTP handler times out whenever a bank aggregator takes two minutes or a human underwriter takes four hours. Worse, when a mobile client or worker blindly retries after a network timeout, it triggers duplicate hard credit pulls (formal credit inquiries that can lower the applicant's credit score) or sends a second $20,000 payout. And if a vendor outage causes an unhandled exception that rejects the application, the lender issues an unfair, legally indefensible loan denial caused purely by its own infrastructure.

Let's trace one $20,000 application (app-42) through five concrete events:

1. Intake (t = 0s):
   POST /v1/applications/app-42:submit (Idempotency-Key: "k-submit-1")
   -> Single SQL transaction sets state = SUBMITTED, writes application_event #1 + outbox row, returns 202.
   -> Client retries same key on flaky Wi-Fi -> gateway replays stored 202 with zero duplicate work.

2. Staged screening & data collection (t = 1s .. 45s):
   -> Stage 1 (KYC/KYB + OFAC sanctions) & Stage 2 (fraud signals) pass in ~2s.
   -> Only AFTER Stages 1-2 pass does Stage 3 fire soft credit pull + async bank-transaction fetch in parallel.
   -> Bank webhook arrives at t = 45s -> moves app-42 to UNDERWRITING -> AUTO_APPROVED -> OFFER_PRESENTED (off-99).

3. E-sign & pre-funding gate (t = 10m):
   -> Owner e-signs; webhook moves off-99 to ACCEPTED -> pre-funding checks verify payout account matches
      the analyzed bank account -> creates loan + disbursement "off-99-1" -> state = FUNDING_PENDING.

4. Ambiguous payout timeout & safe recovery (t = 10m 05s):
   -> Worker claims lease, sets "off-99-1" = SUBMITTING, calls create_credit(idempotency_key="off-99-1").
   -> Read timeout! Worker marks status = UNKNOWN (never FAILED).
   -> Retry worker calls payments.find_by_reference("off-99-1") -> sees provider DID accept it (pay_777)!
   -> Marks "off-99-1" = SUBMITTED without sending a second $20,000 transfer.

5. Settlement & reconciliation (Next business day):
   -> Webhook confirms settled -> ledger moves $20,000 from funds_in_transit to operating_cash -> FUNDED.
   -> Nightly 3-way reconciliation matches our ledger, payment provider report, and bank statement to the cent.

Key trade-offs

  • Synchronous intake (202 Accepted) vs. asynchronous workflow steps. Persisting the submission and running vendor checks, human reviews, and payouts via durable queues forces the UI to poll or stream status updates rather than getting a blocking HTTP answer. In return, vendor slowdowns and server deploys turn into harmless delays rather than failed applications or duplicate bureau charges. Interactive steps with no external wait (product browsing, draft saving, instant self-reported pre-checks) stay synchronous.
  • Database state machine + transactional outbox vs. a dedicated workflow engine. Keeping application.state, optimistic locking (conditional SQL updates WHERE state = expected so racing workers cannot overwrite each other), timers, and an outbox table (queue events committed in the exact same SQL transaction as state changes) inside PostgreSQL is simple to operate and SQL-queryable for compliance at ~1.2 submissions/s. A durable workflow engine (such as Temporal or AWS Step Functions) gives built-in timers and execution history out of the box, at the cost of operating another critical cluster and versioning long-lived workflow code.
  • Staged check ordering vs. running all checks in parallel. Running free eligibility, KYC/KYB, OFAC sanctions screening (checking US Treasury watchlists of sanctioned parties), and fraud checks before paid credit-bureau pulls adds ~2 seconds of latency—completely hidden behind multi-minute bank-data pulls—while saving bureau fees and avoiding unnecessary credit inquiries on rejected applicants.
  • Explicit UNKNOWN state and lookup-before-resend vs. blind retries. Keying every external call by (application_id, purpose), persisting UNKNOWN before sending bytes over the network, and querying the vendor by reference before resending adds schema and adapter code, but prevents duplicate hard credit inquiries and double $20,000 payouts when network responses time out.
  • At-most-once payout controls vs. maximum payout speed. Enforcing a partial unique SQL index on active disbursements per loan, a 24-hour provider idempotency-key window check, and human escalation when an UNKNOWN transfer outlives that window deliberately slows rare ambiguous payouts to guarantee funds are never sent twice.
  • Standard/Same-Day ACH vs. instant rails (RTP / FedNow). ACH (the US batch bank-transfer network) is inexpensive and covers large business loans (up to $1M for Same-Day ACH), but transfers can bounce 2+ banking days later via return codes, meaning "settled" requires return-window handling. Instant rails settle irrevocably in seconds, delighting borrowers, so they must be gated behind complete fraud checks and lower risk caps.
  • Delaying vs. declining during infrastructure outages. Opening a circuit breaker (an automatic switch that pauses calls to a failing vendor and probes periodically for recovery) makes applicants wait longer during bureau outages, increasing abandonment slightly, while guaranteeing our infrastructure never causes an unfair adverse-action notice (a legally required denial letter under US Regulation B stating the specific reasons credit was refused).
  • PII vault tokenization vs. storing raw columns. Tokenization (storing sensitive SSNs and bank account numbers in an isolated vault and keeping only random lookup tokens in application tables) adds a network call for the few vendor adapters that need raw values, while dramatically shrinking the blast radius of a database leak or log exposure.

Common mistakes

  • Running vendor calls inside a synchronous POST /submit request: Slow bank pulls time out the HTTP connection, and client retries trigger duplicate credit-bureau charges and inquiries.
  • Treating a payment or hard-pull network timeout as FAILED and retrying with a fresh ID: A read timeout means the vendor may already have processed the request; generating a new reference or retrying blindly causes double $20,000 disbursements or duplicate hard inquiries on the owner's credit report.
  • Assuming provider idempotency keys last forever: Payment providers typically evict idempotency keys after 24–48 hours; resending after that window expires without first checking find_by_reference can execute a second transfer.
  • Publishing queue events outside the database transaction (no outbox): If the worker crashes between COMMIT and publishing to the queue, the application sits stuck in its current state forever; if it publishes before COMMIT and rolls back, downstream workers act on phantom state.
  • Releasing a fraud or compliance hold without verifying held_from: Allowing FRAUD_HOLD to transition to any active state lets a bug jump an unscreened SCREENING application straight to ACCEPTED, bypassing underwriting.
  • Allowing post-approval bank account edits without full re-verification: Fraudsters routinely pass underwriting using a healthy bank account and swap in a mule account right before disbursement.
  • Updating a mutable balance float instead of an integer-cent double-entry ledger: Floating-point rounding errors and in-place UPDATEs make three-way bank reconciliation and audit trails impossible.
  • Auto-declining when a bureau, KYC vendor, or ML model service is down: Infrastructure errors must route to waiting timers or manual review, never to an adverse credit decision, and SAR (Suspicious Activity Report) compliance holds must never leak tipping-off reasons to customer-facing messages.

Follow-up questions

  • How can the team introduce a new financing offering—such as a seasonal inventory advance—without deploying backend code? Store products as immutable, versioned configuration records specifying allowed states, amount/term bounds, required data steps, pricing grids, knockout thresholds, and agreement templates. Validate new versions against a strict schema, require risk and compliance sign-off, and pin product_version on each application at creation time so mid-flight applicants never see terms shift underneath them. Only genuinely new mechanics—such as integrating a brand-new card-processor data feed for daily revenue-share collection—require new adapter or servicing code.
  • How should the platform handle a borrower who requests to switch their payout bank account after approval? Treat a post-approval payout-account change as a high-risk security event rather than a profile edit. Force the borrower to link the new account through the bank aggregator so we can verify that the legal owner name on the bank account matches the business or guarantor, re-run device/session fraud checks (looking for recent password resets or unrecognized IPs), send out-of-band alerts to the owner's original email and phone, and require underwriter sign-off above a set dollar threshold before creating a new disbursement attempt.
  • If regulators examine a rejected file eighteen months later, how do you reproduce the exact decision and verify fair-lending compliance? Query the immutable decision record, which links to the encrypted feature-vector snapshot, exact policy_version and model_version artifacts, raw vendor response hashes, and the controlled reason_codes[] sent on the adverse-action notice. Because decide() is a deterministic pure function (verified weekly by an automated replay check on sampled decisions) and the hash-chained audit log (an append-only log where each row hashes the previous row and anchors snapshots to write-once storage) records any reviewer actions and timestamps, compliance can reproduce the exact score and reasons mathematically and show fair-lending test results from the pseudonymized warehouse.

Follow-up questions

Similar questions

More Parafin interview questions

All 2 Parafin questions →