在上一章中,我们用 Token 块前缀树(Prefix Trie) 实现了最长前缀匹配,并引入了基于并发数的负载惩罚。但在真实高吞吐集群中,网关与后端推理引擎之间仍存在两个关键盲区:
* 只增不减的"幽灵缓存"(Eviction Blindness):前缀树依赖固定 TTL 淘汰节点,但当显存吃紧时,推理引擎(如 vLLM / SGLang)会提前驱逐(Evict / Preempt)部分 KV Cache 块。如果网关不知道这些块已被驱逐,仍按高命中率把请求发往该节点,就会引发重复计算甚至抢占抖动。
* Prefill 与 Decode 相互干扰(Compute-Bound vs. Memory-Bandwidth-Bound):长上下文首字计算(Prefill)是算力密集型且会产生突发性 KV Cache 占用,而逐字生成(Decode)是显存带宽密集型且高度敏感于尾延迟(TPOT)。混部在同一节点时,大 Prefill 容易把正在 Decode 的请求挤爆显存或拉高延迟。
本章我们将补齐这两块拼图:接入后端驱逐/状态反馈实现前缀树精准裁剪,并将网关调度升级为 Prefill / Decode(P/D)分离协同调度。
一、 核心架构设计
- KV Cache 驱逐闭环反馈
* 事件上报与状态探针:后端推理节点在发生 Block 驱逐(或暴露 Prometheus/KV 指标)时,可通过轻量 Webhook / Redis 事件通道上报被驱逐的块哈希列表(evicted_hashes)或节点显存水位。
* 精确裁剪 Trie:网关收到驱逐事件后,直接从对应节点的 PrefixTrie 中移除失效的块路径,让缓存视图与后端显存状态保持收敛,而非干等 TTL 过期。
- Prefill / Decode(P/D)分离两阶段调度
将后端节点划分为 Prefill 池(prefill_nodes) 与 Decode 池(decode_nodes)(通过 RDMA / KV Connector 传输 KV Cache):
* 阶段一:Prefill 亲和选路:优先挑选 前缀命中率高、Prefill 队列轻 的 Prefill 节点执行提示词计算,最大化复用已有 KV Cache,降低首字延迟(TTFT)。
* 阶段二:Decode 稳态选路:优先挑选 Decode 活跃流少、显存余量充足 的 Decode 节点承接后续自回归生成,保证输出阶段吞吐与 TPOT 稳定。
* KV 交接元数据透传:网关在转发给 Prefill 节点时注入请求关联 ID(如 X-Request-Id),并在完成 Prefill 交接后将目标 Decode 节点信息(如 X-Target-Decode-Node)随请求上下文传递给下游引擎,便于引擎完成跨池 KV 传输与流式输出。
二、 生产级代码实现(Python 3.11+)
以下代码在上一章的分布式前缀树基础上,新增了:
* PrefixTrie.evict_blocks 与驱逐事件订阅(gw:trie:evict 及 /internal/kv-eviction 回调);
* Prefill 池与 Decode 池分离调度器(PDDisaggregatedScheduler);
* 异步关闭与并发安全控制。
import asyncio
from dataclasses import dataclass, field
import hashlib
import json
import time
from typing import Dict, List, Optional, Tuple
import uuid
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse
import httpx
import redis.asyncio as aioredis
app = FastAPI(title="P/D Disaggregated & Eviction-Aware Gateway", version="6.0.0")
BLOCK_SIZE = 16
PREFIX_TTL_SECONDS = 300.0
MAX_PREFILL_CONCURRENCY = 32
MAX_DECODE_CONCURRENCY = 96
==========================================
1. 支持精确驱逐的 Token 块前缀树
==========================================
@dataclass
class TrieNode:
children: Dictstr, "TrieNode" = field(default_factory=dict)
last_seen: float = 0.0
hit_count: int = 0
class PrefixTrie:
def init(self, ttl_seconds: float = PREFIX_TTL_SECONDS):
self.root = TrieNode(last_seen=time.monotonic())
self.ttl_seconds = ttl_seconds
def insert_path(self, block_hashes: Liststr, now: Optionalfloat = None) -> None:
ts = now if now is not None else time.monotonic()
curr = self.root
curr.last_seen = ts
for bh in block_hashes:
node = curr.children.get(bh)
if node is None:
node = TrieNode(last_seen=ts, hit_count=1)
curr.childrenbh = node
else:
node.last_seen = ts
node.hit_count += 1
curr = node
def match_prefix_length(self, block_hashes: Liststr, now: Optionalfloat = None) -> int:
if not block_hashes:
return 0
ts = now if now is not None else time.monotonic()
curr = self.root
matched = 0
for bh in block_hashes:
node = curr.children.get(bh)
if node is None:
break
if ts - node.last_seen > self.ttl_seconds:
del curr.childrenbh
break
matched += 1
curr = node
return matched
def evict_blocks(self, evicted_hashes: Liststr) -> int:
"""根据后端驱逐反馈精确移除匹配的块节点及其子树"""
if not evicted_hashes:
return 0
target_set = set(evicted_hashes)
removed = 0
def _prune(node: TrieNode) -> None:
nonlocal removed
keys_to_delete = k for k in node.children if k in target_set
for k in keys_to_delete:
del node.childrenk
removed += 1
for child in list(node.children.values()):
_prune(child)
_prune(self.root)
return removed
def evict_expired(self, now: Optionalfloat = None) -> int:
ts = now if now is not None else time.monotonic()
removed = 0
def _dfs(node: TrieNode) -> bool:
nonlocal removed
expired_keys = [
k for k, child in node.children.items()
if not _dfs(child) and (ts - child.last_seen > self.ttl_seconds)
]
for k in expired_keys:
del node.childrenk
removed += 1
return bool(node.children) or (ts - node.last_seen <= self.ttl_seconds)
_dfs(self.root)
return removed
def build_block_hashes(tokens: Listint, block_size: int = BLOCK_SIZE) -> Liststr:
if not tokens:
return \[\]
hashes: Liststr = \[\]
parent_digest = "ROOT"
for i in range(0, len(tokens), block_size):
chunk = tokensi : i + block_size
payload = f"{parent_digest}:{','.join(map(str, chunk))}".encode("utf-8")
digest = hashlib.blake2b(payload, digest_size=16).hexdigest()
hashes.append(digest)
parent_digest = digest
return hashes
==========================================
2. P/D 分离与驱逐闭环调度器
==========================================
class PDDisaggregatedScheduler:
def init(
self,
prefill_nodes: Liststr,
decode_nodes: Liststr,
redis_url: str = "redis://localhost:6379/0",
w_prefix: float = 0.75,
w_load: float = 0.35,
):
if not prefill_nodes or not decode_nodes:
raise ValueError("prefill_nodes and decode_nodes must both be non-empty")
self.prefill_nodes = prefill_nodes
self.decode_nodes = decode_nodes
all_nodes = list(dict.fromkeys(prefill_nodes + decode_nodes))
self.redis_url = redis_url
self.w_prefix = w_prefix
self.w_load = w_load
self.redis: Optionalaioredis.Redis = None
self.tries: Dictstr, PrefixTrie = {n: PrefixTrie() for n in all_nodes}
self.active_prefill: Dictstr, int = {n: 0 for n in prefill_nodes}
self.active_decode: Dictstr, int = {n: 0 for n in decode_nodes}
self._rr_prefill = 0
self._rr_decode = 0
self._tasks: Listasyncio.Task = \[\]
async def init(self) -> None:
try:
self.redis = await aioredis.from_url(
self.redis_url,
decode_responses=True,
socket_connect_timeout=0.5,
socket_timeout=0.5,
)
await self.redis.ping()
except Exception:
self.redis = None
self._tasks.append(asyncio.create_task(self._pubsub_loop()))
self._tasks.append(asyncio.create_task(self._gc_loop()))
async def close(self) -> None:
for task in self._tasks:
task.cancel()
if self._tasks:
await asyncio.gather(*self._tasks, return_exceptions=True)
if self.redis:
await self.redis.aclose()
def apply_eviction(self, node_id: str, evicted_hashes: Liststr) -> int:
trie = self.tries.get(node_id)
if not trie:
return 0
return trie.evict_blocks(evicted_hashes)
async def broadcast_eviction(self, node_id: str, evicted_hashes: Liststr) -> int:
removed = self.apply_eviction(node_id, evicted_hashes)
if self.redis and evicted_hashes:
try:
await self.redis.publish(
"gw:trie:evict",
json.dumps({"node_id": node_id, "evicted_hashes": evicted_hashes:256}),
)
except Exception:
pass
return removed
async def record_prefix_path(self, node_id: str, block_hashes: Liststr) -> None:
if not block_hashes or node_id not in self.tries:
return
self.triesnode_id.insert_path(block_hashes)
if not self.redis:
return
sample_hashes = block_hashes:64
try:
await self.redis.publish(
"gw:trie:sync",
json.dumps({"node_id": node_id, "block_hashes": sample_hashes}),
)
except Exception:
pass
def select_prefill_node(self, tokens: Listint) -> Tuplestr, float, float:
"""选择前缀命中高且 Prefill 负载低的节点"""
block_hashes = build_block_hashes(tokens, BLOCK_SIZE)
total_blocks = max(len(block_hashes), 1)
now = time.monotonic()
best_node = self.prefill_nodes0
best_score = float("-inf")
best_hit = 0.0
offset = self._rr_prefill % len(self.prefill_nodes)
self._rr_prefill += 1
candidates = self.prefill_nodesoffset: + self.prefill_nodes:offset
for node_id in candidates:
matched = self.triesnode_id.match_prefix_length(block_hashes, now=now)
hit_ratio = matched / total_blocks if block_hashes else 0.0
load_ratio = min(self.active_prefill.get(node_id, 0) / MAX_PREFILL_CONCURRENCY, 1.5)
score = self.w_prefix * hit_ratio - self.w_load * load_ratio
if score > best_score:
best_score = score
best_node = node_id
best_hit = hit_ratio
if block_hashes:
asyncio.create_task(self.record_prefix_path(best_node, block_hashes))
return best_node, round(best_hit, 4), round(best_score, 4)
def select_decode_node(self) -> Tuplestr, float:
"""选择当前 Decode 并发负载最低的节点"""
best_node = self.decode_nodes0
best_load = float("inf")
offset = self._rr_decode % len(self.decode_nodes)
self._rr_decode += 1
candidates = self.decode_nodesoffset: + self.decode_nodes:offset
for node_id in candidates:
load_ratio = self.active_decode.get(node_id, 0) / MAX_DECODE_CONCURRENCY
if load_ratio < best_load:
best_load = load_ratio
best_node = node_id
return best_node, round(best_load, 4)
async def _pubsub_loop(self) -> None:
while True:
if not self.redis:
await asyncio.sleep(5.0)
try:
candidate = await aioredis.from_url(
self.redis_url,
decode_responses=True,
socket_connect_timeout=0.5,
socket_timeout=0.5,
)
await candidate.ping()
self.redis = candidate
except Exception:
pass
continue
pubsub = None
try:
pubsub = self.redis.pubsub()
await pubsub.subscribe("gw:trie:sync", "gw:trie:evict")
async for message in pubsub.listen():
if message.get("type") != "message":
continue
channel = message.get("channel")
payload = json.loads(message"data")
node_id = payload.get("node_id")
if channel == "gw:trie:sync":
hashes = payload.get("block_hashes")
if node_id in self.tries and isinstance(hashes, list):
self.triesnode_id.insert_path(hashes)
elif channel == "gw:trie:evict":
evicted = payload.get("evicted_hashes")
if node_id in self.tries and isinstance(evicted, list):
self.triesnode_id.evict_blocks(evicted)
except asyncio.CancelledError:
break
except Exception:
await asyncio.sleep(2.0)
finally:
if pubsub is not None:
try:
await pubsub.unsubscribe("gw:trie:sync", "gw:trie:evict")
await pubsub.aclose()
except Exception:
pass
async def _gc_loop(self) -> None:
while True:
try:
await asyncio.sleep(60.0)
for trie in self.tries.values():
trie.evict_expired()
except asyncio.CancelledError:
break
except Exception:
await asyncio.sleep(10.0)
==========================================
3. 路由端点与驱逐反馈接口
==========================================
PREFILL_URLS = {
"prefill-1": "http://localhost:8001",
"prefill-2": "http://localhost:8002",
}
DECODE_URLS = {
"decode-1": "http://localhost:8101",
"decode-2": "http://localhost:8102",
}
scheduler = PDDisaggregatedScheduler(
prefill_nodes=list(PREFILL_URLS.keys()),
decode_nodes=list(DECODE_URLS.keys()),
)
http_client: Optionalhttpx.AsyncClient = None
@app.on_event("startup")
async def on_startup() -> None:
global http_client
http_client = httpx.AsyncClient(
timeout=httpx.Timeout(connect=5.0, read=120.0, write=30.0, pool=10.0),
limits=httpx.Limits(max_connections=512, max_keepalive_connections=128),
)
await scheduler.init()
@app.on_event("shutdown")
async def on_shutdown() -> None:
await scheduler.close()
if http_client:
await http_client.aclose()
@app.post("/internal/kv-eviction")
async def receive_kv_eviction(request: Request):
"""接收推理引擎上报的 KV Cache 块驱逐事件"""
try:
data = await request.json()
except Exception:
raise HTTPException(status_code=400, detail="Invalid JSON payload")
node_id = data.get("node_id")
evicted_hashes = data.get("evicted_hashes", \[\])
if not isinstance(node_id, str) or node_id not in scheduler.tries:
raise HTTPException(status_code=404, detail="Unknown node_id")
if not isinstance(evicted_hashes, list):
raise HTTPException(status_code=400, detail="evicted_hashes must be a list")
removed = await scheduler.broadcast_eviction(node_id, evicted_hashes)
return {"status": "ok", "node_id": node_id, "pruned_nodes": removed}
def extract_prompt_tokens(messages: list) -> Listint:
parts: Liststr = \[\]
for msg in messages:
if not isinstance(msg, dict):
continue
role = msg.get("role", "")
content = msg.get("content", "")
if isinstance(content, str):
parts.append(f"{role}:{content}")
elif isinstance(content, list):
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
parts.append(f"{role}:{item.get('text', '')}")
joined = "\n".join(parts)
return ord(ch) for ch in joined\[:4096]
@app.post("/v1/chat/completions")
async def pd_proxy_chat_completions(request: Request):
try:
body = await request.json()
except Exception:
raise HTTPException(status_code=400, detail="Invalid JSON body")
messages = body.get("messages", \[\])
if not isinstance(messages, list):
raise HTTPException(status_code=400, detail="'messages' must be a list")
tokens = extract_prompt_tokens(messages)
req_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
prefill_node, prefill_hit, prefill_score = scheduler.select_prefill_node(tokens)
decode_node, decode_load = scheduler.select_decode_node()
prefill_url = f"{PREFILL_URLSprefill_node}/v1/chat/completions"
decode_url = f"{DECODE_URLSdecode_node}/v1/chat/completions"
base_headers = {
k: v for k, v in request.headers.items()
if k.lower() not in {"host", "content-length"}
}
base_headers"X-Request-Id" = req_id
base_headers"X-Prefill-Node" = prefill_node
base_headers"X-Decode-Node" = decode_node
scheduler.active_prefillprefill_node = scheduler.active_prefill.get(prefill_node, 0) + 1
scheduler.active_decodedecode_node = scheduler.active_decode.get(decode_node, 0) + 1
async def stream_pd_pipeline():
prefill_released = False
try:
assert http_client is not None
1. 触发 Prefill 节点计算并准备 KV 交接(若后端支持 P/D 独立接口,可将 max_tokens 设为 1 仅做 Prefill)
prefill_payload = {**body, "stream": False, "max_tokens": 1}
async with http_client.stream("POST", prefill_url, json=prefill_payload, headers=base_headers) as p_resp:
p_resp.raise_for_status()
async for _ in p_resp.aiter_bytes():
pass
Prefill 完成后尽早释放 Prefill 并发槽位,让算力投入下一批长前缀
scheduler.active_prefillprefill_node = max(0, scheduler.active_prefill.get(prefill_node, 1) - 1)
prefill_released = True
2. 在 Decode 节点执行完整生成流输出
async with http_client.stream("POST", decode_url, json=body, headers=base_headers) as d_resp:
d_resp.raise_for_status()
async for chunk in d_resp.aiter_bytes():
yield chunk
finally:
if not prefill_released:
scheduler.active_prefillprefill_node = max(
0, scheduler.active_prefill.get(prefill_node, 1) - 1
)
scheduler.active_decodedecode_node = max(
0, scheduler.active_decode.get(decode_node, 1) - 1
)
return StreamingResponse(
stream_pd_pipeline(),
media_type="text/event-stream",
headers={
"X-Request-Id": req_id,
"X-Gateway-Prefill-Node": prefill_node,
"X-Gateway-Decode-Node": decode_node,
"X-Gateway-Prefill-Hit-Ratio": str(prefill_hit),
"X-Gateway-Prefill-Score": str(prefill_score),
"X-Gateway-Decode-Load": str(decode_load),
},
)
三、 架构权衡与进阶演进方向
| 维度 | 传统单池混部网关 | P/D 分离 + 驱逐反馈网关(本章) | 代价与注意事项 |
|---|---|---|---|
| TTFT(首字延迟) | 受 Decode 抢占波动影响大 | Prefill 池专职算力 + 前缀树命中,更稳定 | 短文本请求多一次跨池交接可能增加少量网络开销 |
| TPOT(字间延迟) | 易被大 Prefill 阻塞 | Decode 池负载独立均衡,尾延迟更可控 | 需保证 Prefill 与 Decode 池间的 KV 传输带宽充足 |
| 缓存视图准确度 | 仅靠 TTL 过期,存在滞后 | 驱逐事件主动裁剪 Trie + Pub/Sub 广播 | 后端需支持上报驱逐块标识,否则退化为 TTL + 负载 |
在生产环境中,若遇到超短 Prompt 请求(例如前缀不足 1 个 Block 或总长度小于阈值),直接在 P/D 之间来回跳转的跨节点开销可能超过收益;通常会在网关层增加一条 短请求直通规则(Fast-Path Bypass),让短请求直接走低负载节点,仅对长上下文请求启用完整的 P/D 分离流水线。