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

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

Hello,我是小兔大白糖。 读完能用价差、深度、库存敞口描述做市/流动性场景的基本账,不绑定具体交易所。

流动性是在可接受滑点内快速成交的能力,核心看价差、深度与库存敞口。

估计阅读时间:76 分钟

价差、深度与库存敞口
价差、深度与库存敞口 · 点击查看 SVG 原图

定位:后端开发面试,只需基础理解,不涉及量化数学、做市算法编写
每个知识点:通俗定义 → 业务价值 → 后端开发关联 → 面试高频问答


1. 流动性(Liquidity)、盘口深度(Order Book Depth)、滑点(Slippage)

通俗定义

流动性 = 市场上能快速、低成本完成大额交易的能力。类比:菜市场卖白菜——摊位越多、白菜越多 = 流动性越好,你买 100 斤也不会把价格推高。

盘口深度 = 订单簿(Order Book)上挂了多少买单和卖单。深度越深,单个大单对价格的冲击越小。

滑点 = 你期望的价格和实际成交价格之间的差距。下一个 100 BTC 的市价单 → 吃了好几层卖单 → 最终均价和第一档价格差多少 = 滑点。

深度好: 卖1: 100@$50000, 卖2: 200@$50001, 卖3: 500@$50002
  → 买100 BTC → 全部 $50000 成交,滑点=0

深度差: 卖1: 5@$50000,  卖2: 10@$50010, 卖3: 20@$50050
  → 买100 BTC → 均价$50040,滑点=0.08%

业务价值

角色流动性好=流动性差=
交易所用户多、手续费收入高用户流失到竞品
交易员大单不滑点、成本低一买就涨一卖就跌
做市商赚买卖价差(spread)无人交易,挂单成交不了

后端开发关联

你在后端要关心的:
1. 订单簿数据结构 —— 如何存储和快速查询盘口深度
2. 撮合引擎性能 —— 如何在高并发下高效匹配买卖单
3. 行情推送延迟 —— 盘口变化如何以最低延迟推送给交易员
4. 流动性监控 —— 如何实时判断某交易对流动性是否健康

面试高频问答

Q: What is liquidity and why does it matter for a trading platform?

"Liquidity is the ability to execute large trades quickly without significantly
moving the price. On a deep order book, you can buy 100 BTC at close to the
best ask price. On a thin book, the same order eats through multiple price levels
and you end up paying much more — that's slippage.

For a trading platform, liquidity IS the product. Without it, traders leave.
My role as a backend engineer is to ensure the systems that support liquidity —
order matching, market data distribution, risk checks — are fast, reliable,
and can handle spikes without degrading."

2. 做市商(Market Maker)、挂单(Maker)、吃单(Taker)

通俗定义

做市商(Market Maker) = 同时在买一和卖一挂单的人/程序。赚的是买卖价差(spread),提供流动性换取手续费优惠。

做市商挂单:
  买价 $50,000  ← 希望有人卖给他
  卖价 $50,001  ← 希望有人从他这买
  差价 $1 = spread = 做市商的利润

Maker(挂单方) = 在订单簿上挂限价单等着成交的人 → 提供流动性 → 手续费低
Taker(吃单方) = 下市价单立刻吃掉订单簿上已有订单的人 → 消耗流动性 → 手续费高

业务价值

  • Maker 给平台提供深度 → 平台愿意给抵扣手续费
  • Taker 给做市商提供利润 → 做市商愿意继续挂单
  • 良性循环:做市商挂单 → 有深度 → 散户来交易 → 做市商赚 spread → 继续挂单

后端开发关联

你要关心的:
1. 手续费系统:如何区分 maker/taker 并计算不同费率
2. 做市商 API:如何给机构做市商提供低延迟下单、撤单接口
3. Maker/Taker 识别:撮合时如何判断一笔成交里谁是 maker 谁是 taker
   → 先挂在订单簿上的那个是 maker,后来吃掉它的那个是 taker

面试高频问答

Q: What's the difference between a maker and a taker order?

"A maker order adds liquidity — it rests on the order book as a limit order
waiting to be filled. A taker order removes liquidity — it immediately matches
against existing orders on the book.

From a fee perspective: makers pay lower fees because they provide value to
the platform, while takers pay higher fees because they consume that liquidity.

From an engineering perspective: recognizing which side is maker vs taker at
match time requires checking order timestamps — the order that arrived first
on the book is the maker."

3. 流动性平台核心运作逻辑

通俗定义

流动性平台 = 连接做市商和交易所的中间层。负责:接收做市商的报价 → 聚合多个做市商的流动性 → 展示给交易端 → 路由订单到最优价格。

核心链路

做市商 A(挂卖单) ─┐
做市商 B(挂卖单) ─┤→ 流动性聚合层 → 订单簿 → 撮合引擎 → 成交/撤单
做市商 C(挂卖单) ─┘        ↑                    ↓
                    策略引擎监控        行情推送给所有用户

后端开发关联

你在后端构建的是:
1. 做市商网关(Market Maker Gateway)— 接收做市商报价,低延迟写入订单簿
2. 报价聚合引擎 — 多个做市商对同一交易对报价,如何合并展示
3. 订单路由 — 用户的交易请求路由到哪个做市商的报价
4. 策略引擎 — 做市商配置的自动化策略如何调度执行
5. 清算结算 — 成交后的资金划转

面试高频问答

Q: Describe how a liquidity platform works at a high level.

"A liquidity platform aggregates quotes from multiple market makers and presents
a unified order book to traders. The core flow is:

