面试通识:流动性业务问答

通识对照:加密货币交易流动性通识:价差、深度与库存风险

面试通识:流动性业务问答

Hello,我是小兔大白糖。 这篇整理面试口述与高频追问要点,方便对照站内同主题通识文。


题型:概念理解题(Q1-Q5)→ 业务场景分析题(Q6-Q10)→ 后端开发关联题(Q11-Q15)
语言:英文面试,附核心中文要点


概念理解题(Q1-Q5)


Q1: Explain the relationship between liquidity, order book depth, and slippage.

Core points:

  • Liquidity = ability to trade large size without significant price impact
  • Depth = how many orders are stacked at each price level
  • Slippage = difference between expected price and actual execution price
  • Causal chain: deep book → high liquidity → low slippage

Answer:

"Think of the order book as a staircase of prices. The depth tells you how many
BTC are sitting on each step. Liquidity is the overall ease of trading large
size — the more total volume stacked across the first N levels, the more liquid
the market.

Slippage is what happens when you walk down that staircase. If the first step
only has 2 BTC at $50,000, your 10 BTC market order steps down multiple levels,
and your average fill price might be $50,050 — that $50 gap is slippage, and
it's a direct consequence of thin depth.

So for a liquidity platform: deep order books → less slippage → happy traders
→ more volume → more revenue. Everything we build ultimately serves that chain."

Q2: What is the difference between a market maker and a market taker? Why do they pay different fees?

Core points:

  • Maker: places limit orders that REST on the book → provides liquidity
  • Taker: places market orders that CONSUME existing orders → removes liquidity
  • Fee asymmetry: makers pay less (or even earn rebates) because they provide value to the platform

Answer:

"A maker adds an order to the book and waits — they're providing a service to
the platform by creating liquidity. A taker comes in and immediately matches
against existing orders — they're consuming that liquidity.

The fee structure incentivizes the right behavior: makers get lower fees or
even negative fees (rebates) because without them, the order book is empty and
traders leave. Takers pay standard fees because they benefit from the liquidity
that makers provide.

A useful way to remember it: if your order goes on the book and stays there,
you're a maker. If it executes immediately, you're a taker — regardless of
whether it's a buy or a sell."

Q3: Walk me through what happens when a trader places a market order on a liquidity platform.

Core points:

  • Order hits the gateway → pre-trade risk check → enters matching engine
  • Matching engine walks the order book, filling at best available prices
  • May fill against multiple maker orders at different price levels
  • Post-trade: fee calculation, position update, market data broadcast

Answer:

"Let's say a trader sends a market buy order for 10 BTC on BTC-USDT.

1. The order arrives at the API gateway → authenticated → rate limit checked
2. Pre-trade risk: is this trader's position within limits? Order size reasonable?
3. If checks pass, it enters the matching engine.
4. The engine looks at the sell side of the order book:
   - Sell level 1: 3 BTC @ $50,000 → matched. 7 BTC remaining.
   - Sell level 2: 5 BTC @ $50,010 → matched. 2 BTC remaining.
   - Sell level 3: 2 BTC @ $50,020 → matched. Order fully filled.
   Average fill price = (3×50000 + 5×50010 + 2×50020) / 10 = $50,009

5. Post-trade: the taker pays a fee, each maker whose orders were filled gets
   their maker rebate, positions are updated, and the order book delta is
   broadcast to all WebSocket subscribers.

The entire chain from gateway to broadcast — maybe 50-100 microseconds."

Q4: What is Level 2 market data and why do market makers need it?

Core points:

  • L2 = order book depth (price + quantity at each level, not just best bid/ask)
  • Market makers need it to: calculate their quote price, detect market movement, manage inventory risk
  • Must be real-time + low latency

Answer:

"Level 1 data gives you only the best bid and best ask — useful for a casual
trader checking the price. Level 2 gives you the full depth: how many BTC are
sitting at each price level, both bid and ask sides.

Market makers need Level 2 for several reasons:

1. Quote placement: knowing how much liquidity is at each level helps them
   decide where to place their own quotes. If there's already 100 BTC at $50,000
   bid, adding another 5 BTC there won't get filled any time soon.

