Learning pathsPricingChecking sign-in…
GUIDED PRACTICE

Robinhood

Design a brokerage-style order and portfolio service for an interview.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
Order submission, exchange routing or portfolio display first?Authoritative orders and quote/portfolio projections are separate.
Buying-power holds and simultaneous orders?Funds reservation must prevent overspending atomically.
Exchange timeouts, partial fills and cancel races?Represent unknown outcomes and reconcile by stable order identity.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Robinhood: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Robinhood: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
HTTP: Hypertext Transfer ProtocolThe request/response protocol used by web APIs and media fetching. Application retries still need safe operation identities.
PK: Primary KeyThe declared row identity in a database schema; it does not automatically enforce every cross-row business rule.

Robinhood: Ledger and immutable revisions

What it means: A ledger is authoritative history of recorded monetary or obligation changes. Immutable revisions keep corrections auditable rather than overwriting the past.

Why this problem needs it: Cash, reservation and execution changes need explainable money history.

How to use it: Commit an expense/revision and its balanced deltas together, use integer minor units with a currency policy, and reconstruct balances from accepted facts.

Example in this design: A 1,000 cash balance minus four fills at 49 is 804; remaining reserve 302 leaves available cash 502 under the stated fee policy.

When it fits: Useful when edits, retries and reconciliation must preserve an explainable balance.

Alternative and limits: Mutable balances can be faster to read but still need safe revision history and reconciliation. Recording a settlement is not proof an external payment occurred.

Robinhood: Compare-and-set (CAS) and optimistic concurrency

What it means: A conditional write changes state only if an expected version or value still matches. The comparison and write share one atomic boundary.

Why this problem needs it: Orders and cancel/fill races require an owned current revision.

How to use it: Carry the version read by the caller; atomically compare, mutate and advance it. On conflict, re-read or reject under the business policy.

Example in this design: A stale cancellation cannot erase already committed fills.

When it fits: Useful when concurrent requests must not silently overwrite the same owned state.

Alternative and limits: Row locks or a serial owner can simplify highly contended updates. A read followed by an unconditional write is not CAS.

Robinhood: Idempotency key and stored operation result

What it means: Idempotency means replaying the same logical operation produces no additional business effect. A key identifies that operation under a defined scope.

Why this problem needs it: An exchange timeout must not silently create another order.

How to use it: Atomically associate a request key and payload fingerprint with its effect and result. Return the stored result on replay; reject incompatible payload reuse.

Example in this design: Preserve the external client order ID and reconcile its outcome.

When it fits: Needed when a timeout can hide a successful commit or a queue can redeliver.

Alternative and limits: Unique business identities can enforce selected effects. A cache of recent requests alone may expire too early or race; local keys cannot control an uncooperative external provider.

Robinhood: Projection and materialized view

What it means: A projection is a derived read model built from authoritative facts; it improves a particular read path and can be rebuilt.

Why this problem needs it: Portfolio views can be derived without controlling authoritative fills.

How to use it: Consume versioned facts with replay-safe updates, expose a watermark/revision, and compare or rebuild from the authoritative history.

Example in this design: A delayed position view exposes its revision rather than granting extra buying power.

When it fits: Useful when read shapes or volume justify duplicating computation/state.

Alternative and limits: Read authoritative rows directly for a simpler strongly current baseline. A stale projection must not grant revoked access or decide a strict inventory transition.

Interview scope and guarantees

Submit and cancel orders, display order status, show positions and buying power, and ingest external execution reports. This is an interview model, not a description of a broker’s implementation. Market data can lag; accepting an order must not over-reserve cash or securities.

Capacity worksheet

Assume 1 million users open the app at market start and 5% submit over one minute: about 833 order submissions/s. Quotes can update many times per second for popular symbols, so do not persist and fan out every tick through the transactional order path.

Concrete API contract

Contract / pseudocode
POST /orders {clientOrderId,symbol,side,quantity,type,limitPrice?}
POST /orders/{id}/cancel -> {cancelRequestId}
GET /orders/{id}
GET /accounts/{id}/positions

Data model and access paths

Contract / pseudocode
orders(id PK,account_id,client_order_id,request_hash,state,filled_qty,version); UNIQUE(account_id,client_order_id)
reservations(order_id UNIQUE,asset,quantity,state)
executions(venue,execution_id,order_id,qty,price); UNIQUE(venue,execution_id)
ledger_entries(transaction_id,line,account,asset,delta); PK(transaction_id,line)

Evolve a solution and explain each change

Three architecture decisions for Robinhood, including the pressure each introduces.
Three architecture decisions for Robinhood, including the pressure each introduces.
Read the diagram

Accept an order safely / Validate account and instrument; reserve the required buying power or position. / A cached balance can permit overspending.; Route and reconcile / Persist an order identity before sending to the execution venue and reconcile acknowledgements. / A route timeout can occur after venue acceptance.; Account for fills / Apply immutable fill identities to a ledger with partial-fill and cancellation states. / Cancellation requests can race with additional fills.

Open original
Robinhood · architecture decisions
Three architecture decisions for Robinhood, including the pressure each introduces.

Three architecture decisions for Robinhood, including the pressure each introduces.

Step 1: Accept an order safely

Validate account and instrument; reserve the required buying power or position. A cached balance can permit overspending.

Step 2: Route and reconcile

