Consumer Stock Brokerage Platform

Hard · System Design · Software Engineer · Onsite

Prompt

Architect a mobile-first consumer stock brokerage that lets everyday investors fund accounts, watch live equity prices, and trade US stocks and ETFs with low latency and strict financial accuracy.

Your design must address the end-to-end trading lifecycle:

  • Account setup & bank transfers: Customer identity and sanctions screening (KYC/AML), bank account linking via ACH, and real-time cash and buying-power balances.
  • Live market quotes: High-throughput exchange feed ingestion and low-latency quote streaming to millions of open client apps.
  • Order management & venue execution: Idempotent submission, validation, and pre-trade risk holds across market, limit, and stop orders, followed by routing to exchanges or market makers and post-trade settlement through a partner clearing firm.
  • Holdings & accounting: Position tracking, tax-lot cost basis, realized and unrealized PnL, and corporate actions such as dividends and stock splits.
  • Resilience, operations & future asset classes: Surviving extreme 9:30 a.m. ET market-open surges, managing slow-client backpressure, HA/DR failover, compliance audit trails, safe degradation when quote feeds fail, and clean extensibility to options and crypto.

Scope & Expectations

  • Service boundaries, APIs & storage: Define synchronous vs. asynchronous APIs, message-bus flows, event-sourced ledger/order schemas, and storage engines for accounts, orders, fills, and price ticks.
  • Consistency vs. latency guarantees: Contrast the strict transactional guarantees required for cash holds and order state against the latency-first delivery used for streaming quotes and live portfolio views.
  • Peak scale, backpressure & incident fallbacks: Explain how the system absorbs market-open traffic cliffs, handles Regional/AZ failures, enforces regulatory auditability, and degrades safely during a market-data outage.
  • Product extensibility: Show how your data model and risk engine evolve to support multi-leg options and 24/7 cryptocurrency trading without a ground-up rewrite.