2. Market movement detection: if the bid side suddenly thins out, the market
   might be about to drop — the maker should adjust their ask lower.

3. Inventory risk: a maker holding a large position needs to see the full depth
   to estimate how much they can unwind without causing slippage.

In engineering terms, this means we need to deliver L2 snapshots plus incremental
deltas over WebSocket with sub-millisecond latency."

Q5: Explain pre-trade risk, in-flight risk, and circuit breakers in the context of a strategy engine.

Core points:

  • Pre-trade: check BEFORE the order hits the market (size limit, price sanity, fat-finger)
  • In-flight: monitor DURING execution (position accumulating, P&L deteriorating)
  • Circuit breaker: emergency STOP when thresholds breached

Answer:

"Think of it as three lines of defense:

**Pre-trade (the bouncer at the door):**
Before any order reaches the matching engine: Is the order size within the
strategy's configured limit? Is the price within X% of the market? Has the
strategy exceeded its daily order count? If any check fails, the order is
rejected before it ever touches the book.

**In-flight (the security cameras):**
While orders are live and positions are open, we continuously calculate:
- Current position vs max position limit
- Realized + unrealized P&L vs daily loss limit
- Order-to-fill ratio (too many cancelled orders = potential manipulation)
If a limit is approaching, we can send alerts. If breached, escalate.

**Circuit breaker (the emergency shutdown):**
Hard thresholds that, when breached, immediately suspend all trading for that
strategy or account. For example, 'If P&L drops below -$50,000 in a 5-minute
window, kill switch all open orders and block new ones.' The key is that this
check must happen in microseconds — it's usually a simple memory flag check.
No database query, no network call.

The engineering challenge: these three layers must add negligible latency
to the order path. Pre-trade checks need to complete in under 100 microseconds."

业务场景分析题(Q6-Q10)


Q6: A market maker complains that their quotes are being picked off (adverse selection). From the platform's perspective, what could cause this?

Core points:

  • Latency: maker's quote is stale because market data reached them too slowly
  • Information leakage: someone is front-running their quotes
  • Platform issue: market data broadcast has variable latency

Answer:

"As a platform engineer, the first thing I'd check is latency.

Market makers rely on receiving market data, calculating a new quote, and
submitting it — all faster than the market moves. If there's latency anywhere
in this loop, their quote becomes stale: they're still offering to sell at
$50,000 when the market has already moved to $50,050. A faster competitor sees
this stale quote and picks it off.

I'd investigate three things:
1. Market data distribution latency: is the WebSocket feed delivering updates
   with consistent sub-millisecond P99?
2. Order entry latency: how long from 'maker submits order' to 'order appears
   on the book'?
3. Variation in latency: P50 might be 200μs but P99 could be 50ms — that
   tail latency is what kills a market maker.

If I find that the WebSocket gateway is occasionally GC-pausing for 100ms,
that's the root cause — during those pauses, every maker connected to that
gateway node is trading on stale data."

Q7: During a volatility spike, the strategy engine's order rate suddenly 10x. What could go wrong and how do you protect the platform?

Core points:

  • CPU saturation on strategy engine nodes
  • Order queue overflow (backpressure)
  • Risk checks becoming bottleneck
  • Cascading failures to matching engine

Answer:

"A volatility spike is the worst time for things to break, because that's when
market makers need the platform most.

What could go wrong:
1. Strategy engine CPU maxed out — strategies fire more frequently because
   prices are moving fast, creating a self-reinforcing CPU spiral.
2. Order queue overflow — matching engine receives more orders than it can
   process, queues fill up, latency spikes, arbitrageurs exploit the lag.
3. Risk check timeouts — pre-trade checks start timing out, and depending on
   the fail-closed vs fail-open policy, either all orders get rejected (bad for
   business) or all get passed (catastrophic).

How to protect:
1. Rate limiting at the strategy level — each strategy has a max orders/second cap.
   Trading is a privilege, not a right.
2. Priority-based queuing — market maker orders get priority over less
   time-sensitive operations during overload.