Persist an order identity before sending to the execution venue and reconcile acknowledgements. A route timeout can occur after venue acceptance.

Step 3: Account for fills

Apply immutable fill identities to a ledger with partial-fill and cancellation states. Cancellation requests can race with additional fills.

Responsibility overview

Connected responsibilities for Robinhood. Trace the authoritative and derived paths separately.
Connected responsibilities for Robinhood. Trace the authoritative and derived paths separately.
Read the diagram

Trader to Order API: place order; Order API to Order ledger: reserve and commit order; Order API to Venue: route client order ID; Venue to Reconciler: fills and acknowledgements; Reconciler to Order ledger: apply unique executions; Order API to Market projection: display quote projection

Open original
Robinhood · connected architecture
Connected responsibilities for Robinhood. Trace the authoritative and derived paths separately.

Connected responsibilities for Robinhood. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

A customer submits a limit buy for ten shares. The service reserves funds according to a conservative price/fee policy and records order o17 before routing. The venue accepts but the response is lost, so the service queries by the stable client order identity rather than placing a second order. Four shares fill before cancellation. The fill updates position and cash accounting exactly once using its venue fill ID; cancellation can only stop the remaining six if the venue confirms it. Release unused reservation after the final reconciled outcome. Quotes displayed in the app are not the authoritative execution price.

Why these access paths matter

Order lookup uses account and order identity; fills use a unique venue/execution identifier. Keep reservation and ledger transitions transactional within the account authority. Market-data projections and trading admission are separate systems. Use exact amounts and instrument quantity rules; a generic floating-point balance is not adequate accounting.

Build the baseline first

Robinhood: baseline request paths.
Robinhood · working baseline
Read the diagram

Order request → risk/reservation transaction → routing outbox; Venue report → deduplicated execution → ledger; Position projection → account view

Open original
Robinhood · working baseline
Robinhood: baseline request paths.

Robinhood · working baseline

  1. Order request → risk/reservation transaction → routing outbox.
  2. Venue report → deduplicated execution → ledger.
  3. Position projection → account view.

Evolve the design under load

Robinhood: additional scaling and recovery paths.
Robinhood · scale and recovery paths
Read the diagram

Market-data stream → symbol subscriptions → quote gateways; Account-key command routing → ordered risk decisions; Reconciliation feed → discrepancies → operations queue

Open original
Robinhood · scale and recovery paths
Robinhood: additional scaling and recovery paths.

Robinhood · scale and recovery paths

  1. Market-data stream → symbol subscriptions → quote gateways.
  2. Account-key command routing → ordered risk decisions.
  3. Reconciliation feed → discrepancies → operations queue.

Defend the hardest decision

Reserve buying power before routing a buy order. A market order needs a bounded risk policy because its final price is not known. Partial fills release or consume reservations incrementally and create immutable execution records. A cancel request is not a cancellation acknowledgement: a fill may win the race at the venue. Model pending-cancel explicitly and process authoritative execution reports.

Failure and recovery analysis

A routing timeout leaves uncertainty about whether the venue received the order. Retry with the same external client order ID if supported, query status and reconcile. Never create a fresh order ID just to escape the timeout. Duplicate fills must be rejected by venue execution identity; a local sequence alone is insufficient across reconnects.

Security and privacy boundary

Use strong account authorization, audit administrative actions, isolate market data from money movement, and never log trading credentials.

Interview follow-ups with reasoning

Question: How do you rebuild positions?

Show answer and explanation

Answer: Replay immutable ledger entries and compare with external statements.

Question: How do you handle out-of-order reports?

Show answer and explanation

Answer: Use venue sequencing and state transitions that accommodate partial fills.

Question: What if quotes stop?

Show answer and explanation

Answer: Mark them stale and apply order-type-specific risk controls.

Operate and verify the design

Uncertain order age, execution dedup hits, reservation discrepancies and venue-report lag.

Race a cancel acknowledgement with a partial fill and verify positions and reserved buying power.

A second scenario to test transfer

An order for 10 shares receives a fill for 4, then a timeout, then a second report for the same fill. Deduplicate the external report ID and apply only four shares. A later fill of 6 completes the order. The portfolio view advances from ledger events and reports its watermark; order accepted and order filled remain separate user-visible states.

An order submission times out and the client retries. Then one partial fill report is delivered twice. How many orders and position changes should exist?

Show answer and explanation

Answer: One logical order under the original client identity, and one position change for the unique partial-fill report. Resolve submission through the same external identity or reconciliation before resubmitting. External execution IDs deduplicate reports; the ledger records each accepted fill once.

Compare alternatives

StateMeaningCommon confusion
AcceptedDurable intent storedOrder reached the market
AcknowledgedExternal route confirmedOrder is filled
Partially filledSome execution reports appliedRemaining quantity is cancelled
Cancel pendingCancellation requestedNo more fills can occur

A design-changing exercise

A cancel request returns successfully from the API. Does that prove there will be no further fill?

Show answer and explanation

Answer: No. Distinguish accepted cancellation request from venue-confirmed final cancellation and reconcile fills already executed or racing with cancellation.

Design workshop: reserve buying power and apply fills once

Core scope is limit-order admission, venue routing, partial fills/cancel and portfolio display. Margin, options, tax and regulatory compliance are outside this interview baseline. This is a hypothetical software design, not investment advice or a representation of a broker's actual system. Choose exact quantity/currency arithmetic, no negative reserved buying power and quote freshness explicitly displayed.