Step-by-step walkthrough

  1. Clarify requirements and scope

    A consumer stock brokerage is really three distinct systems running at three different speeds:

    1. The Money & Order Core must be 100% exact—never losing an order, double-filling a retry, or letting two fast taps spend the same dollar twice.
    2. The Market Data Plane must stream millions of live price updates per second with low latency, where dropping an intermediate price tick from 200 ms ago is actually helpful so phones always display the newest price.
    3. The Post-Trade & Compliance Back Office runs on the daily settlement and regulatory clock of Wall Street clearinghouses and auditors.

    Functional requirements

    • Onboarding & funding: Verify customer identity (KYC, or Know Your Customer) and screen against sanctions and money-laundering rules (AML, or Anti-Money Laundering); link bank accounts for ACH (Automated Clearing House—the US bank-to-bank transfer network that takes 1–3 business days to settle) with optional instant buying power.
    • Real-time balances: Show accurate buying_power, settled_cash, unsettled_cash, and withdrawable_cash.
    • Market data: Ingest exchange feeds, stream live quotes to watchlists and stock detail pages, and serve historical price charts.
    • Order lifecycle: Support market, limit, stop, and stop_limit orders (day and gtc, Good-Till-Canceled) with strict idempotency (retrying a timed-out request never buys twice), pre-trade risk checks, cancelation, routing to market makers (high-speed wholesale liquidity firms) or exchanges, and post-trade clearing.
    • Portfolio & tax accounting: Track share positions, tax-lot cost basis (what you paid per share), realized and unrealized PnL (Profit and Loss), and corporate actions (dividends, stock splits, mergers).

    Non-functional requirements & key assumptions

    • Broker model: We operate as an introducing broker (we own the app, real-time risk checks, and customer ledger) partnered with a clearing broker (a licensed firm connected directly to the DTCC/NSCC clearinghouse that settles trades on T+1—one business day after execution—and custodies shares). We reconcile our books against theirs every morning before market open.
    • Scope: v1 covers US stocks and ETFs in cash accounts (DECIMAL quantities ready for fractional shares); margin, options, and crypto are designed as clean extensions in the final step.
    • Latency & availability: Order acceptance p99 < 100 ms server-side; streaming quotes reach phones within ~500 ms; survive the 9:30 a.m. ET market-open surge and regional failures without losing a single committed order or cent.
  2. Back-of-the-envelope numbers

    Let's size both regular market hours (9:30–16:00 ET = 6.5 hours = 23,400 s) and the brutal 9:30 a.m. market-open burst:

    1. Accounts & Order Core
       Funded accounts                25M total; ~5M active on a busy day; 2M concurrent sockets at 9:30 a.m.
       Orders per day                 5M normal day (~215 orders/s avg); 25M meme-rally day
       9:30 a.m. open surge           ~3% of daily volume in minute 1 (including overnight queued orders):
                                      750,000 / 60 s = 12,500 orders/s -> design for 20,000 orders/s peak!
       Fills (executions)             ~1.3 fills per order (partial fills) -> ~26,000 fill events/s peak
       Sharded Postgres write load    32 shards by hash(account_id):
                                      (20,000 accepts + 26,000 fills) / 32 = ~1,440 ACID tx/s per shard
                                      ~7 ledger rows/order x 20,000/s / 32 = ~4,375 rows/s per shard
    
    2. Market Data Fan-Out
       Tradable US equities & ETFs    ~10,000 symbols; raw exchange feed bursts to ~1,000,000 ticks/s at 9:30
       Conflated internal stream      Cap at 4 quote updates/s/symbol -> max 40,000 msgs/s (~4 MB/s total!)
       Client WebSocket egress        2M open apps x 1 batched frame/s (~10 symbols, ~400 B) = ~800 MB/s
                                      (~6.4 Gbit/s) across 80 Stream Gateways (~25,000 sockets/gateway)
    
    3. Daily Storage (busy 25M-order day)
       Orders + order_events          25M x ~1.5 KB                           = ~38 GB/day
       Double-entry ledger            25M x ~7 entries x ~150 B               = ~26 GB/day
       Raw market ticks (Parquet)     ~300k/s avg x 23,400 s x 40 B           = ~280 GB/day uncompressed
       1-minute OHLCV chart bars      10k symbols x 960 min (04:00-20:00 ET)  = ~9.6M rows (< 1 GB/day)
    

    Three architectural lessons jump right out of these numbers:

    1. ~1,440 transactions/s per shard is well within ordinary PostgreSQL capacity—we do not need an exotic custom database to get rock-solid ACID transactions for money.
    2. Conflation (coalescing rapid ticks into at most 4 updates/s per symbol) shrinks 1,000,000 raw ticks/s down to 4 MB/s, small enough to broadcast to every WebSocket gateway in memory.
    3. The 9:30 a.m. bell is an instant vertical cliff, so compute capacity and venue connections must be pre-scaled on a schedule at 9:00 a.m. ET.
  3. Service decomposition, APIs, and sync vs. async boundaries

    We split responsibilities so personal identity data, exact per-account accounting, venue connectivity, and lossy quote streaming never interfere with each other:

    Service               Core Responsibility
    --------------------  -------------------------------------------------------------------------
    Onboarding + PII      KYC/AML vendor workflows; tokenized PII vault (SSN & IDs stored nowhere else)
    Funding Service       Bank linking, ACH batch submission, return handling, instant-credit grants
    OMS (Order Mgmt)      Stateless order validation, idempotency, pre-trade risk holds, cancel state
    Account Shards (x32)  Per-account Postgres source of truth: orders, holds, double-entry ledger, lots
    Smart Order Router    Venue selection (NBBO execution quality), stateful FIX gateway pairs
    Stop Trigger Engine   Symbol-partitioned RAM engine watching every trade print to fire stop orders
    Market Data Plant     Redundant feed handlers, in-memory ticker plant, conflator, Stream Gateways
    Portfolio Read Svc    Read-optimized views of positions, unrealized/realized PnL, and chart bars
    Post-Trade & Recon    Clearing drop-copies, T+1 settlement transitions, corporate actions, daily recon
    Compliance & Audit    WORM immutable archive, CAT regulatory reporting, trade surveillance
    

    Sync vs. Async rule of thumb:

    • Synchronous HTTPS whenever the user needs an immediate, authoritative verdict: POST /v1/orders validates risk and locks buying power inside one local shard transaction before returning 201 Accepted or 422 Insufficient Buying Power.
    • Asynchronous (Kafka + WebSocket push) whenever outcomes depend on external markets or banks: routing over FIX (Financial Information eXchange—the standard persistent TCP messaging protocol spoken by exchanges and market makers), partial fills, ACH clearing, and notifications.
    Key Client REST & Streaming Endpoints
      POST   /v1/orders
             Body: {"client_order_id": "uuid", "account_id": 88, "symbol": "AAPL", "side": "buy",
                    "type": "limit", "qty": "10", "limit_price": "190.50", "time_in_force": "day"}
             -> 201 {"order_id": 9001, "status": "accepted", "version": 1}
             (Retry with same client_order_id + same body -> 200 existing order; different body -> 409)
    
      DELETE /v1/orders/{order_id}   -> 200 {"status": "canceled"} | 202 {"status": "cancel_requested"}
      GET    /v1/accounts/{id}/balances  -> {"buying_power": "1420.00", "withdrawable": "420.00", "version": 9}
      GET    /v1/accounts/{id}/positions -> [{"symbol": "AAPL", "qty": "10", "avg_cost": "189.20", ...}]
      POST   /v1/transfers           Header: Idempotency-Key: <uuid> {"direction": "deposit", "amount": "1000.00"}
    
      WebSocket /v1/stream
        client -> {"subscribe_quotes": ["AAPL", "MSFT"]}
        server -> {"type": "quotes",  "q": [{"s": "AAPL", "bid": "190.48", "ask": "190.50", "last": "190.49"}]}
        server -> {"type": "order",   "order_id": 9001, "status": "filled", "filled_qty": "10", "version": 3}
        server -> {"type": "balance", "buying_power": "1421.00", "version": 10}
    
  4. Data model, double-entry ledger, and event sourcing

    Shard every money and order table by hash(account_id). Because an order, its cash hold, its executions, its ledger entries, and its tax lots all belong to a single account_id, co-locating them on the same PostgreSQL shard lets every state transition execute as one local ACID transaction—zero distributed two-phase commits and zero cross-service race conditions!

    -- Never use IEEE floating point (FLOAT/DOUBLE) for money or share quantities! Always use NUMERIC.
    CREATE TABLE accounts (
      account_id    BIGINT PRIMARY KEY,
      user_id       BIGINT NOT NULL,
      status        TEXT   NOT NULL,              -- 'pending_kyc' | 'active' | 'closing_only' | 'frozen'
      clearing_ref  TEXT                          -- sub-account ID at our clearing broker
    );
    
    -- Event-sourced double-entry journal: append-only; entries per (journal_id, asset) MUST sum to 0!
    CREATE TABLE ledger_entries (
      entry_id    BIGINT         PRIMARY KEY,
      journal_id  BIGINT         NOT NULL,        -- groups legs of 1 event (hold, fill, deposit, dividend)
      account_id  BIGINT         NOT NULL,        -- customer account_id or firm contra-account
      asset       TEXT           NOT NULL,        -- 'USD' or instrument_id (e.g. 'INST_AAPL')
      bucket      TEXT           NOT NULL,        -- 'settled' | 'unsettled' | 'held' | 'instant_avail' | 'instant_used'
      amount      NUMERIC(38,18) NOT NULL,        -- signed decimal (+credit / -debit); 18 decimals for crypto
      ref_type    TEXT           NOT NULL,        -- 'order' | 'execution' | 'transfer' | 'corp_action'
      ref_id      TEXT           NOT NULL,
      created_at  TIMESTAMPTZ    NOT NULL
    );
    
    -- Fast current-balance projection updated inside the EXACT SAME SQL transaction as ledger_entries
    CREATE TABLE balances (
      account_id  BIGINT         NOT NULL,
      asset       TEXT           NOT NULL,
      bucket      TEXT           NOT NULL,
      amount      NUMERIC(38,18) NOT NULL,
      PRIMARY KEY (account_id, asset, bucket)
    );
    
    CREATE TABLE orders (
      order_id        BIGINT         PRIMARY KEY,
      account_id      BIGINT         NOT NULL,
      client_order_id UUID           NOT NULL,
      instrument_id   BIGINT         NOT NULL,
      side            TEXT           NOT NULL,    -- 'buy' | 'sell'
      type            TEXT           NOT NULL,    -- 'market' | 'limit' | 'stop' | 'stop_limit'
      qty             NUMERIC(38,18) NOT NULL,
      limit_price     NUMERIC(20,6),
      stop_price      NUMERIC(20,6),
      time_in_force   TEXT           NOT NULL,    -- 'day' | 'gtc'
      status          TEXT           NOT NULL,    -- 'accepted'|'queued'|'pending_trigger'|'sending'|'working'|'filled'|'canceled'
      filled_qty      NUMERIC(38,18) NOT NULL DEFAULT 0,
      avg_fill_price  NUMERIC(20,6),
      version         INT            NOT NULL DEFAULT 1,
      created_at      TIMESTAMPTZ    NOT NULL,
      UNIQUE (account_id, client_order_id)        -- enforces idempotent order submission
    );
    
    CREATE TABLE order_events (                   -- immutable audit log of every order state change
      order_id  BIGINT      NOT NULL,
      seq       INT         NOT NULL,
      type      TEXT        NOT NULL,
      payload   JSONB       NOT NULL,
      ts        TIMESTAMPTZ NOT NULL,
      PRIMARY KEY (order_id, seq)
    );
    
    CREATE TABLE executions (                     -- deduplicates venue fills via FIX ExecID
      venue     TEXT           NOT NULL,
      exec_id   TEXT           NOT NULL,
      order_id  BIGINT         NOT NULL,
      qty       NUMERIC(38,18) NOT NULL,
      price     NUMERIC(20,6)  NOT NULL,
      ts        TIMESTAMPTZ    NOT NULL,
      PRIMARY KEY (venue, exec_id)
    );
    
    CREATE TABLE tax_lots (
      lot_id         BIGINT         PRIMARY KEY,
      account_id     BIGINT         NOT NULL,
      instrument_id  BIGINT         NOT NULL,
      open_qty       NUMERIC(38,18) NOT NULL,
      cost_per_unit  NUMERIC(20,6)  NOT NULL,
      opened_on      DATE           NOT NULL
    );
    

    Why "event sourcing + same-transaction projection" beats pure event replay: ledger_entries and order_events are append-only event logs (giving regulators a complete history and letting downstream Kafka consumers rebuild portfolio views via a transactional outbox table). Updating balances and orders inside the same database transaction means POST /v1/orders reads current buying power in one primary-key lookup instead of replaying 5 years of trades on the hot path!

  5. High-level architecture and consistency guarantees

    A. Trading & Money Core
                             [Mobile / Web Apps]
                 HTTPS (REST) |               ^ WebSocket (/v1/stream)
                              v               |
              [API Gateway: Auth, Rate Limits, Load Shedding]
                /             |               |              \
         [Onboarding]    [Funding]        [OMS xN]      [Portfolio Read Svc]
               \              |              /                 ^
                v             v             v                  |
         [Account Shards x32: Postgres Primary + Sync Standby] |
                |  (orders, ledger, balances, lots, outbox)    |
                v  CDC / Outbox                                |
         Kafka (partitioned by account_id): orders, executions, ledger-events ---> [Stream Gateways x80]
                |                        ^                     |
                v                        | ExecutionReport     +---> [Post-Trade & Daily Recon] <-> [Clearing Broker]
         [Smart Order Router]            |                     |
                |                        |                     +---> [Compliance: WORM Archive, CAT, AML]
         [FIX Gateways (Active/Standby)]-+
                |
         [Market Makers / Exchanges]
    
    B. Market Data Plane
       [Exchange Feed Line A] -\
                                +-> [A/B Arbiter] -\
       [Exchange Feed Line B] -/                    +-> [In-Memory Ticker Plant]
       [Backup Vendor Feed] ------> [Hot Standby] -/        |        |        \
                                         +------------------+        |         +--> [1s/1m Bars DB + Parquet]
                                         | every trade print         | conflated (<= 4/s/sym, ~4 MB/s)
                                         v                           v
                               [Stop Trigger Engine] ------> [Stream Gateways x80] ---> 2M User Phones
    

    Explicit consistency vs. latency contract:

    • Buying power & order acceptance (Strong / ACID): Checked and debited on the account's primary shard in < 100 ms p99.
    • Order & balance updates to UI (Versioned eventual, < 1 s): Pushed over WebSocket with monotonic version integers; the app ignores any out-of-order frame with frame.version <= local_version.
    • Portfolio total value & live PnL (Best-effort real-time): The server sends share quantities and cost basis; the phone itself multiplies qty x live_quote on screen, eliminating 2 million server recalculations per second and ensuring the chart and PnL always match!
  6. Deep dive 1: Onboarding, ACH funding, and real-time balances

    Onboarding (KYC/AML): Runs as a durable state-machine workflow (STARTED -> VERIFYING -> APPROVED | MANUAL_REVIEW -> OPENING_AT_CLEARING -> ACTIVE) because external identity vendors and OFAC sanctions checks are asynchronous. Sensitive documents and Social Security Numbers live exclusively inside an isolated PII Vault; every internal trading microservice sees only an opaque user_id. All external clearing-account creation calls pass account_id as an idempotency key so retries never open duplicate brokerage sub-accounts.

    ACH funding & instant buying power: Standard ACH bank pulls take 1–3 business days to settle and can bounce (NSF insufficient funds within ~2 banking days, or unauthorized disputes up to 60 days). To let new users trade immediately without letting fraudsters withdraw uncollected money, we grant a risk-scored instant credit limit (e.g., $1,000) tracked in dedicated ledger buckets:

    Formulas (every dollar accounted for without freezing prior settled cash!):
      buying_power = USD.settled + USD.unsettled_proceeds + USD.instant_avail
      withdrawable = max(0, USD.settled - USD.instant_used)
    
    Concrete double-entry journal trace (User starts with $200 settled cash, deposits $1,000 ACH,
    buys 10 shares of XYZ with a $50.00 limit, and fills at $49.90 = $499.00):
    
    1. $1,000 ACH Deposit initiated (instant credit granted):
       A.USD.instant_avail  +1000.00  |  FIRM.USD.ach_instant_pool  -1000.00   (sum = 0)
       -> buying_power = 200 + 0 + 1000 = $1,200.00; withdrawable = max(0, 200 - 0) = $200.00!
    
    2. Order Accepted (Buy 10 XYZ @ $50.00 limit -> lock $500.00 hold, spending settled cash first):
       A.USD.settled         -200.00  |  A.USD.instant_avail         -300.00
       A.USD.held            +500.00  |  A.USD.instant_used          +300.00
       FIRM.USD.instant_trk  -300.00                                           (customer cash held = $500)
    
    3. Order Fills at $49.90/share ($499.00 actual cost -> $1.00 price improvement refunded!):
       A.USD.held            -500.00  |  A.USD.instant_avail           +1.00
       CLEARING.USD.payable  +499.00  |  A.USD.instant_used            -1.00   (used credit drops to $299)
       A.XYZ.unsettled        +10     |  CLEARING.XYZ.receivable      -10      (share legs sum = 0)
    
    4. T+1 Share Settlement (next morning):
       A.XYZ.unsettled        -10     |  A.XYZ.settled                +10
    

    Why track instant_used separately from instant_avail? Notice Step 1: because the user hadn't spent their instant credit yet (instant_used = 0), their pre-existing $200 remained withdrawable! And if they sell XYZ on Monday and that sale settles on Tuesday (T+1) before Thursday's ACH clears, subtracting instant_used ($299) blocks withdrawing the uncollected ACH portion while allowing them to withdraw any profit above it. If the ACH later bounces, we reverse the deposit, switch the account to closing_only, and recover any negative balance.

  7. Deep dive 2: Order validation, risk holds, stop triggers, and venue routing

    1. Atomic order acceptance (one transaction on the account's shard):

    1. Lock the account row (SELECT status FROM accounts WHERE account_id = :a FOR UPDATE) so two simultaneous taps on two devices serialize cleanly.
    2. Check (account_id, client_order_id): if already present with identical parameters, return the existing order (200 OK).
    3. Validate symbol tradability (not halted), session rules (no market orders in extended hours), tick size, and fat-finger price collar.
    4. Place the hold: a buy locks cash (qty x limit_price), while a sell locks shares (available_shares >= qty, preventing accidental short sales in a cash account).
    5. Insert orders, order_events, ledger_entries, update balances, write outbox, and commit!

    2. Handling Market, Limit, and Stop orders safely:

    • Market orders become collared marketable limits: In a volatile market, a raw market order could fill 25% higher than the screen quote and exceed the user's cash! We convert a buy market order into a marketable limit order capped at current_ask x 1.05 (5% collar) and lock qty x ask x 1.05. Because the venue enforces that exact limit price, a fill can never exceed the cash hold.
    • Broker-held Stop & Stop-Limit orders: Major US stock exchanges do not hold retail stop orders on their order books. Instead, the OMS saves the order as pending_trigger (placing the cash/share hold up front) and loads it into our Stop Trigger Engine, partitioned in memory by symbol. Each symbol partition maintains two heaps (priority queues): a max-heap of sell-stop prices and a min-heap of buy-stop prices. When a trade print arrives at $185.00, checking whether the highest sell-stop (>= $185.00) or lowest buy-stop (<= $185.00) fired takes O(1) time! Firing uses a Compare-And-Set (version) update in the OMS so duplicate triggers are harmlessly ignored.

    3. Smart Order Routing, unknown states, and cancel races:

    • Venue routing: The Smart Order Router picks wholesalers or exchanges based on continuously measured NBBO (National Best Bid and Offer) price improvement, fill speed, and reject rates to satisfy regulatory best-execution duties.
    • What if a FIX connection drops mid-send (UNKNOWN state)? Never re-send the order with a new ClOrdID—if the first packet made it through, the customer would buy twice! Instead, mark the order unknown, keep the cash hold locked, reconnect the stateful standby FIX gateway, and use FIX sequence-number replay + OrderStatusRequest (backed by the clearing broker's execution drop-copy) to learn the true state.
    • Preventing the Send-vs-Cancel race: Before writing a NewOrderSingle packet to FIX, the Router atomically flips status from accepted -> sending using WHERE order_id = :id AND version = :v. If a user taps Cancel at the exact same millisecond, DELETE /orders/{id} competes on the same version: whichever wins decides cleanly whether the order cancels locally (200 Canceled, releasing the hold immediately) or sends a FIX OrderCancelRequest to the venue (202 Cancel Requested, holding cash until the venue confirms Canceled, because a fill can cross a cancel on the wire!).
  8. Deep dive 3: Market data ingestion, quote conflation, and feed outages

    Redundant ingestion: Exchange feeds arrive over dual physical lines (Line A and Line B) carrying identical sequence numbers; a hardware/C++ A/B arbiter picks whichever packet arrives first and fills UDP packet drops seamlessly from the twin line. A separate secondary market-data vendor runs as a hot standby (using per-symbol failover rather than packet merging, since different vendors assign different sequence numbers).

    Conflation & backpressure to 2 million phones:

    • The Stop Trigger Engine receives every single valid trade print (ignoring late/out-of-sequence tape corrections) so no stop trigger is missed.
    • Stream Gateways receive a conflated stream capped at 4 updates/s per symbol (~4 MB/s total across all 10,000 stocks)—small enough to broadcast to all 80 Gateways with zero complex subscription-routing state!
    • Per-socket backpressure ("latest value wins"): Each Gateway maintains a tiny fixed-size dirty-symbol map per connected WebSocket and flushes one JSON/Protobuf frame per second. If a user rides into a subway tunnel and their TCP send buffer fills up, the Gateway overwrites old queued AAPL prices with the newest AAPL price instead of appending to an unbounded queue. Memory stays flat, and when the phone reconnects it sees current prices rather than 30-second-old history. (Order and balance events never drop; on reconnect, the client fetches missed events via version.)

    Incident fallback during a full market-data outage: If both primary lines and the backup vendor go stale (missing heartbeats or frozen timestamps during market hours):

    1. UI immediately badges quotes and portfolio totals as "Delayed — as of HH:MM:SS".
    2. Reject new market orders (503 Market Data Unavailable — Use a Limit Order), because we cannot compute a safe 5% collar without live NBBO quotes. Keep limit orders open, since the user specifies the exact cap price and the hold uses qty x limit_price!
    3. Pause the Stop Trigger Engine so stale or glitched ticks never liquidate users unfairly; upon recovery, evaluate stops against current live market prices without replaying historical gap prints.
  9. Post-trade clearing, tax lots, corporate actions, and market-open surges

    Clearing, T+1 settlement, and daily reconciliation: Every execution streams in real time via FIX drop-copy to our clearing broker. Under T+1 settlement, trades executed Monday move from unsettled to settled Tuesday morning before 9:30 a.m. ET—only after an automated reconciliation job diffs every single account's shares, cash, and executions against the clearing broker's start-of-day file. Any discrepancy ("recon break") pages operations and restricts just the affected account until resolved, keeping errors isolated.

    Tax lots, wash sales, and corporate actions:

    • Cost basis & PnL: Every buy fill opens a tax_lots row; every sell relieves open lots (FIFO—first-in, first-out—by default, or user-selected specific lots) to record realized PnL. Asynchronous tax workers compute wash sales (selling at a loss within 30 days before or after buying substantially identical shares, which defers the tax loss into the replacement lot's cost basis for IRS Form 1099-B) off the critical trading path.
    • Corporate actions: Processed idempotently before market open per (action_id, account_id):

      • Cash dividend: Because US equities settle T+1, buying the day before the record date settles in time, whereas buying on the record date settles one day late—so the ex-dividend date equals the record date. Eligible settled shares earn a cash journal on pay date.
      • Forward split (e.g., 4-for-1): Multiplies lot open_qty x 4, divides cost_per_unit / 4, adjusts or cancels open GTC/stop orders per policy, and split-adjusts historical chart bars.

    Surviving the 9:30 a.m. market-open surge & HA/DR:

    • 9:00 a.m. scheduled pre-scale & paced queue drain: All stateless services and DB connection pools scale to peak at 9:00 a.m. Overnight queued orders drain FIFO through per-venue token buckets starting at 9:30:00, recomputing market-order collars against opening quotes (topping up holds or rejecting cleanly if a stock gapped +30% overnight). Cancels ride a dedicated high-priority Kafka topic so Cancel never waits behind Buy.
    • Load shedding: Under extreme overload, the API Gateway sheds low-priority reads first (news -> historical charts -> search), preserving order entry, cancels, and balance lookups.
    • HA & DR: Each of the 32 Postgres shards replicates synchronously to a standby in a second Availability Zone (RPO = 0—zero lost orders on single-AZ failure, < 60 s automatic failover) and asynchronously to a warm standby region. Regional DR failover is a deliberate human-approved flip: before reopening trading in DR, we reconcile the last few seconds of in-flight orders against venue and clearing-broker drop-copies so nothing is double-sent.
  10. Observability, compliance, and extending to options and crypto

    Observability & continuous money invariants:

    • Track stage latencies (accept p99, accept-to-FIX-send p99, fill-to-push p99, quote staleness, outbox lag) with order_id propagated end-to-end as a distributed trace ID.
    • Run a continuous real-time invariant auditor verifying that every journal_id sums to 0 per asset, balances == SUM(ledger_entries), and held >= 0.
    • Maintain instant config-driven kill switches (no code deploy needed): firm-wide halt, per-venue circuit breaker, per-symbol closing_only, and zero deployments during market hours.

    Regulatory & audit compliance:

    • Archive all order_events, ledger_entries, and admin/PII access logs to WORM (Write-Once-Read-Many) object storage (S3 Object Lock) for 6+ years to satisfy SEC Rule 17a-4, and synchronize server clocks to NIST via PTP/NTP to generate daily CAT (Consolidated Audit Trail) reports by 8:00 a.m. ET.

    Extending cleanly to Options and Crypto: Because our schema uses instrument_id (not ticker strings) and NUMERIC(38, 18) asset-agnostic ledger entries, extensions plug in modularly:

    • Options: Add contract metadata (underlying_id, strike, expiry, call/put, multiplier = 100), subscribe phones only to opened option chains (options feeds generate 10x+ equity quote volume!), add multi-leg spread margin rules, and run a 3:30 p.m. expiration-day risk sweep: because the Options Clearing Corporation automatically exercises contracts >= $0.01 in-the-money at close, accounts lacking the cash to buy 100 shares per contract are auto-closed or marked Do-Not-Exercise before the bell!
    • Crypto: Keep a separate legal-entity ledger sub-book; switch batch jobs to 24/7 zero-downtime rolling cutoffs (midnight UTC statements); route via REST/WebSocket to multiple crypto exchanges/market makers (since crypto has no single regulated NBBO); and integrate hot/cold wallet custody waiting N block confirmations before crediting withdrawable balances.

Intuition & how it works

Think of a retail brokerage like a bank vault welded to a live sports scoreboard. The bank vault (orders, cash holds, fills, and share balances) must be 100% exact down to the penny: every customer's data lives on one dedicated account shard (one of 32 PostgreSQL databases chosen by hash(account_id)) where checking buying power, locking cash, and recording an order happen inside a single atomic transaction backed by an append-only double-entry ledger (an accounting log where every debit has an equal and opposite credit so money can never appear or vanish). Meanwhile, the live scoreboard (streaming stock quotes) intentionally drops intermediate price flickers via conflation—bundling rapid exchange updates into at most 4 updates per second per stock—so 2 million open phones always see fresh prices without clogging network buffers, and calculate their own live profit-and-loss right on the device screen.

Why do naive microservice designs fail dangerously in trading? Splitting "check balance" and "place order" into two separate services without a shared lock lets a user tap Buy twice on two phones in the same millisecond and spend $1,000 twice with only $1,000 in cash. Retrying a timed-out order with a brand-new ID—either from the mobile app or over a dropped exchange connection—buys the stock a second time. And pushing every raw Wall Street tick (1,000,000 updates/sec at the 9:30 a.m. bell) into unbounded per-user WebSocket queues exhausts server RAM whenever commuters ride into cell-phone dead zones.

Let's trace a concrete 4-step lifecycle when Alice (account_id = 88, $600.00 settled cash) taps Buy 10 XYZ, Limit $50.00 with client_order_id = "c-1":

1. t = 0 ms (Atomic Accept + Hold on Shard #24):
   - Lock account 88; verify ("88", "c-1") is new; check buying_power ($600 >= $500).
   - Write double-entry hold: A.USD.settled -500.00, A.USD.held +500.00 (sum = 0).
   - Insert order #9001 (status='accepted', version=1) + outbox event -> return 201 in 18 ms.
   - (Alice's Wi-Fi blips and retries "c-1" -> hits UNIQUE(account_id, client_order_id) -> returns #9001!)

2. t = 25 ms (Smart Order Router -> Market Maker via FIX):
   - Router CAS-updates #9001 to status='sending' (version=2) so a concurrent Cancel cannot race,
     then sends FIX NewOrderSingle(ClOrdID=9001, qty=10, limit=50.00).

3. t = 45 ms (Fill Execution @ $49.90/share = $499.00 total, $1.00 price improvement):
   - FIX ExecutionReport(ExecID="ex-77", qty=10, price=49.90) arrives -> deduped on PRIMARY KEY(venue, exec_id).
   - Shard #24 atomically: marks #9001 'filled' (version=3), releases -500.00 held, refunds +1.00 to
     A.USD.settled, books +499.00 payable to clearing broker, credits +10 A.XYZ.unsettled, opens tax lot.
   - Pushes order(v3) + balance(buying_power=$101.00) over Alice's WebSocket; phone multiplies 10 x live quote!

4. Next business morning (T+1 Settlement + Reconciliation):
   - Morning recon confirms our books match the clearing broker's file -> moves +10 XYZ from unsettled to settled.

Key trade-offs

  • Account-sharded PostgreSQL with local ACID transactions vs. distributed microservices with sagas. Keeping orders, balances, ledger_entries, and tax_lots for an account on the same Postgres shard guarantees that risk holds and fills commit all-or-nothing at ~1,440 tx/s per shard without complex compensating rollback sagas. An in-memory single-threaded matching engine (the architecture exchanges use) reaches microsecond latency, which is overkill for a < 100 ms retail broker target and much harder to operate and audit.
  • Event-sourced journals + same-transaction projections vs. pure event replay. Appending immutable rows to ledger_entries and order_events preserves a regulator-ready audit trail and feeds Kafka via a transactional outbox (writing events to a SQL table in the same commit so DB and Kafka never diverge), while updating balances and orders in the same transaction keeps hot-path reads O(1) without replaying historical events.
  • Introducing broker + clearing broker vs. self-clearing. Partnering with a clearing broker avoids huge clearinghouse capital deposits and back-office plumbing, at the cost of per-trade clearing fees and mandatory daily reconciliation against the clearing broker's files before 9:30 a.m.
  • Synchronous cross-AZ DB replication vs. asynchronous replication. Waiting ~1–2 ms for a synchronous standby in a second Availability Zone to confirm every write (WAL, or Write-Ahead Log) ensures RPO = 0—an order we told the customer was Accepted is never lost if the primary machine dies.
  • Lossy conflated quote broadcast (~4 MB/s) vs. lossless per-tick routing. Coalescing quotes to 4 updates/s per stock and overwriting slow client socket buffers bounds gateway RAM and gives humans fresh prices, while routing every raw trade print separately to the Stop Trigger Engine ensures automated stop orders never miss a trigger price.
  • Rejecting market orders (while allowing limit orders) during a market-data outage. Blocking market orders briefly annoys users during a feed blackout, whereas accepting market orders against stale prices risks catastrophic fills far above the user's buying power; keeping limit orders open preserves a safe, price-capped path to trade.
  • Instant ACH buying power vs. waiting 3 business days. Fronting risk-scored credit (instant_avail / instant_used buckets) dramatically boosts new-user conversion in exchange for bounded ACH bounce risk, mitigated by blocking cash withdrawals against unsettled credit.

Common mistakes

  • Storing money or share quantities in binary floating-point (float / double). Binary floats cannot represent 0.10 exactly and accumulate penny rounding errors that break zero-sum ledgers; always use fixed-point NUMERIC decimals end to end.
  • Checking buying power outside an account-locked transaction. Reading balances in Service A and inserting orders in Service B without SELECT ... FOR UPDATE (or atomic CAS) allows double-spending on concurrent requests.
  • Retrying a timed-out venue send with a fresh ClOrdID. If a FIX connection drops before acknowledgment, the order is in an UNKNOWN state; re-sending under a new ID risks executing twice instead of recovering state via FIX sequence replay and clearing drop-copies.
  • Sending raw market orders without a limit collar, or firing stop orders on stale feed data. Uncollared market orders can fill above the cash hold during flash spikes, and unpaused stop engines trigger mass unfair liquidations on glitched ticks.
  • Allowing unsettled ACH instant credit to be withdrawn, or mistakenly subtracting unused instant credit from existing settled cash. Track instant_used separately from instant_avail so prior settled cash stays withdrawable while uncollected ACH funds remain locked inside brokerage positions.
  • Recomputing live portfolio PnL on the server for 2 million users on every price tick. Push positions once (and on fills) and stream conflated quotes so client devices compute (live_price - cost_basis) x qty locally at zero server CPU cost.
  • Relying on cloud autoscaling at 9:30:00 a.m. ET or forgetting corporate actions on open orders. Always pre-scale on a 9:00 a.m. schedule, pace overnight queued orders via venue token buckets, and adjust open GTC/stop orders and tax lots before the bell on stock-split mornings.

Follow-up questions

  • What happens during a viral rally when a single stock ticker drives 40% of total order volume? Because our PostgreSQL core is sharded by account_id rather than symbol, database writes remain spread evenly across all 32 shards! Pressure concentrates instead on external venue session caps and clearinghouse collateral: the Smart Order Router spills excess flow across backup wholesalers and exchanges (queuing in Kafka only if every venue session hits its in-flight cap), the symbol's Stop Trigger partition still runs in O(1) per trade print using min/max heaps, and Risk uses an instant config kill switch to flip that symbol to closing_only if clearinghouse deposit requirements spike.
  • How would you evolve the ledger and risk engine to support leveraged margin accounts? Unlike cash accounts—where buying power changes only on trades and transfers—margin buying power depends continuously on the live market value of every held stock! Add a symbol-subscribed Real-Time Margin Engine that tracks account equity against regulatory floors (50% initial margin under Federal Reserve Regulation T and 25% minimum maintenance under FINRA rules, plus stricter house multipliers for volatile or concentrated stocks), accrues daily interest on a margin_debit ledger bucket, enforces Pattern Day Trader checks in the OMS, and automatically restricts accounts to closing_only—or submits liquidation orders through the OMS—when live equity breaches maintenance thresholds.
  • If an account shard's primary database fails at 9:30:05 a.m. right as an investor submits a buy order, how are the order and cash protected? Because every shard commits synchronously to a standby in another Availability Zone before returning 201 Accepted, any acknowledged order (along with its hold and outbox event) is guaranteed to exist on the promoted standby (< 60 s failover), while any uncommitted in-flight transaction rolls back cleanly when the old primary is fenced and rewound (pg_rewind). Roughly 1/32 of users briefly see a retry prompt, and when their app retries with the exact same client_order_id, it either returns the surviving order (200 OK) or creates it once—guaranteeing zero lost orders and zero double-purchases.

Follow-up questions

Similar questions

More Fanatics interview questions

All 3 Fanatics questions →