Getting Ready: Stock Brokerage
Why This Problem Matters
Stock exchanges and brokerage platforms are among the most performance-critical, correctness-sensitive systems in software engineering. The New York Stock Exchange processes over 3 billion messages per day, with the matching engine handling tens of millions of order executions during peak hours. A single bug in the order matching logic can cost millions of dollars in incorrect trades. Platforms like Robinhood, Zerodha, Interactive Brokers, and Charles Schwab must match buy and sell orders at the best available price, maintain a real-time order book, and notify traders of price movements — all while guaranteeing that no order is lost and that price-time priority is strictly enforced.
What makes the Online Stock Brokerage System an excellent hard-difficulty LLD problem is the convergence of several demanding design challenges:
- Order book as a data structure — The order book is the central artifact: it maintains all outstanding buy orders (bids) sorted by price descending, and all outstanding sell orders (asks) sorted by price ascending. Each price level is a FIFO queue of orders at that price. This is not a simple list — it's a purpose-built data structure that determines the entire system's behavior.
- Matching engine with price-time priority — When a new order arrives, the matching engine must determine whether it can be filled immediately (fully or partially) against existing orders on the opposite side. Market orders execute at the best available price; limit orders execute only when the price condition is met. The matching algorithm enforces price-time priority: better-priced orders fill first, and among orders at the same price, the earlier order fills first.
- Multiple order types — Market orders (execute immediately at best price), limit orders (execute only at a specified price or better), and their variants create distinct flows through the matching engine. Each type has different validation rules, different matching behavior, and different lifecycle states (Pending → Partially Filled → Filled, or Cancelled).
- Price alert subscriptions — Traders subscribe to price alerts: "Notify me when AAPL crosses $150." The system must efficiently check alert conditions on every trade execution and fan out notifications without blocking the matching engine. This is a textbook Observer Pattern application.
- Order as a command — Each order (buy, sell, cancel) is an immutable request that can be logged, validated, queued, and executed — a natural fit for the Command Pattern. This enables order audit trails and potential undo/replay capabilities.
This problem appears in LLD interviews at Goldman Sachs, Morgan Stanley, Tower Research, Zerodha, Robinhood, Bloomberg, and fintech startups because it tests whether candidates can design a data-structure-intensive, correctness-critical system where the matching algorithm is the core intellectual challenge — not just CRUD.
What You'll Learn
By the end of this design problem, you will be able to:
- Design an order book data structure — model bids and asks as price-sorted collections of FIFO order queues, supporting O(log n) insertion and O(1) best-price retrieval
- Implement a matching engine — write the algorithm that matches incoming orders against the order book using price-time priority, handling full fills, partial fills, and unmatched limit orders
- Model multiple order types — design Market Orders (immediate execution at best price) and Limit Orders (conditional execution at specified price) with distinct validation and matching behavior
- Build a price alert system — apply the Observer Pattern so traders can subscribe to price-crossing alerts that fire on every trade execution without coupling the alerting logic to the matching engine
- Apply the Command Pattern to orders — model buy, sell, and cancel operations as command objects with validation, execution, and logging capabilities
- Create three UML diagrams — Use Case Diagram (actors and capabilities), Class Diagram (structural blueprint of the brokerage), and Sequence Diagram (place-an-order flow through the matching engine)
- Write complete implementations in Python and Java, split across two focused tutorials: Order Book data structure and Matching Engine algorithm
- Apply and justify three design patterns — Command (order lifecycle), Observer (price alerts), and Strategy (order matching) — explaining why each fits and what alternatives were rejected
Prerequisites
Before starting this problem, make sure you're comfortable with:
- OOP Relationships — especially Composition (an OrderBook composes its price-level queues) and Association (an Order references a Stock and a Trader) — Fundamentals S4
- Inheritance & Polymorphism — used for order type polymorphism (MarketOrder, LimitOrder extending Order) and Strategy-based matching — Fundamentals S3
- Command Pattern — how operations are encapsulated as objects with execute/validate methods — Fundamentals S12. This is how orders flow through the system.
- Observer Pattern — how subjects notify observers of state changes — Fundamentals S12. Applied to price alert subscriptions.
- Strategy Pattern — how interchangeable algorithms avoid conditional logic — Fundamentals S12. Applied to matching strategies.
- UML Class Diagrams — reading class boxes, relationship arrows, and multiplicities — Fundamentals S5
- UML Sequence Diagrams — reading lifelines, messages, and activation bars — Fundamentals S5
- Basic data structures — sorted maps/trees and FIFO queues. The order book uses a sorted collection of queues, similar to a priority queue with secondary ordering.
If you've completed the Online Shopping System (DP20), you've already worked with order state management and payment flows. This problem goes deeper into the algorithmic core — the matching engine — while requiring less UI/UX modeling.
Problem Scope
We will design: The core domain logic of an Online Stock Brokerage — stock catalog and portfolio management, order submission and validation, the order book data structure, the matching engine with price-time priority, trade execution recording, price alert subscriptions and notifications. All modeled as an object-oriented system with clear class hierarchies and design patterns.
We will NOT design: Network protocols (FIX/FAST), real-time market data feeds, distributed systems or horizontal scaling, database persistence, REST APIs, charting/visualization, margin trading and short selling, regulatory compliance engines, or Options/Futures derivatives. This is a Low Level Design (object-oriented) exercise, not a System Design (infrastructure) problem.
Key distinction from similar problems:
- Unlike the Online Auction System (DP27), which has time-bounded bidding events with a single winner, the Stock Brokerage operates a continuous double auction — buy and sell orders match continuously with no ending time, and the best bid/ask prices change with every trade
- Unlike the Digital Wallet Service (DP16), which handles simple credit/debit transfers between accounts, the Stock Brokerage must match two-sided orders against each other using a price-time priority algorithm — the wallet has known parties, but the brokerage must discover the counterparty
- Unlike the Online Shopping System (DP20), where prices are fixed by the seller, in the brokerage system prices are discovered through order matching — the market price is simply the price of the last executed trade