Orders are unique(account_id,client_order_id); changing order parameters under the same identity returns conflict. Executions are unique(venue,execution_id), since a venue-local ID is not automatically globally unique. A cash account with $1,000 placing ten shares at a $50 limit and a $2 maximum fee reserves $502, leaving $498 available. A four-share fill at $49 consumes $196; remaining six shares need $300 plus the unspent fee reserve under the fee policy. Track reserved, available and settled/unsettled balances separately.

Cash and reservation example with no fee charged yet. Initial / $1,000 / $0 reserved; $1,000 available; 10 shares at $50 limit, $2 fee cap / $1,000 / $502 reserved; $498 available; 4 filled at $49 / $804 / $302 reserved; $502 available; Duplicate same venue execution / $804 / Unchanged; Confirmed cancel after event watermark closes / $804 / Release residual reserve; actual fee handled by policy
Cash and reservation example with no fee charged yet.
Read the diagram

Event / Cash balance / Reservation / available; Initial / $1,000 / $0 reserved; $1,000 available; 10 shares at $50 limit, $2 fee cap / $1,000 / $502 reserved; $498 available; 4 filled at $49 / $804 / $302 reserved; $502 available; Duplicate same venue execution / $804 / Unchanged; Confirmed cancel after event watermark closes / $804 / Release residual reserve; actual fee handled by policy

Open original
Cash and reservation example with no fee charged yet
Cash and reservation example with no fee charged yet. Initial / $1,000 / $0 reserved; $1,000 available; 10 shares at $50 limit, $2 fee cap / $1,000 / $502 reserved; $498 available; 4 filled at $49 / $804 / $302 reserved; $502 available; Duplicate same venue execution / $804 / Unchanged; Confirmed cancel after event watermark closes / $804 / Release residual reserve; actual fee handled by policy

Cash and reservation example with no fee charged yet.

An illustrative double-entry cash transfer for the $196 fill debits a customer-funds liability and credits a broker clearing payable by $196. An independent share ledger records +4 shares in customer holdings and −4 from the clearing allocation in the same asset. These balance per asset; dollars and shares cannot be summed as if the same unit. Settlement and fees append further entries. The account authority transaction checks reservation, inserts the unique execution, updates order filled quantity and posts the fill once.

Cancel and partial fill share a venue order boundary. Client to Order/account authority: Cancel order O; persist cancel intent; Order/account authority to Venue: Send cancel with stable route/order identity; Venue to Reconciler: Fill F1 for 4 shares arrives before cancel confirmation; Reconciler to Order/account authority: Unique venue/F1; apply partial fill and reservation change; Venue to Reconciler: Cancel confirms remaining 6; report watermark still has a gap; Reconciler to Order/account authority: Close earlier event gap, then release residual reserve and preserve fill F1
Cancel and partial fill share a venue order boundary.
Read the diagram

Cancel order O; persist cancel intent; Send cancel with stable route/order identity; Fill F1 for 4 shares arrives before cancel confirmation; Unique venue/F1; apply partial fill and reservation change; Cancel confirms remaining 6; report watermark still has a gap; Close earlier event gap, then release residual reserve and preserve fill F1

Open original
Cancel and partial fill share a venue order boundary
Cancel and partial fill share a venue order boundary. Client to Order/account authority: Cancel order O; persist cancel intent; Order/account authority to Venue: Send cancel with stable route/order identity; Venue to Reconciler: Fill F1 for 4 shares arrives before cancel confirmation; Reconciler to Order/account authority: Unique venue/F1; apply partial fill and reservation change; Venue to Reconciler: Cancel confirms remaining 6; report watermark still has a gap; Reconciler to Order/account authority: Close earlier event gap, then release residual reserve and preserve fill F1

Cancel and partial fill share a venue order boundary.

Design step 1: sequenced quotes and bounded fanout

Market data has its own authority, ordering and availability contract. Ingest a venue snapshot, then apply the contiguous sequenced suffix for each instrument/venue. A duplicate or older sequence is ignored; a gap marks the quote stream stale and triggers snapshot recovery. Do not make an orderable quote appear fresh just because a cache returned it quickly. The client receives asOf, venue sequence and a stale indicator, and the UI can keep displaying the last value while clearly marking its age.

Recover a sequenced quote stream and fan out bounded views. Venue feed to Market data ingestor: Publish snapshot and sequenced quote events; Market data ingestor to Quote store: Detect duplicate or missing sequence; recover gaps from snapshot plus suffix; Market data ingestor to Quote store: Commit latest valid quote and asOf watermark; Quote store to Fanout gateway: Coalesce display updates and bound slow-client buffers; Quote store to Fanout gateway: Expose quote sequence and freshness; never imply a stale value is current
Recover a sequenced quote stream and fan out bounded views.
Read the diagram

Publish snapshot and sequenced quote events; Detect duplicate or missing sequence; recover gaps from snapshot plus suffix; Commit latest valid quote and asOf watermark; Coalesce display updates and bound slow-client buffers; Expose quote sequence and freshness; never imply a stale value is current

