Designing an Order-Routing Platform Over Async Exchange APIs
System DesignModel answerLast updated
Design a crypto order-routing service that fronts unreliable third-party exchange APIs with async fills, exactly-once effects, spiky load, and a durable ledger.
You are designing a trading platform that lets clients submit orders (market, limit, IOC/GTC), cancels, and queries, but never holds the matching engine itself: every order is forwarded to one or more external venues that expose a REST API which looks synchronous. In reality the venue's HTTP 200 only confirms receipt — fills, partial fills, and cancellations land later through polling, webhooks, or websocket streams, and a request can time out after the venue has already executed it.
Cover the following in your design discussion:
- Architecture — the services, datastore(s), event bus, and per-venue connectors; why the client gets a fast synchronous acknowledgement while execution proceeds asynchronously; how submission is decoupled from fill/cancel processing.
- Order state machine — the full set of states (including a distinct "outcome unknown" state), legal transitions, how state is persisted and recovered after a crash, and how transitions are made idempotent.
- Timeouts and partial failures — retries, idempotency keys / client-assigned order IDs, deduplication, circuit breakers, dead-letter handling, and periodic reconciliation with the venue; how to avoid double execution and get effectively-once external effects.
- Bursty traffic — rate limiting, queueing, backpressure, autoscaling, batching, and protection of downstream venue rate limits.
- Consistency and durability — guarantees for orders, fills, and user balances (e.g., double-entry ledger with reserve → settle/release), and how strong internal consistency coexists with eventual consistency against venue truth.
- Multi-venue routing (optional) — smart order router, parent/child order modeling, aggregation of child fills into the parent.
- Client APIs, SLOs, observability — the external API surface, latency/availability targets, and the metrics, tracing, logging, and alerting needed to run it.
State your assumptions about scale and be explicit about trade-offs and failure modes.
Hints
Hint 1
Separate the 'accept' path (fast, local, transactional) from the 'execute' path (slow, remote, retried) — the venue's success response is not the source of truth.
Hint 2
Model 'we sent a request and don't know what happened' as a first-class state resolved only by querying the venue, never by guessing or blindly resubmitting.
Hint 3
Aim for exactly-once *effects*, not exactly-once delivery: at-least-once messaging plus idempotent handlers keyed on client order IDs and venue trade IDs.
Hint 4
Dedupe fills using the venue's cumulative filled quantity, not per-message deltas, so replays are naturally no-ops.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale
Functional. Place/cancel/query orders (market, limit, IOC/GTC); forward to one or more venues; stream order and fill updates to clients; keep balances correct.
Non-functional. Never double-execute; never lose a fill; never let a user spend funds they don't have; order acceptance must be fast and highly available even when a venue is degraded.
Assumptions to state out loud. ~10M users, ~5k orders/s steady with 10x bursts to ~50k/s during volatility; cancels can outnumber new orders. Venue limits are tight (say 50–300 req/s per API key), so multiple keys/sub-accounts and hard traffic shaping are required. Events at ~1 KB × 5k/s ≈ 430 GB/day — keep open orders in hot storage, archive history.
2. Architecture
Client → API Gateway (auth, per-user rate limit)
→ Order Service ──(one DB txn)──► Orders DB + Ledger DB + Outbox
│ CDC / outbox relay
▼
Event bus (Kafka, keyed by order_id)
│
┌────────── Smart Order Router ────┤
▼ ▼
Connector A (token bucket, breaker, Connector B ...
REST + WS/webhooks) → normalized ExecutionReports
│
▼
Execution Processor → order state + ledger settle/release → push to clients
Reconciler (periodic venue diff) · DLQ + ops tooling
Why the client gets an immediate "accepted". Venue latency is unbounded and the venue's HTTP response is not final truth — the fill may arrive seconds later over a stream, and a timeout may hide a successful execution. Blocking the client on the venue couples our availability to theirs. The accept path is: validate → reserve funds → persist order + outbox event in one transaction → return 202 Accepted with order_id well under 100 ms. Submission, fills, and cancels then flow as events; connectors are the only components that speak venue protocols and translate them into a normalized ExecutionReport.
3. Order state machine
NEW → PENDING_SUBMISSION → OPEN → PARTIALLY_FILLED → FILLED
│ │ │ │
│ └→ UNKNOWN ←──┘(timeout) ├→ CANCEL_PENDING → CANCELED
│ │ │ └(late fill)→ PARTIAL/FILLED
▼ └(resolve via lookup) → OPEN / REJECTED / FILLED
REJECTED OPEN/PARTIAL → EXPIRED
Terminal states: FILLED, CANCELED, REJECTED, EXPIRED. UNKNOWN is entered on a submit/cancel timeout or 5xx and means "the venue may or may not have this order" — it is resolved only by querying the venue, never by guessing.
Persistence and idempotency. Each order row carries state, version, cum_filled_qty, avg_price. Every transition is a conditional update (WHERE id=? AND version=? AND state IN (allowed_from)), and each is appended to an order_events log that serves as audit trail and rebuild source. Fills are applied from the venue's cumulative quantity and only when it increases, so replays are no-ops. A unique constraint on (venue, venue_trade_id) dedupes. A fill arriving in CANCEL_PENDING is legal: the cancel only releases the remainder once the venue confirms.
Recovery. On restart, connectors reload non-terminal orders, resubscribe to streams, and backfill via "orders since T" / "fills since T" REST queries.
4. Timeouts and effectively-once effects
Exactly-once delivery is impossible; we get exactly-once effects from at-least-once delivery plus idempotent operations at each hop.
- Client side: an
Idempotency-Keyheader maps to a stored response; a retry returns the sameorder_id. - Venue side: generate a deterministic
client_order_idat order creation and reuse it on every resubmission — most venues reject duplicates, giving dedup for free. - Timeout protocol: mark UNKNOWN, do not resubmit. Poll by
client_order_idwith backoff and watch the stream. Found → adopt venue state. Confirmed absent after a grace window exceeding venue processing latency → resubmit with the same ID. If the venue has no lookup-by-ID, treat it as an operational case: keep funds reserved, escalate, resolve via fills or balance reconciliation. - Retries: exponential backoff with jitter, only for idempotent/ID-protected calls.
4xxrejections are terminal (REJECTED, release reserve);429/5xxare retryable. - Circuit breaker per venue and API key on error rate/latency; when open, the router reroutes or fails fast with a clear status. Use cancel-on-disconnect where supported.
- DLQ for poison events with alerting and replay tooling — never silent drops.
- Reconciliation every few minutes and on every reconnect: diff open orders, fills, and venue balances against our omnibus ledger accounts; discrepancies become corrective events through the same idempotent path or page a human.
5. Bursty traffic
Per-user and per-key token buckets at the gateway; global admission control that returns 429/503 once queue lag means an order would arrive stale. Kafka absorbs bursts between Order Service and connectors; connectors pull at the venue's allowed rate, making backpressure explicit instead of a pile of timeouts. Per-venue distributed token bucket (e.g., Redis) set to ~80% of published limits, sharded across keys. Separate queues so cancels outrank new orders (they reduce risk) and market makers get reserved capacity. Autoscale stateless services on CPU/lag; connectors scale only up to the rate budget, since more pods don't raise venue limits — use venue batch endpoints instead. Hot-shard mitigation: partition by order_id, and keep per-symbol/popular-user activity from concentrating on one partition.
6. Consistency and durability
Balances live in a double-entry ledger: a reserve on accept (available → reserved), then settle (reserved → spent) or release (reserved → available) on fills/cancels. Ledger writes are strongly consistent locally (single-writer per account or serializable transactions) and atomic with the order update via the transactional outbox. Orders and fills have the same durability guarantee (replicated commit before ack). Reconciliation closes the gap where the venue is eventual truth: our ledger is authoritative for what we think happened, the venue is authoritative for what did, and periodic diffs plus idempotent corrective events converge the two.
7. Multi-venue routing (optional)
A parent order is created client-side; the SOR splits it into child orders per venue based on quoted liquidity, fees, and venue health. Child fills are applied individually, and the parent's cum_filled_qty is the sum, with parent terminal only when all children reach a terminal state. Rebalancing/hedging and per-venue exposure limits live in the SOR.
8. APIs, SLOs, observability
Client REST: POST /orders (idempotency key), DELETE /orders/{id}, GET /orders/{id}, plus a websocket stream of order/fill events. SLOs: accept p99 < 100 ms, availability 99.95% for accepts (not for execution), fill-freshness p99 < 2 s. Observability: end-to-end tracing with order_id as correlation key; metrics for accept latency, state-transition counts, venue error/timeout rate, breaker state, queue lag, fill lag, reconcile discrepancy count, ledger imbalance alarms (must always be zero), and DLQ depth. Alert on UNKNOWN orders older than a threshold, on discrepancy, and on rate-limit headroom below threshold.
Common mistakes to flag: treating the venue's synchronous 200 as the final fill, blindly resubmitting on timeout, computing fills from deltas instead of cumulative quantity, mixing up "we accepted it" with "it executed," and omitting the periodic reconcile against venue truth.