Implement a Stateful Trading Order Manager
CoinbaseBackend Engineer · OnsiteLast updated
This problem tests your ability to design a stateful system using hash-based sharding, efficient indexing, and robust state machine transitions for high-frequency financial orders.
Problem Statement
You are tasked with building the core engine for a trading order manager. The system must handle three types of operations: placing a limit order, cancelling an order, and retrieving all active orders for a specific user.
Requirements
- Deterministic Sharding: Use the FNV-1a hash algorithm on the
user_idto route requests to one ofNlogical shards. - State Machine: Orders can be
OPEN,FILLED, orCANCELLED. An order can only transition fromOPENtoFILLEDorCANCELLED. Once in a terminal state, it cannot transition further. - Indexing: Maintain data structures that allow:
- Placing an order in
O(1)average time. - Cancelling an order by ID in
O(1)average time. - Retrieving all
OPENorders for a specific user inO(K)time, whereKis the number of open orders for that user.
- Placing an order in
Interface
class OrderManager:
def __init__(self, num_shards: int):
# Initialize storage for the specified number of shards
def place_order(self, user_id: str, order_id: str, symbol: str, amount: float):
# Store the order if it does not exist
def cancel_order(self, user_id: str, order_id: str):
# Transition order to CANCELLED if it exists and is OPEN
def get_user_orders(self, user_id: str) -> List[dict]:
# Return all orders currently in OPEN state for the given user
Constraints
num_shardswill be between 1 and 1024.order_idis unique system-wide.- Total operations will be in the magnitude of 10^6.
Example
om = OrderManager(num_shards=4)
om.place_order("user1", "ordA", "BTC", 1.0)
om.place_order("user1", "ordB", "ETH", 2.0)
om.cancel_order("user1", "ordA")
# get_user_orders("user1") returns only ordB
Hints
Hint 1
Use a hash map per shard to store the order metadata for constant-time lookups by order_id.
Hint 2
Maintain a secondary index (e.g., a hash map of user_ids to sets or lists of order_ids) to track active orders per user.
Hint 3
Ensure the cancel operation updates both the primary order storage and the user's index simultaneously to maintain consistency.
Follow-up questions
- How would you handle the atomicity of order updates if this system needed to run across multiple threads?
- If the number of shards needed to increase (dynamic scaling), what strategy would you use to rebalance the existing orders without downtime?
- How would you modify the data structures to support order retrieval sorted by price or timestamp?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.