Open original
Recover a sequenced quote stream and fan out bounded views
Recover a sequenced quote stream and fan out bounded views. Venue feed to Market data ingestor: Publish snapshot and sequenced quote events; Market data ingestor to Quote store: Detect duplicate or missing sequence; recover gaps from snapshot plus suffix; Market data ingestor to Quote store: Commit latest valid quote and asOf watermark; Quote store to Fanout gateway: Coalesce display updates and bound slow-client buffers; Quote store to Fanout gateway: Expose quote sequence and freshness; never imply a stale value is current

Recover a sequenced quote stream and fan out bounded views.

Quote fanout can dominate order processing. For an illustrative one million subscribers, two updates per second and 200 bytes per update imply 400 MB/s of payload before protocol overhead. Partition fanout by instrument and region, coalesce display-only updates within a freshness budget, and isolate it from the account/order authority. Execution reports and ledger writes remain durable even when optional chart or quote reads are throttled.

Design step 2: reserve before venue routing

For a long cash limit buy, available cash is cash balance − sum(open order reservations). Reserve quantity × limit price + fee cap in the same account transaction that creates the order and records its client idempotency key. Never size the reservation from a last-traded quote: price can move before execution. If the order is rejected, release the full reservation only after the venue rejection is authoritative. If it partially fills, reduce the remaining quantity and fee budget only as each unique execution is posted.

The model in examples/system-design/robinhood.py uses integer cents and whole shares to avoid floating-point money. It serializes each transition under a lock as a small executable stand-in for an account transaction. tests/test_robinhood_model.py tests stable client order IDs, quote freshness, nonnegative available cash, execution idempotency, asset-balanced entries and cancel/reconcile races.

Suggested APIs are GET /quotes?symbols=..., a sequenced quote subscription, POST /orders with clientOrderId, POST /orders/{id}/cancel, and GET /orders/{id} with order version, fill watermark and reservation state. On an identical create retry, return the same order ID and state. Reusing a client order ID with different terms is a conflict. A cancel endpoint returns cancel_pending, not cancelled, until the venue confirms the transition.

State progression is created→route_pending→acknowledged→partially_filled→filled, with cancel_pending orthogonal to outstanding quantity. A cancel request is not a venue-confirmed cancel; more fills can arrive meanwhile. Venue reports can repeat and be out of order. Persist report identity and cumulative/individual quantity semantics; missing sequence gaps trigger reconciliation. A trade bust/correction appends reversing/correcting execution-linked entries, never edits the original ledger history invisibly.

Order, fill and cancellation transitions. New valid client order / route_pending / Reserve limit notional and fee cap atomically; Venue acknowledges / acknowledged / Keep reserve for full remaining quantity; Unique partial execution / partially_filled / Consume actual cash; retain limit reserve on unfilled shares; Client requests cancel / cancel_pending / Keep unfilled reserve; fills may still race; Venue confirms cancel with complete event watermark / cancelled / Release only unfilled reserve after reconciling earlier fills; Unique fill reaches total quantity / filled / Release unused fee reserve; no remaining shares are cancellable
Order, fill and cancellation transitions.
Read the diagram

Event / Order state / Reservation rule; New valid client order / route_pending / Reserve limit notional and fee cap atomically; Venue acknowledges / acknowledged / Keep reserve for full remaining quantity; Unique partial execution / partially_filled / Consume actual cash; retain limit reserve on unfilled shares; Client requests cancel / cancel_pending / Keep unfilled reserve; fills may still race; Venue confirms cancel with complete event watermark / cancelled / Release only unfilled reserve after reconciling earlier fills; Unique fill reaches total quantity / filled / Release unused fee reserve; no remaining shares are cancellable

Open original
Order, fill and cancellation transitions
Order, fill and cancellation transitions. New valid client order / route_pending / Reserve limit notional and fee cap atomically; Venue acknowledges / acknowledged / Keep reserve for full remaining quantity; Unique partial execution / partially_filled / Consume actual cash; retain limit reserve on unfilled shares; Client requests cancel / cancel_pending / Keep unfilled reserve; fills may still race; Venue confirms cancel with complete event watermark / cancelled / Release only unfilled reserve after reconciling earlier fills; Unique fill reaches total quantity / filled / Release unused fee reserve; no remaining shares are cancellable

Order, fill and cancellation transitions.

Quotes arrive on a separate market-data stream keyed by instrument/venue sequence, with snapshot+suffix recovery. Gateways fan out subscriptions and bound slow-client buffers. A portfolio view displays its applied ledger watermark and quote timestamp; stale quotes cannot become authoritative buying-power updates. Trading admission still checks account funds and declared price/limit rules under its authority.

At one million quote subscribers for a popular instrument, fanout bandwidth can exceed order-write load. Batch quote display under a stated freshness budget while preserving execution events durably. Isolate the routing/account path from optional chart queries. Monitor venue sequence gaps, reserve reconciliation, unmatched fills, cancel age and quote age separately.

Design step 4: reconcile venue state into the ledger

Execution identity is (venue, execution_id), not an order ID or client retry key. In one account-scoped transaction, reject conflicting reuse, record the execution once, debit cash for notional and fee, credit the clearing counterpart, add shares to the customer position, reduce filled quantity, and recalculate the residual reservation. Cash cents and share units balance separately; never net them into one number. A delayed execution with a venue sequence before the cancellation watermark is still applied once, while a report after confirmed cancellation is rejected for reconciliation.

