Designing a Multi-Venue Cryptocurrency Order Routing System
System DesignModel answerLast updated
Build an order-placement architecture that routes crypto trades to external exchanges, handling balance checks, partial fills, and venue failures.
Your team is building an order-placement backend for a cryptocurrency trading platform. Users submit buy and sell orders through your service, but you don't operate a matching engine. Instead, you forward orders to external cryptocurrency exchanges (venues), each with different APIs, rate limits, and reliability characteristics.
Your system must handle:
- Order types: market orders (execute immediately at current price) and limit orders (execute only at a specified price or better)
- Core operations: submit new orders, cancel existing orders, query order status
- Multi-venue integration: connect to 3–10 external exchanges, each using different protocols (REST, WebSocket, FIX, or proprietary formats)
- Balance management: verify sufficient funds and reserve them before sending orders externally
- Execution tracking: process acknowledgments, partial fills, rejections, and reconcile with venue state
- Quality attributes: high availability, correctness guarantees, audit trails, and low internal latency
Design the complete architecture: client-facing APIs, internal services, data models, the order lifecycle, routing decisions, failure scenarios, and scaling strategy.
Working Constraints
Define your own scale assumptions, but reasonable targets include:
- Internal processing latency (before external venue call): p99 under 50ms
- Peak order submission rate: several thousand orders per second
- Execution report volume: 3–5× order volume (acknowledgments, fills, cancellations)
- Multiple external venues with independent failure modes and rate limits
- Custodial model: your platform holds user funds; you manage internal balances
- Orders may fill partially across multiple venues
- Strong consistency for balances and order state; eventual consistency acceptable for historical queries
Questions You Should Explore
Before diving into design, clarify:
- Custody model: Do you hold user funds internally, or do users control keys and sign transactions?
- Routing complexity: Should a single order be split and sent to multiple venues, or route to one venue only?
- Order variants: Beyond market and limit, what about stop orders, immediate-or-cancel (IOC), fill-or-kill (FOK), good-till-canceled (GTC)?
- Compliance: What regulatory requirements exist—sanctions checks, rate limits per user, audit retention periods?
- Venue capabilities: Do exchanges accept client-assigned order IDs for idempotent submission? Do they provide sequence numbers in execution feeds?
- Outage handling: When a venue goes down, should you reject new orders, queue them, or automatically reroute to another venue?
Hints
Hint 1
Start by separating concerns: API gateway, order management, venue adapters, and balance ledger should be distinct services with clear contracts.
Hint 2
Define the order state machine explicitly—what are the valid transitions from pending to filled, canceled, or failed? How do you handle the 'unknown' state after a network timeout?
Hint 3
Think through fund reservation carefully: when do you reserve, when do you release, and how do you handle partial fills that free up some reserved funds?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Requirements and Scope
Functional requirements:
- Accept market and limit orders from users
- Route orders to appropriate external venues
- Cancel orders before or during execution
- Track order status and notify users of state changes
- Reserve funds before external submission and release on completion
- Handle partial fills and multi-venue execution
Non-functional requirements:
- Correctness: no double-spending, no lost funds, accurate balance tracking
- Auditability: immutable log of every state transition for compliance
- Low latency: internal path under 50ms p99
- High availability: continue operating when individual venues fail
- Scalability: support thousands of orders/sec with room to grow
2. High-Level Architecture
Core services:
- API Gateway: authenticates requests, rate-limits per user, forwards to Order Service
- Order Service: validates orders, manages the order state machine, coordinates workflow
- Balance Service: tracks user balances, reserves and releases funds with strong consistency
- Venue Gateway: maintains adapters for each exchange protocol, normalizes responses
- Execution Processor: consumes venue execution reports (fills, acks, rejections), updates order state
- Reconciliation Service: periodically queries venues to detect and fix discrepancies
- Event Store: append-only log of all order and balance events for audit and replay
Data stores:
- Orders DB (PostgreSQL): authoritative order state, queryable by order ID and user
- Balance Ledger (PostgreSQL): user balances and reservations with ACID guarantees
- Event Log (Kafka or equivalent): durable stream of order lifecycle events
- Cache (Redis): recent order status for fast reads, refreshed from DB
3. Data Model
Order entity:
order_id (UUID, client-generated for idempotency)
user_id
order_type (MARKET, LIMIT)
side (BUY, SELL)
symbol (e.g., BTC/USD)
quantity
limit_price (null for market orders)
status (PENDING, SUBMITTED, PARTIALLY_FILLED, FILLED, CANCELED, REJECTED, FAILED)
reserved_funds
filled_quantity
average_fill_price
venue_order_ids (list, if split across venues)
created_at, updated_at
Balance record:
user_id
asset (BTC, ETH, USD, etc.)
available_balance
reserved_balance
total_balance = available + reserved
version (optimistic locking)
Execution report:
execution_id
order_id
venue_order_id
fill_quantity
fill_price
timestamp
venue_sequence_number
4. Order Lifecycle and State Machine
States:
- PENDING: order received, validation in progress
- SUBMITTED: sent to venue, awaiting acknowledgment
- PARTIALLY_FILLED: some quantity executed, remainder open
- FILLED: fully executed
- CANCELED: user-requested cancellation confirmed
- REJECTED: venue declined the order
- FAILED: unrecoverable error (venue timeout, internal failure)
Valid transitions:
- PENDING → SUBMITTED (after fund reservation and venue send)
- SUBMITTED → PARTIALLY_FILLED → FILLED
- SUBMITTED or PARTIALLY_FILLED → CANCELED (on user request or venue confirmation)
- PENDING or SUBMITTED → REJECTED (venue rejects)
- SUBMITTED → FAILED (after retries exhausted or venue unreachable)
Ambiguous state handling: If a venue times out after submission, mark the order as SUBMITTED with a flag needs_reconciliation=true. The Reconciliation Service queries the venue later to determine actual state.
5. Fund Reservation Flow
For buy orders (limit):
- Reserve
quantity × limit_pricein quote currency (e.g., USD) - On partial fill of amount
Aat priceP: releaseA × (limit_price - P)ifP < limit_price - On full fill or cancel: release any remaining reserved funds
For sell orders:
- Reserve
quantityin base currency (e.g., BTC) - On partial fill: reduce reservation by filled amount
- On full fill or cancel: release remainder
Balance Service transaction:
BEGIN;
SELECT available_balance, version FROM balances WHERE user_id = ? AND asset = ? FOR UPDATE;
IF available_balance >= required:
UPDATE balances SET available_balance = available_balance - required,
reserved_balance = reserved_balance + required,
version = version + 1
WHERE user_id = ? AND asset = ? AND version = ?;
COMMIT;
ELSE:
ROLLBACK;
Optimistic locking prevents concurrent overdrafts. If the version check fails, retry.
6. Order Submission Flow
- API Gateway receives order, checks authentication and rate limits
- Order Service validates parameters (price > 0, supported symbol, etc.)
- Balance Service attempts fund reservation
- Success: return reservation ID
- Failure: reject order immediately with insufficient balance error
- Order Service writes order to DB with status PENDING, publishes event to Kafka
- Venue Gateway selects target venue (routing logic below), transforms order to venue protocol
- Send order to venue with client-assigned
order_idfor idempotency - Synchronous response to user: "Order accepted" with
order_id(doesn't wait for venue ack) - Asynchronously: Venue Gateway receives ack/reject, publishes execution report
- Execution Processor updates order status to SUBMITTED or REJECTED, releases funds if rejected
Latency breakdown:
- Steps 1–5 (internal path): 20–50ms
- Step 6 (venue round-trip): 100–500ms, varies by venue
7. Routing Logic
Simple routing (MVP):
- Route to the venue with best liquidity for the symbol
- Use a static mapping: BTC/USD → Venue A, ETH/USD → Venue B
- If primary venue is down, reject or route to fallback venue
Smart order routing (advanced):
- Split large orders across multiple venues to minimize slippage
- Monitor real-time order book depth from each venue
- Allocate order quantity proportional to available liquidity
- Send child orders to venues in parallel, track each with separate
venue_order_id - Aggregate fills and update parent order status
Trade-off: Smart routing improves execution quality but adds complexity in partial fill tracking and cancellation (must cancel all child orders).
8. Failure Handling
Venue timeout after submission:
- Mark order as SUBMITTED with
needs_reconciliation=true - Reconciliation Service queries venue every 30s with the client order ID
- Update state based on venue response (filled, canceled, or not found)
- If venue never responds after 5 minutes, escalate to manual review
Out-of-order execution reports:
- Execution reports may arrive out of order or duplicated
- Use
venue_sequence_numberto detect gaps and reorder - Deduplicate by
execution_id - Buffer reports and flush in sequence order
Venue disconnect:
- Venue Gateway detects WebSocket disconnect or repeated failures
- Mark venue as degraded, stop routing new orders
- For in-flight orders, switch to polling the venue REST API for status
- Alert operations team
Partial fill then venue failure:
- Already-filled quantity is settled; release corresponding reserved funds
- Remaining quantity: attempt to route to another venue or mark as canceled
- Notify user of partial execution
9. Consistency and Scaling
Strong consistency:
- Balance Service uses PostgreSQL with ACID transactions
- Order state transitions are serialized per order (use row-level locks or optimistic versioning)
Eventual consistency:
- Read replicas for historical order queries and dashboards
- Redis cache for recent orders, invalidated on state change
Partitioning:
- Partition Order Service and Balance Service by
user_id(consistent hashing) - Each partition is an independent DB shard
- Venue Gateway is stateless and scales horizontally
- Execution Processor partitions by
order_idto maintain ordering per order
Throughput:
- 10 Order Service instances, each handling 500 orders/sec = 5,000 orders/sec
- Venue Gateway pools connections to venues, respects rate limits
- Execution Processor uses Kafka consumer groups for parallel processing
10. Observability and Compliance
Metrics:
- Order submission rate, success rate, rejection reasons
- p50, p95, p99 latency for internal path and per-venue round-trip
- Balance reservation/release rate, failed reservation count
- Venue health: success rate, timeout rate, lag in execution reports
Alerts:
- Venue degraded (error rate > 5% for 2 minutes)
- Balance discrepancy detected (reserved > total)
- High order rejection rate
- Reconciliation queue backlog growing
Audit log:
- Event Store contains immutable record of every order state change and balance adjustment
- Indexed by user, order, timestamp
- Retained for 7 years per regulatory requirements
- Periodic snapshots for disaster recovery
Compliance:
- Sanctions screening before order acceptance (check user against OFAC list)
- Per-user rate limits to prevent market manipulation
- Daily trade reports generated from Event Store
11. Trade-Offs
- Synchronous vs. asynchronous response: Returning "accepted" before venue ack improves user-perceived latency but requires websocket or polling for status updates.
- Single-venue vs. multi-venue routing: Single-venue is simpler and sufficient for MVP; multi-venue improves execution quality but complicates cancellation and reconciliation.
- Strong vs. eventual consistency for order reads: Strong consistency via DB queries is accurate but slower; caching with invalidation is faster but may show stale data for a few seconds.
- Reserve on submission vs. reserve on fill: Reserving upfront prevents overselling but locks capital during order lifetime; reserving on fill reduces lock time but risks insufficient funds if balance changes.
This design prioritizes correctness and auditability while maintaining low latency for the internal path and providing clear failure modes for external dependencies.