
订单撮合引擎采用分布式分片架构,通过价格分片订单簿(局部跳表维护)、分布式共识协议(如Raft)保障一致性,结合双端匹配逻辑,实现每秒数万笔订单的低延迟与高吞吐。
订单撮合引擎需应对高并发订单处理,核心设计围绕分布式订单簿展开:
| 分片策略 | 定义 | 特性 | 使用场景 | 注意点 |
|---|---|---|---|---|
| 价格分片 | 按订单价格区间划分节点,每个节点维护局部订单簿(如买方价格区间[100,110]) | 负载均衡,减少单点压力,匹配时局部处理 | 高频交易市场(价格区间集中) | 可能导致热点(如价格集中区),需动态调整分片 |
| 订单ID分片 | 按订单ID哈希划分节点,每个节点负责部分订单 | 负载均衡,适合订单ID分布均匀 | 订单ID随机生成(如用户ID) | 需考虑订单ID分布不均,可能引发热点 |
| 时间分片 | 按订单提交时间划分节点(如按秒/分钟) | 适合时间窗口内订单集中场景 | 限价单批量提交(如日内交易) | 时间窗口过短可能导致节点负载不均 |
(注:价格分片是交易系统核心策略,因价格是撮合关键维度。)
# 价格分片节点(伪代码)
class PriceShardNode:
def __init__(self, price_range):
self.price_range = price_range
self.buy_orders = SkipList() # 买方订单(价格从高到低)
self.sell_orders = SkipList() # 卖方订单(价格从低到高)
self.consensus = RaftConsensus() # 全局共识模块
def add_order(self, order_type, price, qty):
if self.price_range[0] <= price < self.price_range[1]:
if order_type == "buy":
self.buy_orders.insert(price, qty) # 插入买方订单
else:
self.sell_orders.insert(price, qty) # 插入卖方订单
self.consensus.sync_order(self, order_type, price, qty) # 同步全局
def match(self):
while not self.buy_orders.is_empty() and not self.sell_orders.is_empty():
buy_price = self.buy_orders.peek_max_price() # 买方最高价
sell_price = self.sell_orders.peek_min_price() # 卖方最低价
if buy_price >= sell_price:
qty = min(self.buy_orders.pop_max_quantity(), self.sell_orders.pop_min_quantity())
self.consensus.record_match(self, buy_price, sell_price, qty) # 记录成交
self.buy_orders.remove_quantity(buy_price, qty) # 更新买方订单
self.sell_orders.remove_quantity(sell_price, qty) # 更新卖方订单
else:
break
def cancel_order(self, order_id, qty):
# 撤销订单(部分成交处理)
if order_id in self.buy_orders:
self.buy_orders.remove_quantity(order_id, qty) # 删除部分量
if self.buy_orders.get_quantity(order_id) == 0:
self.buy_orders.remove(order_id) # 完全撤销
elif order_id in self.sell_orders:
self.sell_orders.remove_quantity(order_id, qty)
if self.sell_orders.get_quantity(order_id) == 0:
self.sell_orders.remove(order_id)
self.consensus.sync_cancel(self, order_id, qty) # 同步撤销操作
(注:SkipList为跳表结构,支持高效操作;RaftConsensus为分布式共识模块,负责全局状态同步。)
“订单撮合引擎设计上,核心是分布式分片架构。订单簿按价格区间分片,每个节点用跳表维护局部订单簿,通过分布式共识(如Raft)保证全局一致。订单路由到对应节点后,节点内按时间优先、价格优先从两端匹配,成交后同步结果。分片减少单点压力,跳表实现高效操作,共识保障数据一致,最终实现每秒数万笔订单的低延迟和高吞吐。”