Reconcile executions before projecting balances. Venue adapter to Execution inbox: Deliver status and fill reports at least once; Execution inbox to Account ledger: Deduplicate by venue/execution ID; retain sequence gaps; Account ledger to Account ledger: Apply cash, fee and share entries atomically per unique fill; Account ledger to Portfolio projection: Advance account ledger watermark and publish projection update; Execution inbox to Venue adapter: Fetch missing execution suffix through the last durable venue watermark
Reconcile executions before projecting balances.
Read the diagram

Deliver status and fill reports at least once; Deduplicate by venue/execution ID; retain sequence gaps; Apply cash, fee and share entries atomically per unique fill; Advance account ledger watermark and publish projection update; Fetch missing execution suffix through the last durable venue watermark

Open original
Reconcile executions before projecting balances
Reconcile executions before projecting balances. Venue adapter to Execution inbox: Deliver status and fill reports at least once; Execution inbox to Account ledger: Deduplicate by venue/execution ID; retain sequence gaps; Account ledger to Account ledger: Apply cash, fee and share entries atomically per unique fill; Account ledger to Portfolio projection: Advance account ledger watermark and publish projection update; Execution inbox to Venue adapter: Fetch missing execution suffix through the last durable venue watermark

Reconcile executions before projecting balances.

The reconciler compares venue order status and execution IDs through an explicit watermark. It replays missing fills through the same idempotent transaction rather than applying a special correction path. Portfolio views report their ledger watermark so readers can distinguish an updated quote from a position that has not yet incorporated a late fill. If venue recovery is unavailable, retain the reservation and flag the order for operations rather than inventing a terminal state.

Final topology and operational contract

Robinhood final topology: authorities and work bounds. Quotes / Venue sequence and snapshot watermark / Async ingest; coalesced fanout buffers / Gap means stale until recovered; Order admission / Account cash, order and reservation transaction / Synchronous bounded account write / Available cash never goes below zero; Venue routing / Stable client order ID and route state / Async bounded in-flight requests / Cancel request is not cancel confirmation; Executions / Unique venue execution and append-only balanced ledger / Async inbox and account transaction / Each execution changes cash and shares once; Portfolio / Ledger watermark plus quote asOf / Derived read projection / Display freshness and account watermark separately
Robinhood final topology: authorities and work bounds.
Read the diagram

Path / Authority / Mode and bound / Invariant; Quotes / Venue sequence and snapshot watermark / Async ingest; coalesced fanout buffers / Gap means stale until recovered; Order admission / Account cash, order and reservation transaction / Synchronous bounded account write / Available cash never goes below zero; Venue routing / Stable client order ID and route state / Async bounded in-flight requests / Cancel request is not cancel confirmation; Executions / Unique venue execution and append-only balanced ledger / Async inbox and account transaction / Each execution changes cash and shares once; Portfolio / Ledger watermark plus quote asOf / Derived read projection / Display freshness and account watermark separately

Open original
Robinhood final topology: authorities and work bounds
Robinhood final topology: authorities and work bounds. Quotes / Venue sequence and snapshot watermark / Async ingest; coalesced fanout buffers / Gap means stale until recovered; Order admission / Account cash, order and reservation transaction / Synchronous bounded account write / Available cash never goes below zero; Venue routing / Stable client order ID and route state / Async bounded in-flight requests / Cancel request is not cancel confirmation; Executions / Unique venue execution and append-only balanced ledger / Async inbox and account transaction / Each execution changes cash and shares once; Portfolio / Ledger watermark plus quote asOf / Derived read projection / Display freshness and account watermark separately

Robinhood final topology: authorities and work bounds.

Duplicate fill, reordered status and cancel race. Venue adapter to Account authority: Deliver partial fill F1, then duplicate F1; unique key applies it once; Venue adapter to Account authority: Deliver cancel confirmation sequence 12 before missing event sequence 11; Account authority to Reconciler: Keep residual reserve locked while the sequence gap is unresolved; Venue adapter to Reconciler: Reconcile sequence 11 as pre-cancel fill; apply once and close the gap; Account authority to Portfolio reader: Publish ledger watermark only after cash and shares balance; Portfolio reader to Account authority: Reader observes the updated position and source watermark
Duplicate fill, reordered status and cancel race.
Read the diagram

Deliver partial fill F1, then duplicate F1; unique key applies it once; Deliver cancel confirmation sequence 12 before missing event sequence 11; Keep residual reserve locked while the sequence gap is unresolved; Reconcile sequence 11 as pre-cancel fill; apply once and close the gap; Publish ledger watermark only after cash and shares balance; Reader observes the updated position and source watermark

Open original
Duplicate fill, reordered status and cancel race
Duplicate fill, reordered status and cancel race. Venue adapter to Account authority: Deliver partial fill F1, then duplicate F1; unique key applies it once; Venue adapter to Account authority: Deliver cancel confirmation sequence 12 before missing event sequence 11; Account authority to Reconciler: Keep residual reserve locked while the sequence gap is unresolved; Venue adapter to Reconciler: Reconcile sequence 11 as pre-cancel fill; apply once and close the gap; Account authority to Portfolio reader: Publish ledger watermark only after cash and shares balance; Portfolio reader to Account authority: Reader observes the updated position and source watermark

Duplicate fill, reordered status and cancel race.

Exercise: The same four-share fill is reported twice after a cancel request. How many position changes occur?

Show answer and explanation

