Stock Ordering System (Order placement/cancellation, race conditions, future scheduling)

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2021-02-12

Problem Statement

Designing a Stock Ordering System for a trading platform (like Zerodha, Robinhood, E-Trade). The system must allow users to place, cancel, and execute stock orders with high reliability and low latency. It should also support future/delayed scheduling of orders, while ensuring correctness in the presence of concurrent transactions and race conditions.


Functional Requirements


1.Order Placement
•Users can place market orders, limit orders, and stop-loss orders.
•Orders must be validated for account balance, stock availability, and compliance.
•Orders should enter an Order Book for matching.
2.Order Matching & Execution
•Orders are matched against an exchange order book (bid/ask).
•Maintain price-time priority (FIFO within price level).
•Support partial fills (order may execute in chunks).
3.Order Cancellation/Modification
•Allow users to cancel or modify orders before execution.
•Race condition: Ensure no "double execution" if order is matched while cancellation is in progress.
4.Future/Daily Scheduled Orders
•Users can schedule orders for a specific time (e.g., "Buy 100 shares at 9:15 AM tomorrow").
•Orders should automatically move into the live book at the scheduled time.
5.Account & Portfolio Updates
•Deduct blocked funds for buy orders.
•Update positions, P&L, and balances after execution.
6.Notifications
•Real-time order status updates (pending, partial fill, executed, cancelled).
•WebSocket push to trading UI.


Non-Functional Requirements


•Low Latency: Sub-10ms for order placement & acknowledgement.
•High Throughput: Millions of concurrent orders during market open.
•Reliability: No order loss, exactly-once execution guarantee.
•Consistency: Strong consistency for balances and order states.
•Scalability: Must scale horizontally for peak trading volumes.


Core Components


•Order API Gateway → Handles order placement/cancellation requests.
•Order Service → Validates orders, checks balances, routes to matching engine.
•Order Matching Engine → Maintains in-memory order books (per symbol), matches buy/sell orders.
•Scheduling Service → Handles future orders, moves them into live books at scheduled times.
•Account Service → Tracks user funds, blocks balance during order placement.
•Portfolio Service → Updates positions after trades.
•Notification Service → Real-time push via WebSockets/Kafka.
•Persistence Layer → Durable storage of orders, trades, cancellations.


Data Model (Simplified)

1 2Orders(order_id PK, user_id, symbol, type, price, qty, status, scheduled_time, created_at, updated_at) 3Trades(trade_id PK, order_id, symbol, price, qty, executed_at) 4Accounts(user_id PK, balance, blocked_amount) 5Positions(user_id PK, symbol, qty, avg_price, updated_at)


Key Challenges & Race Conditions


1.Order Execution vs Cancellation
•If cancel request arrives while order is matching, ensure atomic decision.
•Use locks or CAS (compare-and-swap) operations on order state.
2.Concurrent Matching
•Multiple threads matching the same symbol → risk of double execution.
•Solve via partitioning per symbol (one matching engine instance owns one symbol).
3.Future Scheduling
•Orders scheduled for future should not be prematurely visible.
•Use delayed queue or cron-based scheduling service to activate.
4.Persistence & Recovery
•In case of crash, replay logs to restore order book.
•Ensure idempotent execution of trades.


External Integrations


•Stock Exchanges (NSE, NASDAQ, etc.) for real trades.
•Market Data Feed for live prices.
•Risk Management System (RMS) to check compliance & limits.


Trade-offs & Design Considerations


•In-memory vs DB Order Book → In-memory for speed, DB/logs for durability.
•Consistency vs Latency → Matching engine must prioritize correctness, even if slower under load.
•Scheduling Mechanism →
•Option A: Distributed scheduler (e.g., Quartz, Kafka delayed topic).
•Option B: Sharded in-memory timers per engine.
•Scalability → Partition order books per symbol, replicate read-only states for analytics.


👉 This HLD tests real-time trading system design, race condition handling, concurrency models, and scheduler design — all common in high-frequency trading interviews.

Solution

Comments