1. Market makers submit quotes (bid/ask) via API or WebSocket
2. The platform validates, normalizes, and merges these into a consolidated book
3. When a trader places an order, the matching engine finds the best price
   across all liquidity providers
4. Post-trade: settlement, fee calculation, position update

The key architectural challenge is latency — every microsecond between a market
maker updating their quote and that update reaching the order book is risk for
them. So we need ultra-low-latency market data distribution and order routing."

4. 做市策略的基础运作逻辑

通俗定义

做市策略 = 交易员设定一组参数(什么价格挂、挂多少量、价差多大、什么时候撤),策略引擎自动循环执行"挂单→监控→调整→撤单"。

注意:你不需要懂策略怎么写。你只需要懂"交易员配参数 → 系统自动执行"这条链路。

执行链路

交易员配置策略:
  "BTC-USDT,双边挂单,价差 0.1%,单边量 5 BTC,
   偏离市场价 > 0.5% 时撤单重挂,每 100ms 检查一次"

↓

策略引擎读取配置 → 订阅行情 → 计算挂单价
  → 发送限价单到订单簿 → 监控成交/市场变化
  → 成交了?补单(保持两边都有量)
  → 价格跑了?撤掉旧单 → 新价格重新挂

↓

这条链路全部自动化,交易员只需要调参数

后端开发关联

你负责的是策略引擎的"骨架",不是策略逻辑本身:
1. 策略配置管理:参数的 CRUD、版本控制、灰度发布
2. 策略调度:什么时机触发策略检查?定时器?行情变化事件?
3. 策略执行沙箱:策略跑炸了不能影响其他策略或主服务
4. 风险检查:每笔策略发出的订单都要过风控
5. 监控:策略的盈亏、成交率、延迟——交易员要实时看

面试高频问答

Q: How does a strategy engine execute a market-making strategy?

"I don't write the strategy logic myself — that's the quant team's work.
What I build is the execution framework:

1. Strategy configuration: traders set parameters like spread width, order size,
   re-quote threshold, max position via a config service
2. Scheduling loop: the engine reads config, subscribes to market data,
   calculates target orders, and sends them to the matching engine
3. Risk gating: every order generated by a strategy must pass through
   pre-trade risk checks before reaching the market
4. Monitoring & circuit breakers: if P&L drops below threshold or quote rate
   exceeds limits, the engine auto-suspends the strategy

My job is making this pipeline fast, reliable, and safe — not designing the
pricing model inside it."

5. 策略引擎(Strategy Engine)、策略调度(Strategy Scheduler)、策略参数配置

通俗定义

概念通俗类比做什么
策略引擎自动驾驶系统执行策略逻辑:读行情→算价格→发订单
策略调度交通指挥中心决定什么时候触发哪个策略:定时/事件驱动/手动
参数配置驾驶参数面板存储交易员设定的参数(价差/量/风控阈值等)

后端开发关联

策略引擎:
  → 高并发:同时运行几百个策略实例
  → 低延迟:从行情变化到策略发出订单,延迟要 <1ms
  → 隔离性:一个策略 OOM 不能影响其他

策略调度:
  → 事件驱动架构:行情更新事件 → 触发相关策略
  → 优先级:做市策略优先于套利策略
  → 过载保护:策略执行超时怎么办 → 降级/跳过

参数配置:
  → 热更新:改参数不需要重启策略
  → 版本管理:谁改了什么参数、什么时候改的 → 审计
  → 回滚:参数配错了能一键回滚到上一个版本

面试高频问答

Q: How would you design a strategy parameter configuration system?

"Three principles:

1. Hot-reload: parameters must take effect without restarting the strategy.
   I'd use a configuration center (like Nacos/Apollo) with a listener pattern —
   when a trader updates their spread from 0.1% to 0.2%, the strategy instance
   picks up the change within seconds.

2. Versioning & audit trail: every parameter change is logged with who changed
   it, when, and the old vs new value. This is critical for post-mortem analysis
   if a strategy loses money.

3. Validation & guardrails: the config service validates that parameters are
   within safe ranges before accepting them. For example, an order size of
   '100000 BTC' should be rejected at the API level, not discovered when
   the strategy tries to place it."

6. Level 2 行情数据、WebSocket 行情推送、低延迟数据广播

通俗定义

概念是什么类比
L1 行情只有最优买卖价(买一、卖一)只告诉你"白菜 $2/斤"
L2 行情前 N 档买卖价格+量告诉你"卖1有100斤$2,卖2有200斤$2.1..."
WebSocket 推送服务端主动推送给客户端,不轮询餐厅 buzzer 响了 → 你的菜好了
增量推送只推变化的部分"卖2-卖5没变,卖1从$2变成$1.99"

业务价值

做市商需要 L2 深度来做决策——只看最优价不够。而且必须低延迟——行情延迟 100ms,做市商可能已经亏了。

后端开发关联

技术挑战:
1. 高并发连接:5000 个做市商同时订阅 → 每个一个 WebSocket 连接
2. 低延迟广播:盘口变化 → 推送给所有订阅者,p99 < 1ms
3. 增量 vs 全量:全量推送带宽爆炸,增量推送客户端需要状态同步
4. 消息可靠:做市商断连重连后,如何恢复到最新状态(snapshot + delta)
5. 背压控制:消费慢的客户端怎么办 → 断开 or 降速

常用方案:
  → LMAX Disruptor(RingBuffer 无锁队列)做行情分发
  → Aeron/UDP multicast 做极低延迟广播
  → 序列化选 SBE(Simple Binary Encoding)而非 JSON/Protobuf