Answer: One under unique(venue,execution_id). Cancel pending does not erase an accepted fill. Release only confirmed unfilled reservation; duplicate report handling must not apply another cash/share movement.

Operations and practice

SLIs: quote age and sequence-gap duration by venue/instrument; order-admission latency and rejection reason; time from route to venue acknowledgment; cancel-pending age; unmatched execution count; reconciliation watermark lag; buying-power reservation difference; ledger imbalance; and portfolio projection lag. Alert on a nonzero accounting imbalance immediately, with a separate threshold for stale display quotes.

Overload and recovery: coalesce or shed display-only quote updates for slow clients, but preserve venue execution events and account writes. Bound per-account order requests, venue in-flight calls, report inbox depth and reconciliation batch size. On venue disconnect, stop new routes if order state cannot be established, retain reservations, persist inbound sequence checkpoints, then fetch a snapshot and replay the missing suffix. Resume after open orders, fills and balances reconcile; route uncertain orders only with the same stable venue identity.

Access and cost: authorize every order and cancel against the owning account; encrypt identity and account data; isolate quote entitlements and audit administrative repair. Venue connectivity, market-data licensing and high-fanout network egress dominate variable cost. Keep market-data and execution credentials separate, and require dual review for manual ledger adjustments.

Practice prompt: Design a cash-only limit-order system with sequenced quotes, external venue routing, partial fills, cancels and a portfolio view. Show the account reservation transaction, fill ledger, quote freshness contract and recovery path. Use the $1,000 example above and calculate cash, reserved amount and available buying power after the four-share fill.

Failure follow-up: The venue sends a four-share fill twice, then a cancel acknowledgment arrives before an earlier sequence event. Explain which data is authoritative, whether the reserve can be released, and how the portfolio catches up.

Rubric: The invariant is that available buying power never becomes negative and each (venue, execution_id) changes the account once. A strong answer reserves against the limit plus fee cap before routing, treats cancel as pending until confirmed, retains reserve across sequence gaps, posts balanced cash/share entries, and reconciles the venue through a watermark before publishing a final portfolio state. It distinguishes quote freshness from ledger freshness and bounds fanout separately from financial writes.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Duplicate a fill, reorder status messages, and race cancel with execution; reserved funds and position changes reconcile.

Operational contract

AreaDecision and signals
SLIsQuote age/sequence gaps; order-ack latency; fill/cancel reconciliation lag; ledger imbalance; rejected stale events.
Overload limitsBound market-data fanout, order submissions per account/venue, callback backlog, and reconciliation queries.
RecoveryReconcile venue order/execution reports before retrying unknown commands; rebuild user projections from immutable ledger events.
Access controlsEnforce account authorization, least-privilege venue credentials, audit trails, and sensitive financial-data controls.
Dominant costMarket-data feeds, venue/provider charges, and durable ledger/event retention.

Senior-level interviewer follow-ups

Question: A cancel request races with a partial fill. How does the displayed position change?

Show answer and explanation

Answer: Apply each venue execution identity once to cash and share ledgers. Keep the remaining reserve while cancel is pending; if a cancellation watermark has a sequence gap, reconcile earlier events before releasing it. The portfolio projection advances only after the ledger update.

Question: Why can a cached buying-power value not authorize an order?

Show answer and explanation

Answer: It may be stale relative to reservations, fills, or corrections. The authoritative risk transaction reserves funds or buying power against a versioned account state before sending the order.

A 60-second design answer

I would treat order acceptance, venue execution, and account ledger as distinct durable facts. An idempotent command reserves buying power before dispatch; venue executions use unique venue/execution identities and update a balanced ledger. Cancel/fill races are reconciled from venue state, while portfolio views are derived. I would monitor unknown orders, reconciliation lag, ledger imbalance, and stale quotes.

Dealing with Contention PostgreSQL

Technical references

Provider idempotency contract example.

PostgreSQL transaction isolation and concurrent updates.

Reconcile reserved value and exchange facts

An order reserves 100 minor units of buying power under this simplified exercise. A confirmed partial fill settles 40; 60 remains reserved until the applicable cancel/remaining-fill facts resolve. A duplicate fill does not settle another 40. A cancel request is pending until the exchange outcome is known; an in-flight fill can legitimately arrive around that boundary.

Contract / pseudocode
initial reserved: 100
fill f7 accepted once: settled 40; remaining reserved 60
duplicate f7: unchanged
cancel remaining confirmed: release applicable 60
initial reserved: 100; fill f7 accepted once: settled 40; remaining reserved 60; duplicate f7: unchanged; cancel remaining confirmed: release applicable 60
Reconcile reserved value and exchange facts
Read the diagram

initial reserved: 100; fill f7 accepted once: settled 40; remaining reserved 60; duplicate f7: unchanged; cancel remaining confirmed: release applicable 60

Open original
Reconcile reserved value and exchange facts
initial reserved: 100; fill f7 accepted once: settled 40; remaining reserved 60; duplicate f7: unchanged; cancel remaining confirmed: release applicable 60

Reconcile reserved value and exchange facts

Track order, replace/cancel operation, exchange reference and fill identity independently. Price stream sequence/freshness is a separate projection: recovering a market-data gap does not modify settled money. Use integer amounts with explicit currency/instrument units and appropriate accounting rules; this fixture omits real exchange/fee complexity.