3. Circuit breakers based on system health, not just P&L: if the matching engine
   queue depth exceeds threshold, auto-throttle all non-critical order sources.
4. Graceful degradation: if the full risk check engine is overloaded, fall back
   to a lightweight 'fast-path' check (only size limit and kill switch check)
   that runs entirely in memory.

The core principle: protect the core system first. A single misbehaving strategy
should never degrade the experience for everyone else."

Q8: A strategy's P&L suddenly goes deeply negative. Walk through how the platform detects and responds.

Core points:

  • In-flight P&L monitoring (real-time, per-second)
  • Threshold: soft alert → hard limit → kill switch
  • Response: cancel all open orders, block new ones, notify

Answer:

"The risk monitor is continuously calculating position + P&L per strategy.
Let's trace what happens:

T+0s: Strategy 'Alpha' starts losing money. Risk monitor detects P&L crossing
      the soft alert threshold (-$10K). Alert sent to trader via WebSocket notification.

T+30s: P&L accelerates to -$30K, crossing the 'reduce-only' threshold.
       The platform automatically cancels all open orders for this strategy
       but does not cancel existing positions — the trader can still manually
       close out.

T+60s: P&L reaches -$50K, the hard kill-switch limit.
       Immediately: cancel ALL open orders → block new order submission →
       if configured, also liquidate open positions at market.

All of this happens without human intervention. The thresholds are configured
per-strategy and can be adjusted in real-time. Every state transition is logged
with timestamps for post-mortem analysis.

From an engineering perspective, the critical design choice is: the kill-switch
check runs in the same process as the order gateway, using in-memory state,
with no network call. If it had to query an external risk service, a network
timeout during a volatility spike could delay the kill by seconds — and seconds
cost real money."

Q9: Two market makers are providing quotes for the same instrument. How does the platform handle conflicting or overlapping quotes in the consolidated order book?

Core points:

  • Price-time priority: same price → whoever arrived first gets priority
  • FIFO within the same price level
  • No preference between market makers — the order book is anonymous

Answer:

"The matching engine doesn't know or care which market maker submitted which
order. It only sees a price-time priority queue.

At each price level, orders are sorted strictly by arrival time — FIFO.
If Maker A sends sell 5 BTC @ $50,000 at 10:00:00.001 and Maker B sends
sell 3 BTC @ $50,000 at 10:00:00.002, then Maker A's order is at the front
of the queue at that price level.

When a taker buy order comes in, it matches against Maker A's 5 BTC first,
then Maker B's 3 BTC. Maker A has no advantage or disadvantage versus Maker B
beyond the timestamp of their order.

The platform's job is:
1. Fair, accurate timestamping (using a monotonic clock, not wall clock)
2. Consistent ordering across all matching engine replicas
3. Transparency — makers can see their position in the queue via market data

One subtlety: we use a high-precision monotonic clock for sequencing,
not System.currentTimeMillis(). Wall clock can jump backwards due to NTP
adjustment, which would corrupt the FIFO ordering."

Q10: A trader wants to deploy a new version of their strategy without stopping it. How does the platform support hot-reloading of strategy parameters?

Core points:

  • Config center push → strategy listener → reload without restart
  • Validation before applying new parameters
  • Rollback capability

Answer:

"Strategy parameters live in a configuration center (like Nacos, Apollo, or an
internal config service). The strategy engine subscribes to config change events.

Flow:
1. Trader updates spread width from 0.1% to 0.15% in the UI
2. Config center validates: is 0.15% within [0.01%, 5%]? Yes.
3. Config pushed to strategy engine nodes
4. Strategy instance receives onChange event → reads new spread value
   → next quote cycle uses 0.15%

Key design decisions:
- The validation happens server-side, not just UI-side. A malicious client
  should not be able to bypass range checks.
- Old parameter is kept in memory. If the new parameter causes issues,
  the trader can one-click rollback to the previous version.
- Parameter changes are async — the strategy doesn't block waiting for
  config confirmation. If the config push fails, the strategy continues
  with the old parameter.

This is essentially the same pattern as feature flags or dynamic configuration
in any distributed system — just applied to trading parameters."

