Bird
Raised Fist0

Design an Online Stock Brokerage - Portfolio, Trade, Order, Market Data, P&L

LLDmediumInterview freq: medium
Choose your preparation mode4 modes available
🏗️
Design an Online Stock Brokerage - Portfolio, Trade, Order, Market Data, P&L
Low-level design of an online stock brokerage system focusing on portfolio management, trade execution, order handling, market data integration, and profit & loss calculation.
mediumFinancial and E-Commerce OOPFreq: medium
Prerequisites:OOP FundamentalsJava Concurrency BasicsDesign Patterns (Factory, Observer, Strategy)SOLID Principles
⚙️
Functional Requirements
  • Maintain portfolio with multiple securities and quantities
  • Support placing, modifying, and canceling orders (market, limit)
  • Execute trades atomically and update portfolio accordingly
  • Calculate real-time P&L per security and overall portfolio
  • Ingest and update market data with thread-safe mechanisms
  • Ensure thread-safe concurrent access to portfolio and orders
  • Provide order status tracking and history
👤
Use Cases
  • Trader views portfolio holdings and P&L
  • Trader places market and limit orders
  • System executes trades based on orders
  • System updates portfolio and P&L after trade execution
  • System receives and updates real-time market data
  • Trader cancels or modifies open orders
🧑‍💻
Actors
  • Trader
  • Brokerage System
  • Market Data Provider
  • Order Execution Engine
  • Portfolio Manager
❓
Clarifying Questions to Ask
  • How many concurrent threads/gates will access portfolio and order data? (e.g., multiple traders, market data updates)
  • What pricing strategy to use for P&L calculation? FIFO, LIFO, or average cost?
  • Are partial fills allowed for orders? How to handle them?
  • What is the expected latency for market data updates and trade execution?
  • Should order matching be part of this system or delegated to an external engine?
  • How to handle order cancellations during execution race conditions?
  • Is historical trade and order data retention required?