面试高频问答

Q: How do you design a low-latency market data distribution system?

"The goal is to get order book updates from the matching engine to subscribers
in under 1 millisecond end-to-end.

Architecture:
1. Matching engine emits order book deltas (not full snapshots) to a Disruptor
   ring buffer — lock-free, single producer, multiple consumers
2. Consumers (WebSocket gateways) read from the ring buffer and push to connected
   clients. Each gateway handles ~10K connections via Netty (async I/O)
3. Binary encoding (SBE) instead of JSON — reduces payload from ~200 bytes
   to ~40 bytes per tick, which matters at 100K messages/second

Edge cases:
- Slow consumers: if a client can't keep up, throttle or disconnect.
  Never let one slow client block the entire broadcast.
- Reconnection: client sends the last known sequence number, server replays
  missed deltas from an in-memory ring buffer or falls back to sending a
  full snapshot if the gap is too large."

7. 事前风控、事中风控、熔断机制、仓位风险限制

通俗定义

阶段检查内容举例
事前订单发出前"这笔订单量超过单笔上限?挂单价格偏离市场价>10%?"
事中订单执行中/持仓变化时"策略累积仓位超过上限?单日亏损超过阈值?"
事后交易完成后"策略盈亏和预期偏差太大?某账户交易频率异常?"
熔断触发阈值立刻停"策略 5 分钟内亏了$50K → 暂停策略所有订单"

业务价值

做市商手里可能同时跑几十个策略、管理几百万美元仓位。没有风控 = 一个 bug 可能几分钟亏掉几个月的利润。

后端开发关联

风控系统架构:
  Pre-trade Risk Gateway → 每笔订单必过,延迟必须 <100μs
  Real-time Risk Monitor → 持续计算仓位/盈亏,延迟 <10ms
  Circuit Breaker → 触发阈值后,50μs 内发出暂停指令

技术挑战:
  → 风控检查不能成为延迟瓶颈
  → 规则要热更新(紧急情况下不能等发布)
  → 熔断后要能快速恢复("fat finger"误触发怎么办)

面试高频问答

Q: How would you implement a pre-trade risk check without adding latency?

"Pre-trade risk must be ultra-fast — you can't add 5ms to every order.
The approach is:

1. In-memory risk rules — load all active rules into a local cache,
   refreshed via config push (not polling). No database/cache lookup on
   the hot path.

2. Pre-computed limits — for example, remaining position capacity is
   updated asynchronously after each trade, so the pre-trade check only
   needs a single 'if remaining >= orderQty' comparison.

3. Circuit breaker is just a boolean flag in memory.
   Strategy risk breach → flip circuitBreakerOpen = true → all subsequent
   orders from that strategy are rejected in nanoseconds.

4. If a check must query an external service, use a timeout < 1ms and
   default to 'reject if timeout' — never let a slow risk check silently
   pass a dangerous order."

8. 大型加密货币交易所 机构做市、自动化做市、跨市场对冲

通俗定义

机构做市:大型加密货币交易所 为专业做市商(如 Jump、Wintermute)提供专属 API、更低费率、更高下单频率限制。这些做市商跑的是自己的策略,通过 大型加密货币交易所 的流动性平台连接到交易所。

自动化做市:不是 AMM(Uniswap 那种链上池子),而是 大型加密货币交易所 提供策略引擎让做市商配置自动化策略。做市商不需要自己写代码部署系统,直接用 大型加密货币交易所 的平台配参数就行。

跨市场对冲:做市商同时在 大型加密货币交易所 和 大型加密货币交易所 交易同一币种。在 大型加密货币交易所 上挂卖单 → 成交了 → 立刻在 大型加密货币交易所 上买入对冲 → 赚取两个交易所之间的价差。

业务价值

机构做市商是流动性平台的核心客户——他们贡献了 70%+ 的盘口深度。平台的目标是让他们越做越爽:低延迟、低费率、好用的工具。

后端开发关联

你需要关注的:
1. Multi-tenant isolation:机构 A 的策略绝不能看到机构 B 的参数/仓位
2. API rate limiting:不同等级做市商有不同的下单频率上限
3. Cross-market data feeds:如果支持跨市场对冲,平台需要提供其他交易所的行情
4. Fee engine:Maker/Taker 费率因客户等级不同而不同

面试高频问答

Q: How does institutional market making differ from retail trading on 大型加密货币交易所?

"Institutional market makers are not manually clicking buy/sell.
They run automated strategies that submit thousands of quotes per second.
大型加密货币交易所 provides them with:

1. Dedicated API endpoints with higher rate limits and lower latency
2. Maker rebates — they pay negative fees (earn fees) for providing liquidity
3. A strategy engine platform where they can configure and run strategies
   without deploying their own infrastructure
4. Risk management tools: position limits, circuit breakers, kill switches

From an engineering perspective, institutional traffic is fundamentally
different from retail traffic — it's high-frequency, low-latency, and one
misbehaving strategy can flood the system. So we need per-account rate limiting,
strict pre-trade checks, and tenant isolation."

速记卡片

编号概念一句话
1流动性能快速低成本交易大额 → 盘口深=流动性好
2Maker/Taker挂单等成交=Maker,吃掉已有挂单=Taker
3流动性平台聚合做市商报价 → 统一订单簿 → 撮合交易
4做市策略交易员配参数 → 策略引擎自动挂单/调价/撤单
5策略引擎执行框架 = 调度 + 配置 + 风控沙箱
6L2/WS推送前N档深度 + 增量推送 + 低延迟广播
7风控事前(发前检查) + 事中(持仓监控) + 熔断(阈值自停)
8机构做市专业做市商API + 自动化策略平台 + 跨市场对冲