Show answer and explanation

Answer: Never release all 100 simply because the cancel HTTP request returned. Resolve the authoritative remaining quantity/value, preserve fills and reconcile uncertain outcomes before changing spendable balance.

Decision review: Robinhood

Robinhood: What it is

A trading exercise accepts order intent, reserves buying power and derives positions from acknowledged exchange or broker facts.

Robinhood: Why it is needed

A client cancel request does not prove cancellation, and partial fills must update cash, shares and remaining reservations consistently.

Robinhood: When to use it

Use authoritative order/report identities when fills, rejects and cancellation can arrive late or out of order.

Robinhood: How to use it

Persist the order and reserve its declared maximum exposure. Ingest immutable report identities, apply valid transitions or reconcile sequences, and recompute remaining reservations from accepted fills and open quantity.

Robinhood: Compare an alternative

A cached portfolio is useful for browsing but cannot grant buying power. Margin, short selling or market orders require different risk policies than this cash-only bounded-limit exercise.

Robinhood: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

A 1,000-unit cash account orders 10 shares at limit 50 with fee cap 2, reserving 502. Four shares fill at 49 with no fee yet posted: cash becomes 804. Keeping a full 2-unit fee reserve leaves 302 reserved for six shares and 502 available.

Robinhood: Cash 1000; reserve 10 x 50 + fee cap 2 = 502; Four shares fill at 49: cash 804; Six open shares + fee reserve = 302; Available cash = 804 - 302 = 502
Robinhood: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

Cash 1000; reserve 10 x 50 + fee cap 2 = 502; Four shares fill at 49: cash 804; Six open shares + fee reserve = 302; Available cash = 804 - 302 = 502

Open original
Robinhood: worked example
Robinhood: Cash 1000; reserve 10 x 50 + fee cap 2 = 502; Four shares fill at 49: cash 804; Six open shares + fee reserve = 302; Available cash = 804 - 302 = 502

Robinhood: a concrete state and recovery trace under the exercise assumptions.

Does requesting cancellation allow all 302 reserved units to be released immediately?

Show answer and explanation

Answer: Only a confirming fact or explicit risk protocol can establish the remaining quantity is no longer executable. A fill can race cancellation. Reconcile reports using their declared identity/order contract and retain sufficient reservation until the open exposure is resolved.

Robinhood: Check the design

Inspect reserved exposure, unmatched reports, late fills and ledger/position reconciliation. Label the fee assumption and currency unit before doing arithmetic.

Trading extension: preserve executable exposure through change

Start with the cash-only limit-order, fill and cancellation baseline. This workshop extends it through pending replacement, linked execution corrections and independently watermarked account/quote views. The local arithmetic assumes a declared atomic venue replacement contract; independent cancel-and-new routing requires a different risk bound.

Deep dive: a requested replacement is not a new effective order

The existing cash-only limit-order exercise already reserves buying power, applies unique executions and reconciles cancellation. This workshop adds replacement exposure, execution corrections and explicit account/projection evidence. It remains a hypothetical software design with whole shares, integer cents and declared fee assumptions; margin, market orders and actual venue-specific risk rules are outside this baseline.

Pin order terms and the operation chain

An order has immutable original identity plus acknowledged revisions. A cancel or replace operation has its own account-scoped key, canonical payload, expected order revision and venue reference. Preserve a chain from original client order through replacement acknowledgments. A retry resolves the same accepted operation; another key is not safe recovery for an uncertain old route.

Contract / pseudocode
order(account, id, acknowledged_revision, total_qty, filled_qty, limit_minor,
      fee_budget_minor, active_venue_ref, state)
order_operation(id, order_id, kind, expected_revision, payload_hash,
                proposed_total_qty, proposed_limit, venue_key, state)
execution(scope, execution_id, original_execution_id, kind,
          qty, price_minor, fee_minor, account, instrument)
risk_reservation(order_id, revision, exposure_minor, uncertainty_state)
account_event(account, ledger_position, operation_or_execution, postings)
projection(account, complete_ledger_position, quote_session, quote_position)

Quantity must say total order quantity or remaining quantity. This variant replaces total quantity; remaining is new total minus already accepted fills. Reject a proposed total below filled quantity under this chosen policy. Bind account, instrument, side, currency and requested terms; a signed report for another account/order is not applicable evidence. Execution ID scope follows the negotiated venue contract. If IDs reset by session or business day, include that scope; the baseline's venue/ID pair assumes venue-wide uniqueness.

Reserve the permitted worst case before replace dispatch

Initial cash is 100,000 cents. Ten shares at a 5,000-cent limit plus a 200-cent fee cap reserve 50,200, leaving 49,800 available. Four shares fill at 4,900 with zero fees posted: cash becomes 80,400; six remaining at 5,000 plus the full fee budget require 30,200, leaving 50,200 available.

Now request total quantity twelve at a 5,500-cent limit. Eight remaining shares plus 200 fee cents require 44,200. Under a venue contract guaranteeing an atomic mutually exclusive replace, keep the maximum permitted old/new exposure: max(30,200,44,200)=44,200, provisionally reserving another 14,000 and leaving 36,200 available. This maximum rule is not valid for independent cancel-and-new requests that can both remain executable; those need the combined worst-case exposure or sequentially confirmed cancellation.

Do not reduce risk merely because the client requested fewer shares or a lower limit. The old order can still execute while replacement is pending. If two more old-revision shares fill at 5,000, cash becomes 70,400 and filled quantity six. Old residual exposure is 20,200; proposed residual is 33,200. Recompute from accepted fills, keeping the permitted worst case until replacement/cancellation evidence is complete. A rejected replacement retains the old acknowledged terms and their current residual risk, not the original pre-fill reservation.

Distinguish pending commands from venue facts

A replace acknowledgment changes effective terms only under the venue's applicable acceptance/order protocol. The FIX order-state scenarios (EP258, July 2020) are a primary reference for pending cancel/replace, intervening executions and corrections; this exercise's risk equations and adapter assumptions are additional application contracts, not universal FIX guarantees.

A fill can arrive while replacement is pending and reference the earlier revision. Persist execution identity and ordering evidence, apply it once to cash/shares, and recompute exposure. A replacement acknowledgment cannot erase those fills. Distinguish individual execution deltas from cumulative filled-quantity observations: adding a cumulative value as another execution double-counts activity. Reconcile disagreement rather than inventing an execution from whichever field arrived last.

Trading replace recovery: revision 1 remains executable; replace R reserves worst-case revision 2 exposure; an old-revision fill arrives; risk recomputes under pending R; only complete replacement evidence changes effective terms
Provisional risk covers the actual allowed exposure while command outcome is unknown.
Read the diagram

Revision 1 remains executable → Replace R reserves revision 2 worst case → An old-revision fill arrives → Risk recomputes while R stays pending → Complete venue evidence changes terms

Open original
Robinhood: recovery decision
Trading replace recovery: revision 1 remains executable; replace R reserves worst-case revision 2 exposure; an old-revision fill arrives; risk recomputes under pending R; only complete replacement evidence changes effective terms

Provisional risk covers the actual allowed exposure while command outcome is unknown.

Use complete report evidence before releasing exposure

A session receiving report 52 while 51 is missing has a maximum observed position of 52, not a complete prefix through 52. A cancel/replace status at 52 may depend on prior executions. Retain sufficient reserve and flag uncertainty until the gap or an authoritative compatible snapshot/execution set resolves it. Eventual quote recovery cannot fill an execution-report gap; they are different streams and authorities.

A definitive cancellation can release only the confirmed unfilled risk under the declared evidence boundary. Ordinary new fills inconsistent with terminal order history require investigation. A later authenticated trade bust/correction is a different event type linked to the original execution and may legitimately amend accounting after an order became terminal; do not blanket-drop it as just another late new fill.

Post a correction as an immutable referenced reversal/replacement under its own identity. Deduplicate it and validate original account, instrument, quantity and correction chain. Cash and shares balance separately. If a valid correction creates a deficit or uncertain executable exposure, record the real fact and block or restrict new orders under the risk policy; never discard external evidence just to keep a displayed invariant green. Recalculate exposure and reconcile against authoritative venue facts before making returned funds spendable.

Publish portfolio evidence and bound recovery

A portfolio projection reports its complete applied account-ledger position and quote as-of/session independently. Fresh price does not prove position freshness, and a high observed ledger event does not prove all earlier postings were applied. Join views at declared boundaries or show their distinct ages. Authoritative order admission rechecks account risk rather than trusting the cached portfolio's buying power.

At 5,000 execution reports/s with an average of four ledger lines, the writer faces 20,000 lines/s before indexes/replication; duplicate intake and replay have separate processing costs even when they create no new postings. A ten-minute gap outage at 100 unresolved orders/s creates 60,000 cases. Recovery at 250/s with 100/s new cases has 150/s useful drain, requiring at least 400 seconds. Quote fanout must not consume this financial recovery capacity.

Track pending replace/cancel age, unmatched execution identity, complete report lag, risk/venue discrepancy, correction backlog and portfolio watermark lag. Canary adapters with out-of-order fills, corrections after cancel, changed ID scope and lost replacement replies. Restore accepted operation chains and fee policies during failover; rollback cannot reinterpret an admitted replacement or erase executions already accepted.

Trading assessment: preserve executable exposure

Question: A client asks to lower the limit, but the venue has not acknowledged replacement. May the account immediately spend the released difference?

Show answer and explanation

Answer: No. Old terms can still execute. Retain the permitted worst-case exposure until the relevant complete venue evidence changes the effective order.

Question: Can max(old,new) reserve be used when cancel and new are independently routed?

Show answer and explanation

Answer: Not if both can execute. Reserve their combined permitted exposure or confirm old cancellation before routing the new order.

Question: A linked trade correction arrives after cancellation. Must every post-cancel report be discarded?

Show answer and explanation

Answer: No. Distinguish new-fill inconsistency from a valid correction. Append referenced entries, reconcile exposure and restrict new activity if necessary.

Score one point for scoped order/replacement/execution identity, explicit quantity/fee/worst-case risk arithmetic, complete venue evidence and pending-command semantics, immutable correction handling, and separately watermarked bounded account/quote views. Compare Payments, Ledger and Time and Ordering.

30:00Self-guided practice timer
The timer resets when you leave this page. Save your design separately.
Your challenge

An order submission times out and the client retries. Then one partial fill report is delivered twice. How many orders and position changes should exist?

Your design draft

Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.

Read study notes

Self-review checklist

Self-guided practice. Automated AI feedback and code execution are not connected.