Crypto exchange web platforms are the primary interface between retail traders and orderbook or automated market maker systems. Understanding their architecture matters because latency, session management, and API design directly affect execution quality, fund safety, and system reliability. This article dissects the technical stack beneath exchange web frontends, the tradeoffs between REST and WebSocket approaches, and the failure modes that separate robust implementations from fragile ones.
Frontend to Backend Communication Patterns
Most exchange web clients use a hybrid model: REST for control plane operations (order placement, account queries, withdrawal requests) and WebSocket for market data streams. REST endpoints return acknowledged state changes and allow idempotent retries. WebSocket connections stream orderbook snapshots, trade ticks, and private account updates with sub-100ms latency on well tuned infrastructure.
The choice of protocol affects both UX and risk. REST polling at one second intervals creates visible lag in fast moving markets and wastes bandwidth. WebSocket subscriptions reduce overhead but require client side reconnection logic and sequence number validation to detect dropped frames. Exchanges typically assign a connection ID and monotonic sequence to each message. Clients compare received sequence numbers against expected values. A gap triggers a snapshot request before resuming incremental updates.
Session affinity complicates horizontal scaling. If the exchange load balances WebSocket connections without sticky routing, a reconnect may land on a different edge server that lacks cached subscription state. Better implementations store subscription metadata in a distributed cache (Redis or similar) keyed by session token, allowing any edge node to rebuild context after failover.
Authentication and Session Security
Web clients authenticate via API keys for programmatic access or session tokens for browser users. API keys are typically HMAC signed request headers with a nonce and timestamp to prevent replay attacks. The exchange verifies the signature using the stored secret, checks the nonce is unused within the validity window (commonly 30 to 60 seconds), and rejects stale requests.
Browser sessions rely on HttpOnly cookies or bearer tokens stored in localStorage. HttpOnly cookies prevent JavaScript access, reducing XSS risk but complicating mobile app integration. Bearer tokens in localStorage are readable by any script on the domain, so exchanges using this pattern must enforce strict Content Security Policy headers to block inline scripts and third party resources.
Rate limiting sits between authentication and business logic. Sophisticated exchanges apply tiered limits: per IP, per user, per API key, and per endpoint. A typical setup allows 1200 requests per minute for market data but restricts order placement to 10 per second per user. Exceeding the limit returns HTTP 429 with a Retry-After header. Clients should parse this header and implement exponential backoff rather than hammering the endpoint.
Orderbook Representation and Sync Logic
Exchanges stream orderbook updates in two formats: full snapshots and incremental deltas. A snapshot contains every price level and quantity. Deltas report only changes: new levels, cancelled orders, or filled volume. Deltas are smaller and faster but require the client to maintain local state.
A robust client requests a snapshot on initial connection, applies deltas with sequence numbers greater than the snapshot sequence, and discards earlier deltas as stale. If a delta arrives out of order or a sequence gap appears, the client discards its local book and requests a fresh snapshot. Without this logic, the local book drifts from exchange state, showing phantom liquidity or stale prices.
Some exchanges send aggregated levels (price and total quantity) while others expose individual orders (Level 3 data). Aggregated books are easier to render and consume less bandwidth. Level 3 data reveals queue position and allows estimation of fill probability but generates high message volume on liquid pairs.
Example: Placing a Limit Order via REST and Monitoring Fill via WebSocket
A trader wants to buy 0.5 BTC at 42000 USDT on an exchange using REST for orders and WebSocket for updates.
- The client sends a POST to
/api/v3/orderwith JSON payload:{"symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", "price": "42000", "quantity": "0.5", "timeInForce": "GTC"}. The request includes HMAC signature in theX-Signatureheader and a timestamp. - The exchange validates the signature, checks account balance (21000 USDT required plus fees), places the order in the matching engine, and returns
{"orderId": "78912", "status": "NEW", "executedQty": "0"}. - The client’s WebSocket subscription to the
user.ordersstream receives an update:{"orderId": "78912", "status": "PARTIALLY_FILLED", "executedQty": "0.2", "price": "42000"}when part of the order fills. - A second message arrives:
{"orderId": "78912", "status": "FILLED", "executedQty": "0.5", "avgPrice": "42000"}once fully matched. - If the client disconnects during step 4, on reconnect it queries
/api/v3/order?orderId=78912to confirm final status before assuming execution.
Common Mistakes and Misconfigurations
- Ignoring sequence numbers in WebSocket streams. Clients that append every delta without validating monotonicity build corrupted orderbooks and display incorrect spreads.
- Retrying order placement without checking execution. Network timeouts do not guarantee the order failed. Blindly resubmitting can create duplicate positions.
- Hardcoding API endpoints. Exchanges rotate domains or add regional mirrors. Retrieve the base URL from a config service or DNS rather than embedding it in code.
- Using browser localStorage for API secrets in web apps. Any XSS vulnerability leaks credentials. Store secrets server side and issue short lived session tokens to the frontend.
- Failing to handle 429 rate limit responses. Continuing to retry without backoff can trigger IP bans or account suspension.
- Assuming WebSocket reconnection is instant. Budget 2 to 5 seconds for TLS handshake, authentication, and snapshot retrieval. Queue user actions during this window rather than blocking the UI.
What to Verify Before You Rely on This
- Current API rate limits per tier and endpoint. These change as exchanges adjust capacity.
- WebSocket message format versioning. Exchanges occasionally deprecate fields or change timestamp precision.
- Session token expiry duration. Some exchanges use 24 hour tokens, others expire after 1 hour.
- Order status enum values. Confirm which states the exchange uses (e.g.,
PENDING_CANCELvsCANCELING). - Minimum and maximum order sizes per symbol. These vary by market and are updated periodically.
- Whether the exchange supports order amendment or requires cancel-replace sequences.
- Supported TLS versions and cipher suites. Older clients may fail handshake after protocol upgrades.
- Geographic restrictions and IP whitelisting policies if using API keys from servers.
- Whether the exchange provides a testnet or sandbox environment for integration testing.
- Maintenance windows and historical uptime SLA if running automated strategies.
Next Steps
- Implement sequence gap detection in your WebSocket client and test behavior under simulated packet loss.
- Audit your retry logic for order placement. Ensure idempotency keys or query before resubmit patterns are in place.
- Benchmark round trip latency from your deployment region to the exchange’s edge servers. Consider colocation if consistent sub-50ms execution matters to your strategy.
Category: Crypto Exchanges