题型:概念理解题(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 延迟飙升排查

优先级 1:岗位核心考察
方向:Java 高并发 / 分布式架构 / 低延迟系统 / 系统设计
每题结构:问题 → 核心知识点 → 高分回答要点 → 推荐回答话术(英文)


一、Java 核心 (Q1-Q8)


Q1: Explain the difference between synchronized and ReentrantLock. When would you use each?

核心知识点:锁实现、可中断、公平性、条件变量、性能差异

高分要点:

  • synchronized = JVM monitor,自动释放,不可中断
  • ReentrantLock = AQS 实现,必须 finally unlock,可中断/可超时/可公平
  • 性能在 JDK 6+ 后相当(锁升级后)
  • 选 ReentrantLock 场景:需要 tryLock 超时、需要 Condition 多条件、需要公平锁

推荐回答:

"Synchronized is the JVM built-in lock — it's simple, automatically releases
on block exit or exception, but you can't interrupt a thread waiting for it
and you can't timeout.

ReentrantLock gives you more control: tryLock with timeout, lockInterruptibly,
fair mode, and multiple Condition objects for producer-consumer scenarios.

Before JDK 6, ReentrantLock was faster. Since then, synchronized has lock
escalation (biased → lightweight → heavyweight) so performance is comparable.

My rule: default to synchronized for simplicity. Reach for ReentrantLock only
when I need timeout, interruptibility, or multiple conditions — which is
usually in complex producer-consumer or resource management code."

Q2: How does a ThreadPoolExecutor work? How do you choose core pool size, max pool size, and queue type?

核心知识点:线程池生命周期、参数选择、拒绝策略、四种队列对比

高分要点:

  • 核心线程 = 常驻,最大线程 = 瞬时可扩容上限
  • 有界队列保护系统,无界队列可能导致 OOM
  • 拒绝策略:CallerRunsPolicy(推荐,背压)、AbortPolicy(默认抛异常)
  • 公式:CPU密集型=N+1,IO密集型=2N(但要用实际压测验证)
ThreadPoolExecutor pool = new ThreadPoolExecutor(
    8,                               // corePoolSize
    16,                              // maximumPoolSize
    60, TimeUnit.SECONDS,            // keepAlive
    new LinkedBlockingQueue<>(1000), // bounded queue → backpressure
    new ThreadPoolExecutor.CallerRunsPolicy() // caller runs on overload
);

推荐回答:

"A ThreadPoolExecutor has a lifecycle: when a task is submitted, if there are
fewer than corePoolSize threads running, it creates a new thread. If all core
threads are busy, the task goes to the work queue. If the queue is full AND
fewer than maxPoolSize threads exist, it creates an additional thread.

Most important rule: NEVER use unbounded queues with Executors.newFixedThreadPool
or newCachedThreadPool. It WILL OOM under high load. Always use bounded queues.

For a trading system, I'd choose:
- corePoolSize = CPUs for CPU-bound tasks
- A bounded LinkedBlockingQueue for backpressure
- CallerRunsPolicy as rejection handler — it slows down the producer instead
  of silently dropping tasks, which is critical for financial systems"

Q3: How do you avoid GC pauses in a latency-sensitive trading system?

核心知识点:GC 选择、对象分配优化、堆外内存

高分要点:

  • 选 ZGC/Shenandoah(<1ms STW,4TB 以下选 G1)
  • 避免在热路径上创建对象(对象池、基本类型代替包装类)
  • 堆外内存(DirectByteBuffer)绕开 GC
  • -XX:+DisableExplicitGC 禁止 System.gc()

推荐回答:

"For latency-sensitive systems, the goal is to keep GC pauses under 1ms.
Three layers:

1. GC choice: ZGC or Shenandoah — both have sub-millisecond STW pauses
   regardless of heap size. G1 is good for <4TB heaps with predictable pauses.

2. Object allocation discipline on the hot path:
   - Use primitive types instead of boxed (long not Long)
   - Pre-allocate and reuse objects via object pools (RingBuffer slots)
   - Avoid string concatenation and auto-boxing in the order processing path

3. Off-heap memory: DirectByteBuffer or Unsafe for large, long-lived data
   structures that would otherwise trigger GC.

The LMAX Disruptor pattern is a great example — a pre-allocated ring buffer
with no allocation on the hot path. I've used this approach for market data
distribution with zero GC in the critical code path."

Q4: What is the Disruptor pattern and why is it used in trading systems?

核心知识点:RingBuffer、无锁、伪共享、Sequence Barrier

高分要点:

  • 预分配对象 → 无 GC
  • CAS 代替锁 → 高并发
  • Padding 避免伪共享 → 缓存行友好
  • 单生产者顺序写 → 无锁争用

推荐回答:

"The LMAX Disruptor is a high-performance inter-thread messaging library built
on a pre-allocated ring buffer. It's widely used in trading systems because:

1. Zero allocation on the hot path — slots are pre-allocated, so no GC
2. Lock-free using CAS and memory barriers instead of synchronized blocks
3. Cache-line padding to avoid false sharing between producer and consumer
4. Batching — consumer can process multiple events in one claim, amortizing cost

In a trading context, I'd use it for:
- Market data fan-out: matching engine writes ticks → Disruptor → multiple
  consumers (WebSocket gateways, strategy engines, risk monitors) read in parallel
- Order processing pipeline: pre-trade check → matching → post-trade settlement

The key insight is that the ring buffer imposes backpressure naturally:
if consumers are slow, the ring fills up and the producer blocks automatically."

Q5: What are the volatile and CAS semantics in Java? Where does CAS not work?

核心知识点:可见性、指令重排、ABA 问题、自旋消耗

高分要点:

  • volatile:保证可见性 + 有序性,不保证原子性
  • CAS:Compare-And-Swap,乐观锁,无 STW
  • CAS 失败 → 自旋重试 → 高竞争下 CPU 浪费 → LongAdder 分段累加
  • ABA 问题 → AtomicStampedReference

推荐回答:

"volatile guarantees visibility — a write by one thread is immediately seen
by others because it forces a store barrier to flush to main memory. It also
prevents instruction reordering around the variable. But it does NOT make
compound operations atomic — i++ is still a read-modify-write, not atomic.

CAS (Compare-And-Swap) provides atomic update without locks. It works by
comparing the current value with an expected value and only swapping if they
match — all in a single CPU instruction (cmpxchg).

CAS fails under high contention: threads spin, wasting CPU. For counters under
heavy contention, I use LongAdder which segments the counter into multiple cells.

ABA problem: between CAS read and write, the value changed from A to B back to A.
CAS sees A and proceeds, missing the intermediate change. Use AtomicStampedReference
to embed a version number for this case."

Q6: Explain the JVM memory model. What goes in each space?

核心知识点:堆结构、元空间、直接内存、GC 分区

高分要点:

┌──── Heap ─────────────────────────────┐
│  ┌── Young ──┐  ┌── Old (Tenured) ──┐ │
│  │ Eden│S0│S1│  │                    │ │
│  └──────────┘  └────────────────────┘ │
└──────────────────────────────────────┘
┌── Metaspace (native memory) ──────────┐
│  Class metadata, method data          │
└──────────────────────────────────────┘
┌── Direct Memory (native) ─────────────┐
│  NIO ByteBuffers                      │
└──────────────────────────────────────┘

推荐回答:

"The JVM memory is split into heap and non-heap areas.

Heap:
- Young Generation (Eden + two Survivor spaces S0/S1): new objects. Minor GC
  happens here — copies surviving objects between survivor spaces and eventually
  promotes long-lived objects to Old.
- Old Generation: long-lived objects. Full GC here is expensive.
  Tuning: -Xms -Xmx set heap size, -XX:NewRatio sets young/old ratio.

Non-heap:
- Metaspace: class metadata stored in native memory (replaced PermGen in Java 8).
  Tuning: -XX:MaxMetaspaceSize
- Direct Memory: NIO ByteBuffer.allocateDirect(). Bypasses heap and GC entirely.
  Critical for low-latency systems — but you manage it yourself.

Key insight for trading: allocating objects in the hot path causes GC pressure.
Use direct memory or pre-allocated buffers for market data processing."

Q7: How do you troubleshoot a thread pool where tasks keep timing out?

核心知识点:排查方法、工具、根因分析

高分要点:

  • 监控指标:活跃线程数、队列积压、任务等待时间、拒绝次数
  • 工具:Arthas thread 命令、jstack、Micrometer 指标
  • 根因分类:线程不够 / 任务本身变慢 / 下游阻塞

推荐回答:

"I'd approach this in three steps:

1. Observe: Check metrics — active threads vs pool size, queue depth, task
   completion time distribution (P50/P99). If active threads = max pool size
   AND queue is backing up, the pool is undersized or tasks are blocking.

2. Diagnose with Arthas:
   - 'thread -n 5' to find top CPU-consuming threads
   - 'thread --state BLOCKED' to find threads stuck on locks
   - 'thread --state WAITING' to find threads waiting on I/O or conditions
   This tells me whether tasks are blocking on external calls (Redis, DB, RPC)
   or competing for an internal lock.

3. Root cause fix:
   - If blocking on external calls: add timeout to the call
   - If tasks are CPU-heavy: increase core pool size or optimize the task
   - If queue is backing up: check if downstream (e.g., DB connection pool) is
     the real bottleneck — thread pool is often a symptom, not the cause

I've used exactly this approach to track down a thread leak where
50K threads were in WAITING state — Arthas showed they were all from
a ResponseCache component that was being instantiated per-request
instead of as a singleton."

Q8: Compare ConcurrentHashMap and HashMap + synchronized. Why is ConcurrentHashMap faster?

核心知识点:分段锁、CAS、读无锁

JDK 7 vs JDK 8:

  • JDK 7: Segment 分段锁(默认 16 段)——16 个并发
  • JDK 8: 抛弃 Segment → 每个 bin(链表头)加 synchronized + CAS → 锁粒度到单桶

推荐回答:

"ConcurrentHashMap is faster because it minimizes lock contention through
granular locking:

JDK 7: Used segment-level locking — the map was divided into 16 segments,
each with its own ReentrantLock. Two threads writing to different segments
don't block each other. But all 16 segments share the lock pool.

JDK 8: Replaced segments with per-bucket locking using synchronized on the
first node of each hash bin, combined with CAS for insertions into empty bins.
This means:
- Reads are lock-free (volatile reads)
- Writes only lock the specific hash bucket being modified
- Resize operations are cooperative — multiple threads help with migration

For a trading system, ConcurrentHashMap is the default choice for any
shared in-memory data structure (order book cache, position tracker, etc.)
because reads have zero lock overhead."

二、分布式架构 (Q9-Q14)


Q9: How do you ensure exactly-once processing in a distributed trading system?

核心知识点:幂等性、事务消息、去重表

高分要点:

  • 通过 idempotency key + DB 去重实现 exactly-once 语义
  • Kafka: idempotent producer + consumer dedup
  • 金融场景:DB 唯一键 = 最终保底

推荐回答:

"True exactly-once is impossible in a distributed system (FLP result).
What we implement is effectively-once using idempotency:

1. Producer: assign a unique idempotency key (order ID, event sequence number)
   → Kafka idempotent producer deduplicates by PID + sequence number
   → RocketMQ: the broker deduplicates by message key

2. Consumer: maintain a dedup table in the database
   → CREATE TABLE consumed_messages (msg_id VARCHAR PRIMARY KEY, consumed_at TIMESTAMP)
   → Before processing: INSERT INTO consumed_messages VALUES (msg_id)
     → Success: first time processing → proceed
     → DuplicateKeyException: already processed → skip (idempotent)

3. Fallback: the DB unique constraint IS the ultimate dedup guarantee.
   Even if Redis SETNX fails or the dedup cache expires, the DB primary key
   prevents double-processing.

For order processing specifically, the order ID is naturally unique,
so the order table itself serves as the dedup mechanism."

Q10: Design a circuit breaker for a strategy engine that places orders. How to fail safely?

核心知识点:熔断器状态机、半开探测、快速失败

高分要点:

状态机:CLOSED → (errors > threshold) → OPEN → (timeout) → HALF-OPEN
         ↑                                                     │
         └──── (success) ←──────┘                     (failure) └──→ OPEN

策略引擎专用熔断维度:
  - 策略级别:单策略熔断(盈亏超限、下单频率异常)
  - 账户级别:单账户总仓位熔断
  - 全局级别:交易所连接断开 → 全部策略暂停

推荐回答:

"A circuit breaker for a strategy engine has three states and three levels:

Per-strategy breaker:
  → If a strategy loses $X in Y minutes → flip to OPEN
  → All subsequent order requests from this strategy are immediately rejected
    (nanosecond fast — just check a boolean flag in memory)
  → After cooling period (e.g., 5 min), transition to HALF-OPEN
  → Allow one small order through → if OK, close breaker; if not, re-open

Per-account breaker:
  → Monitor total position across all strategies on the same account
  → If net position exceeds risk limit → suspend ALL strategies on that account

Global breaker (kill switch):
  → If exchange connectivity fails or latency exceeds threshold
  → Emergency STOP: cancel all open orders, reject all new orders
  → Manual intervention required to resume

Critical design: the breaker check must be on the order hot path.
I use in-memory boolean flags updated atomically — no database lookup,
no cache call. Open/close latency must be measured in microseconds."

Q11: Redis cache breakdown, penetration, and avalanche — how to handle in a trading system?

核心知识点:缓存三大问题、解决方案

问题场景方案
穿透查询不存在的数据Bloom Filter 预过滤
击穿热点 key 过期瞬间大量请求互斥锁 + 逻辑过期
雪崩大量 key 同时过期TTL + 随机抖动

推荐回答:

"Three distinct problems, three distinct solutions:

Cache Penetration (querying data that doesn't exist):
  → Attacker queries non-existent instrument → every request hits DB
  → Solution: Bloom Filter pre-check. If filter says 'definitely not exists',
    return immediately. If 'possibly exists', then check cache/DB.
  → For trading: pre-load all valid instruments into a local Bloom Filter.

Cache Breakdown (hot key expiry):
  → BTC order book cache expires → thousands of requests hit DB simultaneously
  → Solution: 'never expire' pattern. Set physical TTL but keep a logical
    expiry timestamp in the value. Background thread refreshes before logical
    expiry. On cache miss, use a distributed lock so only ONE thread penetrates.

Cache Avalanche (many keys expire simultaneously):
  → Solution: add random jitter to TTL (e.g., 300s + random(0,60))
  → For trading: order book snapshots for different instruments should have
    staggered refresh times, not all refreshing at minute boundaries."

Q12: Kafka vs RocketMQ — which would you choose for order events and why?

核心知识点:事务消息、延迟消息、顺序性、适用场景

高分要点:

场景选型理由
订单事件流RocketMQ事务消息保证"本地事务+消息发送"原子
行情数据管道Kafka百万 TPS 吞吐,顺序 IO
策略信号通知RocketMQ低延迟、优先级消息
审计日志Kafka大量、容忍秒级延迟

推荐回答:

"Both have their place in a trading system:

For ORDER EVENTS — I'd choose RocketMQ:
  → Transactional messages: order creation + MQ send in one atomic operation.
    If the DB write succeeds but MQ send fails, the half-message + broker
    callback mechanism ensures consistency.
  → Lower latency: RocketMQ's push model and simpler architecture give
    single-digit-millisecond end-to-end latency.

For MARKET DATA — I'd use Kafka:
  → Higher throughput: sequential disk I/O + zero-copy → millions of messages/sec
  → Better for streaming/ETL: market data → Kafka → Flink → analytics

For a strategy engine, I'd use RocketMQ for order events (need transactional
guarantees) and Kafka for market data distribution (need throughput).

If the team only has one MQ, I'd lean RocketMQ for trading because correctness
(transactional messaging) matters more than raw throughput."

Q13: How do you implement a distributed lock for a trading scenario?

核心知识点:Redis Redlock、ZooKeeper、etcd

高分要点:

  • Redis SET NX EX(单实例简单,非 CP)
  • Redlock(多实例,CP 妥协,有争议)
  • ZooKeeper 临时顺序节点(CP,但运维重)
  • 锁续期:watchdog 自动续期

推荐回答:

"For a trading system, I'd use Redis with the following pattern:

Lock: SET order:lock:123 unique_value NX EX 30
  → NX = only if not exists, EX 30 = auto-expire in 30 seconds
  → unique_value = UUID to prevent accidentally releasing another's lock

Unlock (Lua script, atomic):
  if redis.call('get', KEYS[1]) == ARGV[1] then
    return redis.call('del', KEYS[1])
  end

Watchdog: background thread renews the lock every 10 seconds if the business
  logic is still running. This prevents the lock expiring during long operations.

Why not Redlock? Martin Kleppmann's analysis showed Redlock has safety issues
under network partitions. For trading, if I need CP guarantees, I'd use
ZooKeeper's ephemeral sequential nodes with session-based locking instead.

But honestly: for most trading scenarios, a well-implemented Redis lock with
watchdog is sufficient. The key risk isn't the lock implementation — it's
the split-brain scenario where two instances think they hold the lock because
GC paused one of them beyond the lock TTL."

Q14: API rate limiting design — how to handle a market maker that floods your gateway?

核心知识点:令牌桶、滑动窗口、分级限流

高分要点:

  • 单用户限流 + 全局限流 双重保护
  • 令牌桶算法(允许突发,平均限流)
  • 越限返回 429 + Retry-After header

推荐回答:

"I'd implement a two-tier rate limiter using the token bucket algorithm:

Tier 1 — Per-account limiter:
  → Each market maker has a rate limit defined in their SLA
  → Token bucket: tokens refill at R tokens/second, bucket capacity C
  → This allows bursts up to C while averaging R

Tier 2 — Global gateway limiter:
  → Total capacity across all accounts
  → Prevents one misbehaving client from starving others
  → If global limit is 100K RPS and account A uses 90K, account B can only
    use the remaining 10K regardless of their individual limit

Implementation:
  → In-memory token buckets per account (Redis for accuracy, local for speed)
  → Check at the gateway filter level, BEFORE the request reaches business logic
  → Return HTTP 429 with Retry-After header when throttled

For ultra-low-latency scenarios, use in-memory counters with periodic sync to
Redis instead of calling Redis on every request — the 100ms sync delay is
acceptable for rate limiting accuracy vs the microseconds saved per request."

三、系统设计 (Q15-Q18)


Q15: Design a high-throughput, low-latency order processing system

核心知识点:撮合引擎、订单簿数据结构、Disruptor、风控网关

提示答题框架:接口 → 数据模型 → 核心链路 → 性能优化 → 容灾

推荐回答:

"Architecture layers:

1. API Gateway (Netty-based, async non-blocking):
   → Accepts orders via REST/WebSocket/FIX protocol
   → Rate limiting & authentication at the edge
   → Passes to pre-trade risk check

2. Pre-Trade Risk Gateway (in-memory, <100μs):
   → Validates: order size, price reasonability, position limits
   → Uses in-memory rule cache with hot-reload
   → Rejects immediately on any violation

3. Order Matching Engine (core):
   → Order book: ConcurrentSkipListMap (price-sorted) for bids/asks
   → Price-time priority: lowest ask + earliest timestamp matches first
   → Disruptor ring buffer for matching events
   → Output: match events → post-trade processing + market data broadcast

4. Post-Trade Pipeline:
   → Trade settlement → position update → P&L calculation
   → Fee calculation (maker/taker differentiated)
   → Market data delta broadcast via Disruptor → WebSocket gateways

Performance targets:
   → End-to-end: order acceptance to match < 1ms P99
   → Throughput: 100K+ orders/second per matching engine instance
   → GC: ZGC with <1ms pause target

Resilience:
   → Primary-standby matching engine with Raft-based log replication
   → If primary fails, standby takes over with < 1 second gap
   → All orders persisted to WAL before match confirmation"

Q16: Design a real-time position & P&L monitoring system for market makers

核心知识点:事件驱动、CDC、时序数据、WebSocket 推送

推荐回答:

"Data flow:

1. Trade event ingestion:
   → Every match (trade) is an event published to a high-throughput MQ (Kafka)
   → Each trade event contains: account, instrument, side, price, qty, timestamp

2. Position aggregation (stream processing):
   → Kafka → Flink/Kafka Streams → maintain running position per account+instrument
   → Keyed by (account_id, instrument) for consistent state
   → Output: position snapshot every time it changes

3. P&L calculation:
   → Realized P&L: SUM(trade_profit) = SUM(trade_qty * (price - avg_entry))
   → Unrealized P&L: current_position * (mark_price - avg_entry_price)
   → Mark price = last traded price OR index price from oracle

4. Distribution to frontend:
   → Position/P&L snapshots → Redis sorted set (keyed by account, TTL 1s)
   → Market makers subscribe via WebSocket for real-time push
   → Frontend dashboard updates on every position change

Alerting:
   → If P&L drops below threshold → trigger alert + optional auto-suspend
   → Use sliding window: 'loss > $10K in last 5 minutes' not just absolute"

Q17: Design a market data distribution system (order book broadcast)

核心知识点:增量推送、序列号、snapshot+delta、Disruptor

推荐回答:

"Design:

1. Data source: Matching engine
   → Emits order book deltas: {seq: 1001, side: BID, price: 50000, qty: 2.5}
   → Not full order book — only the changed price level

2. Fan-out: Disruptor Ring Buffer
   → Single producer (matching engine) → 3 consumer groups in parallel:
     a) Public WebSocket gateways (for retail traders)
     b) Institutional FIX/API gateways (for market makers)
     c) Strategy engine feed (for automated strategies)