Out of Scope
✗ User authentication and authorization
✗ Complex order types like stop-loss or trailing stops
✗ Margin trading and risk management
✗ Settlement and clearing processes
✗ UI/UX design
⚡
QPS Calculation
read qps5000
write qps1000
🖥️
Server Estimate
application servers10
database servers3
market data servers2
🔢
Enumerations
enum OrderType
MARKET | LIMIT
Enum prevents typo bugs and enables exhaustive switch statements for order processing logic.
enum OrderStatus
NEW | PARTIALLY_FILLED | FILLED | CANCELED | REJECTED
Defines finite states of an order lifecycle, enabling clear state transitions and validation.
enum TradeSide
BUY | SELL
Explicitly distinguishes trade direction, preventing logic errors in portfolio updates.
enum MarketDataType
QUOTE | TRADE
Differentiates types of market data events for appropriate processing.
📦
Portfolio
2 fields
private final Map<String, Position> positionsprivate final String ownerId
Maintain current holdings per security, update positions after trades, calculate aggregate P&L.
public synchronized Position getPosition(String symbol)Returns the current position for a given security symbol in a thread-safe manner.
public synchronized void updatePosition(Trade trade)Atomically updates the position based on executed trade details.
public synchronized double calculatePnL()Calculates total profit and loss across all positions.
📦
Position
3 fields
private final String symbolprivate int quantityprivate double averagePrice
Track quantity and average price of a single security holding.
public synchronized void adjustQuantity(int delta, double tradePrice)Adjusts quantity and recalculates average price atomically after a trade.
public synchronized double getUnrealizedPnL(double currentPrice)Calculates unrealized P&L based on current market price.
📦
Order
8 fields
private final String orderIdprivate final String symbolprivate final OrderType typeprivate final TradeSide sideprivate volatile int quantityprivate volatile int filledQuantityprivate volatile OrderStatus statusprivate final double limitPrice
Represent a client order with lifecycle state and track filled quantities.
public synchronized void fill(int quantityFilled)Atomically updates filled quantity and order status.
public synchronized boolean cancel()Attempts to cancel the order if not already filled or canceled.
public synchronized boolean isOpen()Checks if order is still open for execution.
📦
Trade
7 fields
private final String tradeIdprivate final String orderIdprivate final String symbolprivate final TradeSide sideprivate final int quantityprivate final double priceprivate final long timestamp
Immutable record of executed trade details.
public double getTradeValue()Returns total value of the trade (quantity * price).
📦
MarketData
5 fields
private final String symbolprivate final MarketDataType typeprivate final double priceprivate final int sizeprivate final long timestamp
Represents incoming market data events for price and size updates.
public boolean isValid()Validates market data fields for correctness.
📦
OrderBook
3 fields
private final String symbolprivate final List<Order> buyOrdersprivate final List<Order> sellOrders
Maintain and match buy and sell orders for a security.
public synchronized void addOrder(Order order)Adds a new order to the order book in a thread-safe manner.
public synchronized List<Trade> matchOrders()Matches buy and sell orders and returns list of executed trades.
📦
PortfolioManager
1 fields
private final Map<String, Portfolio> portfolios
Manage multiple portfolios, route trade updates, and provide portfolio queries.
public synchronized Portfolio getPortfolio(String ownerId)Returns portfolio for a given owner.
public synchronized void processTrade(Trade trade)Routes trade updates to the appropriate portfolio.
🗄️
Orders
PK: orderId
orderId STRINGsymbol STRINGtype STRINGside STRINGquantity INTfilledQuantity INTstatus STRINGlimitPrice DOUBLEtimestamp BIGINT
🗄️
Trades
PK: tradeId
tradeId STRINGorderId STRINGsymbol STRINGside STRINGquantity INTprice DOUBLEtimestamp BIGINT
🔌
GET
/portfolio/{ownerId}
Request
"ownerId as path parameter"
Response
"Portfolio details including positions and P&L"
Fetches current portfolio snapshot for the given owner.
🔌
POST
/order
Request
"Order details JSON (symbol, type, side, quantity, limitPrice)"
Response
"Order confirmation with orderId and status"
Places a new order in the system.
🔌
POST
/order/{orderId}/cancel
Request
"orderId as path parameter"
Response
"Cancellation status boolean"
Attempts to cancel an open order.

Practice

(1/5)
1. In the in-memory file system design, a FileSystem class has a private constructor and a static synchronized getInstance() method returning the single instance. Which pattern is applied here and why is this the correct use case?
easy
A. Factory pattern, because it controls object creation centrally.
B. Singleton pattern, to ensure only one instance manages the entire file system state.
C. Builder pattern, to construct complex file system objects step-by-step.
D. Prototype pattern, to clone existing file system instances efficiently.

Solution

  1. Step 1: Identify the pattern from constructor and method signature

    The private constructor prevents external instantiation, and the static synchronized getInstance() method ensures a single shared instance, matching Singleton pattern characteristics.
  2. Step 2: Reason why Singleton fits this use case

    Singleton is appropriate because the file system state must be globally consistent and unique; multiple instances would cause conflicting states.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Private constructor + static synchronized getInstance() -> Singleton [check]
Hint: Private constructor + static getInstance() -> Singleton [check]
Common Mistakes:
2. In a parking lot system, if parkVehicle() is not synchronized, which exact thread interleaving causes double-booking of the same spot?
medium
A. Thread 1 parks vehicle, Thread 2 parks vehicle simultaneously without checking availability.
B. Thread 1 updates spot status after parking, Thread 2 reads stale status and parks again.
C. Thread 1 releases spot, Thread 2 immediately parks without synchronization.
D. Thread 1 checks spot availability -> true, context switch; Thread 2 checks availability -> true; both park concurrently.