后端开发关联题(Q11-Q15)


Q11: How would you design the order entry API for market makers? What are the key considerations?

Core points:

  • Low latency (sub-ms), high throughput (10K+ orders/sec)
  • Idempotency (duplicate order requests)
  • Rate limiting per account
  • Authentication + API key management

Answer:

"The market maker order API has different requirements than a retail trading API:

1. Protocol: REST + WebSocket. REST for order placement (POST /api/v1/order),
   WebSocket for order status updates and market data.

2. Idempotency: every order request includes a client-generated order ID (clOrdId).
   If the market maker's network blips and they retry the same clOrdId, the
   platform recognizes it as a duplicate and returns the existing order status
   instead of creating a duplicate order. This is critical — network issues
   during volatility can cause retries, and without idempotency, you'd create
   phantom orders.

3. Rate limiting: token bucket per API key, configurable by account tier.
   Institutional makers get higher limits than retail traders.

4. Authentication: HMAC-signed requests with timestamp in the signature to
   prevent replay attacks. But the signature check must be fast — pre-compute
   what you can.

5. Response: return immediately with 'accepted' status, not 'filled'.
   The actual fill comes via WebSocket push. This decouples order submission
   latency from matching engine latency.

6. Graceful degradation: if downstream (risk engine, matching engine) is slow,
   fail fast — return 503 immediately rather than queuing indefinitely.
   Market makers prefer a fast rejection over a slow acceptance."

Q12: You need to guarantee that a market maker's order is either fully processed or fully rejected — no partial states. How do you ensure consistency in a distributed order processing pipeline?

Core points:

  • At-least-once delivery + idempotent processing
  • Outbox pattern for critical state transitions
  • Reconciliation for eventual consistency

Answer:

"In a distributed pipeline, the classic failure mode is: the matching engine
processes the order but the response fails to reach the gateway, or the position
update succeeds but the fee calculation fails. You end up in a partial state.

My approach:

1. Each order gets a globally unique order ID (can be client-generated clOrdId
   or server-assigned). This is the idempotency key.

2. Order processing is modeled as a state machine:
   RECEIVED → RISK_CHECKED → MATCHED → SETTLED
   Each state transition is idempotent — replaying the same transition with the
   same order ID is safe.

3. For critical paths (especially position updates and fee calculations):
   use the outbox pattern. The state change and the event emission happen in
   the same database transaction. If the event fails to publish, the database
   transaction rolls back — no partial state.

4. Daily reconciliation: compare order records between gateway, matching engine,
   and settlement system. Any discrepancy → alert + manual investigation.

5. Event sourcing as the aspirational architecture: the order book is a projection
   of the event log. If any downstream system crashes, it replays from the log.

The key insight: in a trading system, you cannot have 2PC across services because
it kills latency. So you accept eventual consistency for non-critical paths
and use reconciliation to catch the rare inconsistencies."

Q13: The strategy engine needs to process market data updates and fire strategy evaluations with minimal latency. How would you structure the threading model?

Core points:

  • Single-threaded per instrument for lock-free processing
  • Disruptor / RingBuffer for event pipeline
  • Avoid thread-per-strategy (context switching kills latency)

Answer:

"The naive approach — one thread per strategy — is a disaster. With 500 strategies,
you'd have 500 threads competing for CPU, and the OS scheduler becomes the bottleneck.

Better approach: event-driven, single-threaded per instrument.

Architecture:
1. Market data events enter a Disruptor ring buffer (lock-free, pre-allocated)
2. A pool of worker threads reads from the ring buffer. Each instrument
   (e.g., BTC-USDT, ETH-USDT) is pinned to a specific thread — this ensures
   all processing for that instrument is single-threaded and lock-free.
3. Each worker: receives market data tick → looks up which strategies are
   subscribed to this instrument → evaluates each strategy's pricing logic
   (calling into quant's plugin/library) → generates orders → writes to
   order output ring buffer
4. Order output ring buffer → order gateway workers → submit to matching engine

Why this works:
- No locks on the hot path: processing per instrument is single-threaded
- No thread-per-strategy: 500 strategies served by maybe 8-16 worker threads
- Batching: process multiple ticks in one pass when possible
- Backpressure: ring buffer naturally provides it — if producers outpace
  consumers, the ring fills up and the slowest component controls the pace

Latency target: market data arrives → strategy evaluated → order emitted = sub-100μs."

Q14: The WebSocket gateway needs to maintain 10,000 concurrent connections and push order book updates to all of them. How do you avoid head-of-line blocking and handle slow consumers?

Core points:

  • Non-blocking I/O (Netty)
  • Per-connection send queue with backpressure
  • Disconnect slow consumers

Answer:

"Head-of-line blocking happens when one slow consumer delays updates to everyone
else. On a traditional thread-per-connection model, one slow TLS handshake can
block the entire thread pool. The solution is non-blocking I/O.

Design:
1. Netty (Java NIO) event loop — a small number of I/O threads (1-2 per core)
   handle all 10,000 connections. Each connection is a Channel with its own
   pipeline of handlers.

2. Order book updates arrive from the Disruptor → each gateway worker publishes
   to all subscribed channels. The key: the write to each channel is
   non-blocking. Netty queues the bytes in the channel's send buffer and the
   event loop moves on to the next channel.

3. Slow consumer detection: if a channel's send buffer exceeds a threshold
   (e.g., 64KB queued, meaning the client can't keep up), the gateway either:
   a) Drops non-critical messages (keep only the latest price, skip intermediate
      ticks) — for market data, 'latest value wins'.
   b) If the buffer keeps growing, disconnect the client with a 'slow consumer'
      error code. One slow client must never impact 9,999 others.

4. For critical order status updates that CANNOT be dropped, use a separate
   channel/stream with a smaller buffer and stricter timeout.

The fundamental rule of data broadcasting: 'latest value wins' for market data,
'every message matters' for order acknowledgments. Treat them differently."

Q15: You're monitoring the platform and notice the P99 latency of order processing has spiked from 5ms to 200ms. Both the matching engine and the risk engine look fine individually. What's your debugging approach?

Core points:

  • Look for correlation, not just individual metrics
  • Check the slowest link in the chain
  • Tail latency is usually GC, network, or queue buildup

Answer:

"My first thought: if individual components look fine but end-to-end is slow,
the problem is in the connections between them — the queues, the network, or
coordination overhead.

Step 1: Check if the spike correlates with anything.
  - Time of day? (If it's exactly on the hour, could be a cron job)
  - Any deployment? (Someone pushed config changes?)
  - Volume spike? (Did order rate suddenly increase?)

Step 2: Look at the queues between components.
  - Risk engine → Matching engine: is the queue depth growing?
  - If matching engine P50 is 1ms but the queue has 200ms of backlog,
    the P99 end-to-end would be ~200ms even though matching is fine.

Step 3: Check GC on the gateway nodes.
  - A 200ms GC pause on a gateway looks like 'no orders processed for 200ms'
    followed by a burst. P99 latency jumps, P50 barely moves.

Step 4: Check network between services.
  - TCP retransmissions? Nagle's algorithm causing 200ms delays?
  - Cross-AZ latency? (If one component got moved to a different AZ)

Most likely cause: a GC pause on one of the intermediary services, or a
queue building up at a choke point. The symptom (200ms P99) points to a
periodic stall, not a constant slowdown — and periodic stalls in the JVM
world are almost always GC-related."

速记表

#类型主题
Q1概念流动性/深度/滑点关系
Q2概念Maker vs Taker + 费率差异
Q3概念市价单执行全链路
Q4概念L2 数据 + 做市商为什么需要
Q5概念事前/事中/熔断风控
Q6场景做市商被 pick off → 延迟排查
Q7场景波动率飙升 → 策略引擎过载
Q8场景策略爆亏 → 自动熔断链路
Q9场景多做市商报价冲突 → 价格时间优先
Q10场景策略参数热更新
Q11后端做市商下单 API 设计
Q12后端分布式一致性保证
Q13后端策略引擎线程模型
Q14后端WebSocket 10K 连接 + 慢消费者
Q15后端P99 延迟飙升排查