3. Delta encoding:
   → SBE (Simple Binary Encoding) instead of JSON
   → Payload per tick: ~30 bytes (vs ~200 bytes JSON)

4. Snapshot + Delta model:
   → New connection → send full order book snapshot (all levels)
   → Subsequent updates: send only deltas with monotonically increasing seq
   → Client tracks last seen seq → on reconnect, send 'replay from seq N'
   → Server maintains ring buffer of last 10,000 deltas for replay
   → If client falls behind > 10K → force full snapshot

5. Slow consumer handling:
   → If client TCP buffer is full → throttle or disconnect
   → Never let one slow client block the broadcast

Performance:
   → Matching engine tick → last WebSocket subscriber: < 1ms P99
   → 500K messages/second through the ring buffer
   → GC-free on the hot path (pre-allocated objects in ring buffer)"

Q18: Design a fault-tolerant configuration service for strategy parameters

核心知识点:热更新、版本管理、灰度发布、回滚

推荐回答:

"Requirements:
  → Hot-reload: parameter changes take effect without restart
  → Audit: who changed what, when
  → Rollback: one-click revert to previous version
  → Guardrails: parameter validation before acceptance

Architecture:

1. Storage:
  → PostgreSQL for persistence (ACID for audit trail)
  → Redis for hot path reads (strategies read config from Redis, not DB)
  → Config push via Redis Pub/Sub: when config changes → publish event
    → strategy instances subscribe → reload from Redis