Solution

  1. Step 1: Identify the check-then-act race condition

    Without synchronization, Thread 1 reads spot as available and is preempted before marking it occupied. Thread 2 also reads available and proceeds to park.
  2. Step 2: Confirm both threads park concurrently causing double-booking

    Both threads believe the spot is free and park, leading to inconsistent state and double-booking.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Unsynchronized check-then-act -> double-booking race [check]
Hint: Check-then-act without sync -> double-booking race condition [check]
Common Mistakes:
3. ElectricCar pieces require special ChargingSpot compatibility in the Jigsaw Puzzle System. What is the minimum design change to support ElectricCar and ChargingSpot without modifying existing classes?
hard
A. Add ELECTRIC_CAR to PieceType enum, CHARGING to SpotType enum, create ElectricCarPiece subclass, and update compatibility map externally.
B. Modify existing Piece and Spot classes to include electric-specific fields and logic.
C. Create a new ElectricCarPiece class implementing a new interface and modify Board to handle it specially.
D. Add a god-class CompatibilityManager that hardcodes all compatibility rules including electric cars.

Solution

  1. Step 1: Identify extensibility requirements

    New piece and spot types must be added without modifying existing classes to respect OCP.
  2. Step 2: Evaluate minimal change approach

    Adding new enum values and subclass for ElectricCarPiece plus updating compatibility map externally allows extension without modifying existing code.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    New enums and subclass extend system without changing existing classes [check]
Hint: Add enums + subclass + external map update = minimal invasive extension [check]
Common Mistakes:
4. The Workflow Engine must support ElectricCar vehicles requiring ChargingSpot compatibility. What is the minimum change to the current design to add this without modifying existing classes?
hard
A. Add charging logic inside Executor class to handle ElectricCar spots dynamically.
B. Modify Vehicle base class to include isElectric flag and add charging logic inside existing Spot classes.
C. Create a new ElectricVehicle interface and modify all existing Vehicle subclasses to implement it.
D. Add ELECTRIC_CAR to VehicleType enum, CHARGING to SpotType enum, create ElectricCar subclass, and update SpotCompatibility.COMPATIBILITY_MAP accordingly.

Solution

  1. Step 1: Identify extensibility requirements

    Adding ElectricCar and ChargingSpot must not modify existing classes to respect OCP and avoid class explosion.
  2. Step 2: Use enums and subclassing

    Adding new enum values and a new ElectricCar subclass extends functionality cleanly; updating compatibility map centralizes spot-vehicle matching without changing existing code.
  3. Step 3: Avoid modifying base classes or Executor

    Modifying Vehicle or Executor violates OCP and risks introducing bugs.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    New enums + subclass + compatibility map update -> minimal, no existing class change [check]
Hint: Add enums + subclass + map update, no existing class change [check]
Common Mistakes:
5. ElectricCar needs to be added to the product catalog with ChargingSpots. What is the minimum change to support this without modifying existing classes?
hard
A. Create a new ElectricCar class and a new ChargingSpot class, modifying Vehicle and Spot base classes to support them
B. Add ELECTRIC_CAR to VehicleType enum and CHARGING to SpotType enum, create ElectricCar extends Vehicle, update SpotCompatibility.COMPATIBILITY_MAP accordingly
C. Modify Vehicle class to add isElectric flag and add charging logic inside existing ParkingSpot classes
D. Add charging logic inside Vehicle class and extend SpotType enum with charging spots, modifying existing compatibility logic

Solution

  1. Step 1: Identify extensibility without modifying existing classes

    Adding new enum values and new classes for ElectricCar and ChargingSpot allows extension without changing existing class code, preserving OCP.
  2. Step 2: Why updating compatibility map is needed

    SpotCompatibility.COMPATIBILITY_MAP controls which vehicles fit which spots; updating it ensures ElectricCar and ChargingSpot compatibility without modifying base classes.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    New enums + classes + compatibility map update -> minimal existing class changes [check]
Hint: Add enums + classes + map, no base class changes [check]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard