Designing a High-Throughput Order Management & Execution System
System DesignModel answerLast updated
Design a scalable retail brokerage order management system handling limit/market orders, cancellations, concurrency-safe account balances, and edge cases like lost/duplicate fill reports.
Design an Order Management and Execution System (OMS) for a retail stock brokerage. The system must process market orders and limit orders while allowing users to cancel unexecuted order remainders.
Key Requirements
-
Order Processing Lifecycle:
- Market Orders: Must execute immediately at the best available market price.
- Limit Orders: Must execute only at or better than the specified price (buy at/below limit price, sell at/above limit price). Unfilled portions remain pending until executed, expired, or cancelled.
- Cancellations: Users can request cancellations for active orders. Only the unfilled portion of the order is cancelled. Fills completed prior to or concurrently with the cancellation remain valid.
- Partial Fills: Orders can fill incrementally over time across multiple partial executions.
-
Account Balance & Inventory Management:
- Prevent double-spending of cash or over-selling of positions under concurrent requests (e.g., submitting multiple orders simultaneously).
- Ensure accurate updates to user balances (cash and shares) across fills, cancels, and rejections.
-
Fault Tolerance & Reliability:
- Guarantee idempotency for order submissions, exchange execution reports, and cancellations.
- Gracefully handle out-of-order execution reports, duplicate notifications, and exchange connectivity drops.
-
Scalability & Performance:
- Scale to handle millions of daily orders with extreme spikes during market open/close (e.g., peak loads of 10,000+ orders per second).
- Provide sub-second order acknowledgment latencies to end users.
Deliverables
Provide a architectural blueprint covering:
- Core Architecture & Functional Flow: High-level components and communication flows between clients, your OMS, and external execution venues/exchanges.
- Order Lifecycle & State Machine: Explicit state transitions, edge case handling (e.g., cancel/fill race conditions), and recovery from failures.
- Balance Management & Concurrency Control: Data schemas for cash/inventory, locking strategies, and reconciliation mechanics.
- Scalability & Data Storage Strategy: Partitioning scheme, database choices, caching strategy, and queueing/rate-limiting mechanisms for high volatility bursts.
Hints
Hint 1
Think about how to distinguish between total cash/shares and available cash/shares to prevent double-spending without needing global locks across all users.
Hint 2
Consider using a state machine where state transitions are idempotent. How do you handle a scenario where an Execution Report (FILL) arrives AFTER a CANCELLED confirmation, or vice versa?
Hint 3
What partition key will ensure that order updates and account balance updates for a given user land on the same database shard/event processing node?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level System Architecture
The Order Management System (OMS) sits between retail client applications (web/mobile) and external market venues (e.g., exchanges, Market Makers, or Smart Order Routers).
[ Client Apps ]
│
▼ (HTTPS / WebSockets)
[ API Gateway / Rate Limiter ]
│
▼ (gRPC)
[ Order Management Service (OMS) ] ◄──► [ Balance / Ledger Service ]
│ │
├── (Publish Event) ▼
▼ [(User DB / Ledger)]
[ Kafka / Event Bus ]
│
▼
[ Execution Gateway ] ◄── (FIX Protocol) ──► [ External Exchange / Market Maker ]
│
▼ (Execution Reports)
[ Ingestion & Settlement Worker ]
Component Breakdown
- API Gateway: Provides authentication, TLS termination, SSL pinning, and aggressive rate limiting per user/IP.
- Order Management Service (OMS): Stateless routing layer validating incoming payloads, checking idempotency keys, and orchestrating balance holds.
- Balance / Ledger Service: Manages accounts, balances, and reserved funds. Enforces strict transactional integrity to prevent over-allocation.
- Execution Gateway: Translates internal order schemas to financial messaging standards (e.g., FIX 4.2 / FIX 5.0) and manages persistent TCP connections to external market venues.
- Ingestion & Settlement Service: Asynchronously consumes execution reports from the market, updates order states, settles balance holds into actual positions, and emits updates to clients via WebSockets.
Part 1: Order Execution Flow, State Machine & Failure Handling
State Machine Definition
To handle partial fills, race conditions, and out-of-order execution reports safely, orders must transition strictly according to explicit rules:
┌────────────┐
│ PENDING │
│ CREATION │
└─────┬──────┘
│
▼
┌────────────┐
│ NEW │ (Acknowledged by OMS)
└─────┬──────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
┌───────────┐┌───────────┐┌───────────┐
│ REJECTED ││ SUBMITTED ││ EXPIRED │
└───────────┘└─────┬─────┘└───────────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
┌───────────┐┌───────────┐┌───────────┐
│ PARTIALLY ││ FILLED ││ PENDING │
│ FILLED │└───────────┘│ CANCEL │
└─────┬─────┘ └─────┬─────┘
│ │
├─────────────────────────┼──────────────┐
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│ FILLED │ │ CANCELLED │ │ PARTIALLY │
└───────────┘ └───────────┘ │ FILLED & │
│ CANCELLED │
└───────────┘
Valid State Transitions
PENDING_CREATION$\rightarrow$NEW(OMS accepted and validated order)NEW$\rightarrow$SUBMITTED(Sent to Exchange) ORREJECTED(Validation / Exchange Reject)SUBMITTED$\rightarrow$PARTIALLY_FILLED,FILLED,PENDING_CANCEL,EXPIREDPARTIALLY_FILLED$\rightarrow$PARTIALLY_FILLED,FILLED,PENDING_CANCELPENDING_CANCEL$\rightarrow$CANCELLED(if 0 executed before cancel),PARTIALLY_FILLED_AND_CANCELLED(if partial executed before cancel), or back toSUBMITTED/PARTIALLY_FILLED(if cancel request was rejected by Exchange).
Solving the Cancel vs. Fill Race Condition
A common issue occurs when a user submits a Cancel Order request at the exact moment the Exchange executes a Fill:
- Client sends Cancel Request: OMS transitions local status to
PENDING_CANCELand sends aOrderCancelRequest (35=F)to the exchange. - Exchange executes Fill concurrently: Before receiving the cancel request, the exchange matches the order and emits an
ExecutionReport (35=8, ExecType=FILL).
Resolution Protocol:
- Exchange authority: The external exchange is the absolute source of truth regarding order execution.
- If the exchange processes the Fill first, it responds to the Cancel Request with an
OrderCancelReject (35=9). - If the OMS receives a
FILLmessage while in statePENDING_CANCEL, the OMS must process the fill (decrementing remaining quantity). - When the exchange's
OrderCancelOkorOrderCancelRejectarrives, the OMS updates the terminal state accordingly:- If
OrderCancelOkarrives with executed quantity > 0 and remaining quantity = 0, state becomesPARTIALLY_FILLED_AND_CANCELLED. - Unfilled reserved balance is instantly unlocked and returned to the user's available balance.
- If
Failure Handling & Message Guarantee Mechanics
- Lost Execution Reports (Network Drop):
- Sequence Numbers (e.g., FIX
MsgSeqNum) are tracked for every venue connection. - On reconnect, the Execution Gateway sends a
ResendRequest (35=2)to replay missed execution reports.
- Sequence Numbers (e.g., FIX
- Duplicate Fills (At-Least-Once Delivery):
- Fills carry a unique
ExecIDgenerated by the venue. - The Ingestion Service maintains an
Idempotency Store(Redis + DB unique constraint onexec_id). If an incoming report contains an already processedExecID, it is safely acknowledged and ignored.
- Fills carry a unique
- OMS Process Crash mid-flight:
- Order creation uses a 2-Phase Write:
- Insert Order record with status
PENDING_CREATIONin DB. - Send payload to Kafka / Execution Gateway.
- Insert Order record with status
- A background Reconciler Worker queries orders stuck in
PENDING_CREATIONorPENDING_CANCELfor more than $N$ seconds and queries the venue viaOrderStatusRequest (35=H)to synchronize state.
- Order creation uses a 2-Phase Write:
Part 2: Balance & Inventory Management
To support rapid order submissions without race conditions or double-spending, we separate balance into Available and Reserved pools.
Database Schema (Relational / ACID compliance required)
user_accounts Table
| Column | Type | Description |
|---|---|---|
account_id | UUID (PK) | Unique user identifier |
cash_balance | DECIMAL(18,4) | Total cash settled |
cash_reserved | DECIMAL(18,4) | Cash locked for pending BUY orders |
user_positions Table
| Column | Type | Description |
|---|---|---|
account_id | UUID (PK) | Foreign key |
symbol | VARCHAR(10) (PK) | Stock Ticker (e.g., AAPL) |
share_balance | DECIMAL(18,4) | Total shares owned |
shares_reserved | DECIMAL(18,4) | Shares locked for pending SELL orders |
Atomic Reservation Strategy
To prevent race conditions where two simultaneous API requests attempt to spend the same cash, we use strict DB transactions with conditional checks (WHERE clause guards):
Scenario A: User places Buy Order (Limit Price = $150, Qty = 10 $\rightarrow$ Required Cash = $1,500)
-- Atomic Check-and-Reserve Cash
UPDATE user_accounts
SET cash_reserved = cash_reserved + 1500.00
WHERE account_id = 'usr_123'
AND (cash_balance - cash_reserved) >= 1500.00;
If updated rows = 0, throw INSUFFICIENT_FUNDS error immediately.
Market Order Handling:
Market orders do not specify a price limit. To prevent negative balances due to slippage, the system applies a Buffer Collar (e.g., locking $105%$ of the latest Ask price) before routing to the venue.
Execution Settlement Logic (Idempotent Execution Processing)
When a fill report arrives (executed_qty, executed_price, exec_id):
BEGIN TRANSACTION;
-- 1. Insert Execution Record (Fails on duplicate exec_id)
INSERT INTO order_executions (exec_id, order_id, qty, price, executed_at)
VALUES ('exec_abc123', 'ord_999', 10, 149.50, NOW());
-- 2. Adjust Order Quantities
UPDATE orders
SET filled_qty = filled_qty + 10,
status = CASE WHEN filled_qty + 10 = total_qty THEN 'FILLED' ELSE 'PARTIALLY_FILLED' END
WHERE order_id = 'ord_999';
-- 3. Settle Cash & Reserved Balance (For BUY Order)
-- Reserved cash locked at limit price ($150.00), actual execution was at $149.50 ($1,495.00 actual cost)
-- Unlock full $1,500 reserved; deduct actual $1,495 from total cash balance.
UPDATE user_accounts
SET cash_reserved = cash_reserved - 1500.00,
cash_balance = cash_balance - 1495.00
WHERE account_id = 'usr_123';
-- 4. Credit Shares to User Inventory
INSERT INTO user_positions (account_id, symbol, share_balance, shares_reserved)
VALUES ('usr_123', 'AAPL', 10, 0)
ON CONFLICT (account_id, symbol)
DO UPDATE SET share_balance = user_positions.share_balance + 10;
COMMIT;
Part 3: Scalability, Sharding & High-Throughput Strategy
System Sizing & Throughput Budget
- Daily Volume: 10 Million orders / day.
- Trading Window: 6.5 hours (23,400 seconds).
- Average Throughput: $\frac{10,000,000}{23,400} \approx 427 \text{ orders/sec}$.
- Peak Burst Factor (Market Open/Close): $25\times$ average $\approx \mathbf{10,500 \text{ orders/sec}}$.
Partitioning & Sharding Strategy
To process $10,000+$ ops/sec without encountering cross-node locks, all transactions for a specific user must execute sequentially on a single node.
Sharding Key: account_id
- Database Partitioning: Both
orders,user_accounts, anduser_positionstables are partitioned by Hash(account_id). - Kafka Partitioning: All events (
OrderIntent,CancelIntent) useaccount_idas the message partition key. This guarantees strict single-partition ordering per user while scaling horizontally across dozens of brokers.
┌──────────────────────┐
│ Kafka: order-intents │
└──────────┬───────────┘
│
┌────────────────┼────────────────┐
▼ ▼ ▼
Partition 0 Partition 1 Partition 2
(Hash: acc_0-33) (Hash: acc_34-66)(Hash: acc_67-99)
│ │ │
▼ ▼ ▼
[ OMS Worker 1 ] [ OMS Worker 2 ] [ OMS Worker 3 ]
Low Latency Execution & Volatility Protection
1. In-Memory Balance Ledger with Write-Ahead Log (WAL)
For ultra-low latency, reading and updating balances in a SQL DB during volatile spikes can cause bottlenecking.
- Pattern: Maintain account balances in an in-memory transactional cache (e.g., Redis cluster partitioned by
account_idor single-threaded custom ledger services like LMAX Disruptor pattern). - Flash balance changes to memory $\rightarrow$ append to an append-only WAL $\rightarrow$ asynchronously persist to Postgres.
2. Back-Pressure & Rate Limiting
- Token Bucket Rate Limiter at API Gateway (e.g., max 50 orders per second per user).
- Queue Load Shedding: If Kafka queue lag for order execution exceeds SLA thresholds (e.g., $>500\text{ms}$ processing delay), market orders are rejected early to protect users from unexpected price execution delays during flash crashes.
3. Execution Gateway Connection Pooling
- External venues limit the number of FIX connections. The Execution Gateway multiplexes thousands of user orders across pooled TCP/FIX session channels using persistent Session IDs.
Trade-offs and Key Takeaways
| Architecture Decision | Option Selected | Alternative Evaluated | Trade-off Rationale |
|---|---|---|---|
| Partition Key | account_id | symbol (Ticker) | Partitioning by account_id eliminates distributed transactions between balance checks and order creation. Internal order matching engines partition by symbol, but a brokerage OMS prioritizes balance safety per account. |
| Balance Lock Strategy | Ledger Hold (cash_reserved) | Pessimistic Locking (SELECT FOR UPDATE) | Pessimistic DB locking causes high lock contention and database timeouts under rapid bursts. Separate reserved counters allow non-blocking concurrent operations. |
| Messaging Infrastructure | Apache Kafka | RabbitMQ / Traditional Broker | Kafka provides immutable log replay capability which simplifies audit trails, reconciliations, and state rebuilds after system failures. |