2. API for traders:
  → PUT /strategies/{id}/params → validate → write DB → update Redis → publish
  → GET /strategies/{id}/params/history → list all versions
  → POST /strategies/{id}/params/rollback → revert to version N

3. Validation gateway:
  → Parameter range check before persistence
  → e.g., 'spread_pct' must be between 0.01 and 5.0
  → e.g., 'order_size' * 'max_position' < account_balance * leverage
  → Reject invalid at API level, not in strategy execution

4. Canary deployment for config:
  → Roll out to 10% of strategies first → monitor for 5 min
  → If P&L, error rate, latency all OK → roll to 100%
  → If anomaly detected → auto-rollback

This is conceptually similar to what I built for 某业务系统's meltdown
configuration system — Redis Pub/Sub for instant propagation, with
fallback to polling if Pub/Sub fails."

四、算法题 (Q19-Q20)


Q19: Implement a thread-safe LRU cache

高频程度:⭐⭐⭐⭐⭐

核心知识点:HashMap + 双向链表、并发安全

class LRUCache<K, V> {
    private final int capacity;
    private final Map<K, Node> map;
    private final Node head, tail; // dummy nodes
 
    private static class Node<K, V> {
        K key; V value; Node prev, next;
    }
 
    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.map = new ConcurrentHashMap<>();
        head = new Node(); tail = new Node();
        head.next = tail; tail.prev = head;
    }
 
    public V get(K key) {
        Node<K, V> node = map.get(key);
        if (node == null) return null;
        synchronized (this) {
            moveToHead(node);
        }
        return node.value;
    }
 
    public void put(K key, V value) {
        Node<K, V> node = map.get(key);
        synchronized (this) {
            if (node != null) {
                node.value = value;
                moveToHead(node);
            } else {
                node = new Node<>(key, value);
                map.put(key, node);
                addToHead(node);
                if (map.size() > capacity) {
                    Node removed = removeTail();
                    map.remove(removed.key);
                }
            }
        }
    }
}

推荐回答:

"An LRU cache combines a HashMap for O(1) lookup with a doubly-linked list
for O(1) eviction. The HashMap maps keys to list nodes. On access: move the
node to the head. On eviction: remove the tail node.

For thread safety, I synchronize only the list operations — the ConcurrentHashMap
already handles concurrent reads. This gives good throughput for read-heavy
workloads.

Tradeoff: this implementation synchronizes on 'this'. For higher concurrency,
you could use per-segment locking or a ConcurrentLinkedHashMap. But for most
use cases, the simpler approach is sufficient and less bug-prone."

Q20: Top K frequent elements in a stream (Heap + HashMap)

public List<Integer> topKFrequent(int[] nums, int k) {
    // Count frequencies
    Map<Integer, Integer> freq = new HashMap<>();
    for (int n : nums) freq.merge(n, 1, Integer::sum);
 
    // Min-heap of size K
    PriorityQueue<Integer> heap = new PriorityQueue<>(
        Comparator.comparingInt(freq::get));
 
    for (int n : freq.keySet()) {
        heap.offer(n);
        if (heap.size() > k) heap.poll();
    }
 
    return new ArrayList<>(heap);
}
// Time: O(N log K), Space: O(N)

推荐回答: "Count with HashMap (O(N)), then maintain a min-heap of size K (O(N log K)). If K is small, this is efficient. For trading system analogy: this is like finding the top K most traded instruments in real-time — you'd use a similar heap-based approach with a time-decaying counter."


速度检查

模块题数状态
Java 核心8 (Q1-Q8)✅
分布式架构6 (Q9-Q14)✅
系统设计4 (Q15-Q18)✅
算法题2 (Q19-Q20)✅

没有 LeetCode 原题集? 熟练 LRU、TopK、买卖股票(1/2)、岛屿数量、二叉树层序遍历,后端岗够用。重点是系统设计不在算法。

系列:risk-systems 相关通识