到了这一步,网关已经具备了分布式前缀树同步、驱逐闭环反馈、P/D 分离调度、多模型灰度以及基础指标监控能力。但在生产运维(尤其是 Kubernetes 滚动发布或节点缩容)中,仍有两个常见事故点:
* 改配置必须重启网关:调整灰度权重(canary_weight)、增减 Prefill/Decode 后端节点或修改调度权重时,如果每次都重启容器,不仅会打断长连接流式推理,还会丢失本地 PrefixTrie 视图。
* 停机瞬间掐断流式请求:当网关收到 SIGTERM 准备下线时,若负载均衡器尚未摘除该实例,或者网关立即关闭 HTTP 连接池与后台任务,正在进行中且可能耗时数十秒的 SSE 流式推理请求就会直接断开。
本章我们将补全网关生命周期治理的最后三环:配置热更新(Hot Reload)、优雅停机排空(Graceful Draining) 与 高并发流式压测方案。
一、 治理机制设计
- 原子配置热更新(Atomic Config Swap)
* 将不可变的 ModelPoolConfig 映射封装在统一快照对象中,通过原子引用替换(或异步锁保护)更新路由表,同时为新增节点懒初始化 PrefixTrie 与并发计数器。
* 提供 /internal/config/reload 管理接口(生产环境应配合内网鉴权或配置中心事件监听),实现零重启调整灰度比例与节点池。
- 优雅停机排空(Graceful Draining)
* 网关进入 draining 状态后(可通过 SIGTERM 信号触发,也可通过 /internal/drain 手动演练):
* 健康探针 /healthz 返回 503 Service Unavailable,促使上层 NLB / K8s Service 尽快停止向该实例分发新请求;
* 网关拒绝或快速返回 503 处理新到的推理请求,同时等待当前正在流式输出的存量请求(in_flight_streams)自然完成(设置最大排空超时 DRAIN_TIMEOUT,超时后再强制收尾,避免进程卡死)。
- 流式推理高并发压测关注点
与普通 REST 接口不同,大模型流式网关的压测需要同时关注:
* 首字响应时间(TTFT)与流式吞吐(Chunk/s / Tokens/s);
* 前缀命中收敛曲线:并发发送具有共享系统提示词/长上下文的请求时,观察 X-Gateway-Prefix-Hit-Ratio 与节点分布是否符合预期;
* 排空演练验证:在持续流式压测期间触发排空信号,验证存量 SSE 流是否完整结束而不出现 ConnectionResetError 或计数泄漏。
二、 生产级代码实现(Python 3.11+)
以下代码在上一章基础上新增了 动态配置热更新、优雅停机排空控制器(DrainController) 与 健康检查/排空管理端点:
import asyncio
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass, field
import hashlib
import json
import signal
import time
from typing import Any, Dict, List, Optional, Tuple
import uuid
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import PlainTextResponse, StreamingResponse
import httpx
import redis.asyncio as aioredis
try:
from opentelemetry import trace as otel_trace
from opentelemetry.trace import Status, StatusCode
_OTEL_AVAILABLE = True
except ImportError:
_OTEL_AVAILABLE = False
app = FastAPI(title="Production Governed LLM Gateway", version="8.0.0")
BLOCK_SIZE = 16
PREFIX_TTL_SECONDS = 300.0
MAX_PREFILL_CONCURRENCY = 32
MAX_DECODE_CONCURRENCY = 96
DRAIN_TIMEOUT_SECONDS = 30.0
==========================================
1. 可观测性管理器
==========================================
class ObservabilityManager:
def init(self, service_name: str = "llm-inference-gateway"):
self.service_name = service_name
self.request_counter: DictTuple\[str, str, str, str, int] = defaultdict(int)
self.eviction_counter: DictTuple\[str, str, int] = defaultdict(int)
self.latency_sum: DictTuple\[str, str, str, float] = defaultdict(float)
self.latency_count: DictTuple\[str, str, str, int] = defaultdict(int)
self.latency_buckets: DictTuple\[str, str, str, Dictfloat, int] = defaultdict(
lambda: {0.05: 0, 0.1: 0, 0.25: 0, 0.5: 0, 1.0: 0, 2.5: 0, 5.0: 0, 15.0: 0, float("inf"): 0}
)
self.prefix_hit_sum: DictTuple\[str, str, float] = defaultdict(float)
self.prefix_hit_count: DictTuple\[str, str, int] = defaultdict(int)
self.tracer = otel_trace.get_tracer(service_name) if _OTEL_AVAILABLE else None
def observe_request(
self, model: str, node: str, status: str, is_canary: bool, hit_ratio: float
) -> None:
canary_label = "true" if is_canary else "false"
self.request_counter(model, node, status, canary_label) += 1
self.prefix_hit_sum(model, node) += hit_ratio
self.prefix_hit_count(model, node) += 1
def observe_eviction(self, node_id: str, pruned_nodes: int) -> None:
self.eviction_counter(node_id, "pruned") += pruned_nodes
def observe_duration(self, model: str, stage: str, node: str, seconds: float) -> None:
key = (model, stage, node)
self.latency_sumkey += seconds
self.latency_countkey += 1
buckets = self.latency_bucketskey
for bound in buckets:
if seconds <= bound:
bucketsbound += 1
@contextmanager
def span(self, name: str, attributes: OptionalDict\[str, Any] = None):
if self.tracer and _OTEL_AVAILABLE:
with self.tracer.start_as_current_span(name) as sp:
if attributes:
for k, v in attributes.items():
sp.set_attribute(k, str(v))
try:
yield sp
except Exception as exc:
sp.record_exception(exc)
sp.set_status(Status(StatusCode.ERROR, str(exc)))
raise
else:
yield None
def render_prometheus(self, draining: bool, in_flight: int) -> str:
lines: Liststr = [
"# HELP gw_draining Whether gateway is draining connections (1=draining, 0=active).",
"# TYPE gw_draining gauge",
f"gw_draining {1 if draining else 0}",
"# HELP gw_in_flight_streams Current active streaming requests on this gateway.",
"# TYPE gw_in_flight_streams gauge",
f"gw_in_flight_streams {in_flight}",
"# HELP gw_requests_total Total inference requests handled by gateway.",
"# TYPE gw_requests_total counter",
]
for (model, node, status, canary), val in sorted(self.request_counter.items()):
lines.append(
f'gw_requests_total{{model="{model}",node="{node}",status="{status}",canary="{canary}"}} {val}'
)
lines.append("# HELP gw_kv_evicted_trie_nodes_total Pruned Trie nodes triggered by KV eviction.")
lines.append("# TYPE gw_kv_evicted_trie_nodes_total counter")
for (node_id, action), val in sorted(self.eviction_counter.items()):
lines.append(f'gw_kv_evicted_trie_nodes_total{{node="{node_id}",action="{action}"}} {val}')
lines.append("# HELP gw_prefix_hit_ratio_avg Average prefix block hit ratio.")
lines.append("# TYPE gw_prefix_hit_ratio_avg gauge")
for (model, node), total_hit in sorted(self.prefix_hit_sum.items()):
cnt = max(self.prefix_hit_count(model, node), 1)
lines.append(
f'gw_prefix_hit_ratio_avg{{model="{model}",node="{node}"}} {round(total_hit / cnt, 4)}'
)
lines.append("# HELP gw_stage_duration_seconds Latency of gateway pipeline stages.")
lines.append("# TYPE gw_stage_duration_seconds histogram")
for key, buckets in sorted(self.latency_buckets.items()):
model, stage, node = key
cumulative = 0
for bound, count in sorted(buckets.items(), key=lambda x: x0):
cumulative += int(count)
le_val = "+Inf" if bound == float("inf") else str(bound)
lines.append(
f'gw_stage_duration_seconds_bucket{{model="{model}",stage="{stage}",node="{node}",le="{le_val}"}} {cumulative}'
)
lines.append(
f'gw_stage_duration_seconds_sum{{model="{model}",stage="{stage}",node="{node}"}} {round(self.latency_sumkey, 6)}'
)
lines.append(
f'gw_stage_duration_seconds_count{{model="{model}",stage="{stage}",node="{node}"}} {self.latency_countkey}'
)
return "\n".join(lines) + "\n"
==========================================
2. 前缀树、配置模型与优雅排空控制器
==========================================
@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
@dataclass(frozen=True)
class ModelPoolConfig:
model_name: str
stable_prefill: Dictstr, str
stable_decode: Dictstr, str
canary_model_name: Optionalstr = None
canary_weight: float = 0.0
canary_prefill: Dictstr, str = field(default_factory=dict)
canary_decode: Dictstr, str = field(default_factory=dict)
class DrainController:
"""管理网关排空状态与存量流式请求计数"""
def init(self):
self.draining: bool = False
self.in_flight: int = 0
self._drained_event = asyncio.Event()
self._drained_event.set()
def begin_drain(self) -> None:
self.draining = True
if self.in_flight == 0:
self._drained_event.set()
def enter_request(self) -> bool:
if self.draining:
return False
self.in_flight += 1
self._drained_event.clear()
return True
def exit_request(self) -> None:
self.in_flight = max(0, self.in_flight - 1)
if self.in_flight == 0:
self._drained_event.set()
async def wait_for_drain(self, timeout: float = DRAIN_TIMEOUT_SECONDS) -> bool:
self.begin_drain()
if self.in_flight == 0:
return True
try:
await asyncio.wait_for(self._drained_event.wait(), timeout=timeout)
return True
except asyncio.TimeoutError:
return False
def build_block_hashes(model: str, tokens: Listint, block_size: int = BLOCK_SIZE) -> Liststr:
if not tokens:
return \[\]
hashes: Liststr = \[\]
parent_digest = f"MODEL:{model}"
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
==========================================
3. 支持热更新的综合调度器
==========================================
class GovernedInferenceScheduler:
def init(
self,
initial_configs: Dictstr, ModelPoolConfig,
obs: ObservabilityManager,
drain_ctrl: DrainController,
redis_url: str = "redis://localhost:6379/0",
w_prefix: float = 0.75,
w_load: float = 0.35,
):
self.model_configs: Dictstr, ModelPoolConfig = dict(initial_configs)
self.obs = obs
self.drain_ctrl = drain_ctrl
self.redis_url = redis_url
self.w_prefix = w_prefix
self.w_load = w_load
self.redis: Optionalaioredis.Redis = None
self.tries: Dictstr, PrefixTrie = {}
self.active_prefill: Dictstr, int = {}
self.active_decode: Dictstr, int = {}
self._ensure_nodes_registered(self.model_configs)
self._rr_prefill = 0
self._rr_decode = 0
self._tasks: Listasyncio.Task = \[\]
def _ensure_nodes_registered(self, configs: Dictstr, ModelPoolConfig) -> None:
for cfg in configs.values():
for node_id in (
list(cfg.stable_prefill.keys())
-
list(cfg.stable_decode.keys())
-
list(cfg.canary_prefill.keys())
-
list(cfg.canary_decode.keys())
):
if node_id not in self.tries:
self.triesnode_id = PrefixTrie()
if node_id not in self.active_prefill:
self.active_prefillnode_id = 0
if node_id not in self.active_decode:
self.active_decodenode_id = 0
def apply_hot_config(self, new_configs: Dictstr, ModelPoolConfig) -> int:
"""原子替换模型路由配置快照,并初始化新增节点状态"""
self._ensure_nodes_registered(new_configs)
self.model_configs = dict(new_configs)
return len(self.model_configs)
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 resolve_target_pools(
self, requested_model: str, sticky_key: str
) -> Tuplestr, Dict\[str, str, Dictstr, str, bool]:
cfg = self.model_configs.get(requested_model)
if cfg is None:
if not self.model_configs:
raise HTTPException(status_code=503, detail="No model pool configured")
cfg = next(iter(self.model_configs.values()))
use_canary = False
if cfg.canary_weight > 0.0 and cfg.canary_prefill and cfg.canary_decode:
digest = hashlib.md5(sticky_key.encode("utf-8")).hexdigest()
bucket = int(digest:8, 16) / 0xFFFFFFFF
if bucket < cfg.canary_weight:
use_canary = True
if use_canary:
eff_model = cfg.canary_model_name or cfg.model_name
return eff_model, cfg.canary_prefill, cfg.canary_decode, True
return cfg.model_name, cfg.stable_prefill, cfg.stable_decode, False
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
async def broadcast_eviction(self, node_id: str, evicted_hashes: Liststr) -> int:
trie = self.tries.get(node_id)
removed = trie.evict_blocks(evicted_hashes) if trie else 0
self.obs.observe_eviction(node_id, removed)
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
def select_prefill_node(
self, model: str, tokens: Listint, pool_nodes: Liststr
) -> Tuplestr, float, float:
block_hashes = build_block_hashes(model, tokens, BLOCK_SIZE)
total_blocks = max(len(block_hashes), 1)
now = time.monotonic()
best_node = pool_nodes0
best_score = float("-inf")
best_hit = 0.0
offset = self._rr_prefill % len(pool_nodes)
self._rr_prefill += 1
candidates = pool_nodesoffset: + pool_nodes:offset
for node_id in candidates:
trie = self.tries.get(node_id)
matched = trie.match_prefix_length(block_hashes, now=now) if trie else 0
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, pool_nodes: Liststr) -> Tuplestr, float:
best_node = pool_nodes0
best_load = float("inf")
offset = self._rr_decode % len(pool_nodes)
self._rr_decode += 1
candidates = pool_nodesoffset: + pool_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):
removed = self.triesnode_id.evict_blocks(evicted)
self.obs.observe_eviction(node_id, removed)
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)
==========================================
4. 生命周期、热更新与流式推理端点
==========================================
INITIAL_CONFIGS: Dictstr, ModelPoolConfig = {
"qwen-32b": ModelPoolConfig(
model_name="qwen-32b",
stable_prefill={"p-stable-1": "http://localhost:8001", "p-stable-2": "http://localhost:8002"},
stable_decode={"d-stable-1": "http://localhost:8101", "d-stable-2": "http://localhost:8102"},
canary_model_name="qwen-32b-canary",
canary_weight=0.15,
canary_prefill={"p-canary-1": "http://localhost:8201"},
canary_decode={"d-canary-1": "http://localhost:8301"},
)
}
obs_manager = ObservabilityManager()
drain_controller = DrainController()
scheduler = GovernedInferenceScheduler(
initial_configs=INITIAL_CONFIGS,
obs=obs_manager,
drain_ctrl=drain_controller,
)
http_client: Optionalhttpx.AsyncClient = None
def _install_sigterm_handler() -> None:
try:
loop = asyncio.get_running_loop()
def _on_sigterm():
drain_controller.begin_drain()
loop.add_signal_handler(signal.SIGTERM, _on_sigterm)
except (NotImplementedError, RuntimeError):
Windows 或非主循环环境下安全跳过
pass
@app.on_event("startup")
async def on_startup() -> None:
global http_client
_install_sigterm_handler()
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 drain_controller.wait_for_drain(timeout=DRAIN_TIMEOUT_SECONDS)
await scheduler.close()
if http_client:
await http_client.aclose()
@app.get("/healthz")
async def healthz(response: Response):
if drain_controller.draining:
response.status_code = 503
return {"status": "draining", "in_flight": drain_controller.in_flight}
return {"status": "ok", "in_flight": drain_controller.in_flight}
@app.post("/internal/drain")
async def trigger_drain():
drained_cleanly = await drain_controller.wait_for_drain(timeout=DRAIN_TIMEOUT_SECONDS)
return {
"status": "drained" if drained_cleanly else "timeout",
"remaining_in_flight": drain_controller.in_flight,
}
@app.post("/internal/config/reload")
async def reload_config(request: Request):
"""热更新模型池与灰度权重配置(无需重启进程)"""
try:
raw = await request.json()
except Exception:
raise HTTPException(status_code=400, detail="Invalid JSON body")
models_payload = raw.get("models")
if not isinstance(models_payload, dict) or not models_payload:
raise HTTPException(status_code=400, detail="'models' must be a non-empty object")
updated: Dictstr, ModelPoolConfig = {}
for model_key, item in models_payload.items():
if not isinstance(item, dict):
raise HTTPException(status_code=400, detail=f"Invalid config for model '{model_key}'")
weight = float(item.get("canary_weight", 0.0))
if not (0.0 <= weight <= 1.0):
raise HTTPException(status_code=400, detail="canary_weight must be between 0.0 and 1.0")
stable_prefill = item.get("stable_prefill") or {}
stable_decode = item.get("stable_decode") or {}
if not stable_prefill or not stable_decode:
raise HTTPException(status_code=400, detail="stable_prefill and stable_decode are required")
updatedmodel_key = ModelPoolConfig(
model_name=item.get("model_name") or model_key,
stable_prefill=dict(stable_prefill),
stable_decode=dict(stable_decode),
canary_model_name=item.get("canary_model_name"),
canary_weight=weight,
canary_prefill=dict(item.get("canary_prefill") or {}),
canary_decode=dict(item.get("canary_decode") or {}),
)
count = scheduler.apply_hot_config(updated)
return {"status": "reloaded", "models_count": count}
@app.get("/metrics", response_class=PlainTextResponse)
async def prometheus_metrics() -> str:
return obs_manager.render_prometheus(
draining=drain_controller.draining,
in_flight=drain_controller.in_flight,
)
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 chat_completions(request: Request):
if not drain_controller.enter_request():
raise HTTPException(status_code=503, detail="Gateway is draining connections")
req_start = time.monotonic()
entered_stream = False
try:
try:
body = await request.json()
except Exception:
raise HTTPException(status_code=400, detail="Invalid JSON body")
requested_model = body.get("model")
if not isinstance(requested_model, str) or not requested_model:
raise HTTPException(status_code=400, detail="'model' is required")
messages = body.get("messages", \[\])
if not isinstance(messages, list):
raise HTTPException(status_code=400, detail="'messages' must be a list")
req_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
sticky_key = request.headers.get("X-User-Id") or request.headers.get("X-Session-Id") or req_id
eff_model, prefill_map, decode_map, is_canary = scheduler.resolve_target_pools(
requested_model, sticky_key
)
tokens = extract_prompt_tokens(messages)
prefill_node, prefill_hit, prefill_score = scheduler.select_prefill_node(
eff_model, tokens, list(prefill_map.keys())
)
decode_node, decode_load = scheduler.select_decode_node(list(decode_map.keys()))
prefill_url = f"{prefill_mapprefill_node}/v1/chat/completions"
decode_url = f"{decode_mapdecode_node}/v1/chat/completions"
forward_headers = {
k: v for k, v in request.headers.items()
if k.lower() not in {"host", "content-length"}
}
forward_headers"X-Request-Id" = req_id
forward_headers"X-Effective-Model" = eff_model
forward_headers"X-Canary-Route" = str(is_canary).lower()
forward_headers"X-Prefill-Node" = prefill_node
forward_headers"X-Decode-Node" = decode_node
forward_body = {**body, "model": eff_model}
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_pipeline():
nonlocal entered_stream
entered_stream = True
prefill_released = False
final_status = "200"
try:
assert http_client is not None
with obs_manager.span(
"gateway.prefill_stage",
{"req.id": req_id, "model": eff_model, "node": prefill_node, "canary": is_canary},
):
p_start = time.monotonic()
prefill_payload = {**forward_body, "stream": False, "max_tokens": 1}
async with http_client.stream(
"POST", prefill_url, json=prefill_payload, headers=forward_headers
) as p_resp:
p_resp.raise_for_status()
async for _ in p_resp.aiter_bytes():
pass
obs_manager.observe_duration(
eff_model, "prefill", prefill_node, time.monotonic() - p_start
)
scheduler.active_prefillprefill_node = max(
0, scheduler.active_prefill.get(prefill_node, 1) - 1
)
prefill_released = True
with obs_manager.span(
"gateway.decode_stream",
{"req.id": req_id, "model": eff_model, "node": decode_node, "canary": is_canary},
):
async with http_client.stream(
"POST", decode_url, json=forward_body, headers=forward_headers
) as d_resp:
d_resp.raise_for_status()
async for chunk in d_resp.aiter_bytes():
yield chunk
except httpx.HTTPStatusError as exc:
final_status = str(exc.response.status_code)
raise
except Exception:
final_status = "502"
raise
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
)
obs_manager.observe_duration(
eff_model, "total", decode_node, time.monotonic() - req_start
)
obs_manager.observe_request(
eff_model, decode_node, final_status, is_canary, prefill_hit
)
drain_controller.exit_request()
return StreamingResponse(
stream_pipeline(),
media_type="text/event-stream",
headers={
"X-Request-Id": req_id,
"X-Effective-Model": eff_model,
"X-Gateway-Canary": str(is_canary).lower(),
"X-Gateway-Prefill-Node": prefill_node,
"X-Gateway-Decode-Node": decode_node,
"X-Gateway-Prefix-Hit-Ratio": str(prefill_hit),
"X-Gateway-Prefill-Score": str(prefill_score),
"X-Gateway-Decode-Load": str(decode_load),
},
)
except Exception:
if not entered_stream:
drain_controller.exit_request()
raise
三、 高并发异步压测脚本示例
可以使用下面的独立压测脚本,模拟共享长前缀的并发流式请求、观察响应头中的前缀命中率,并在压测期间验证热更新与排空指标:
import asyncio
import time
import httpx
SHARED_SYSTEM_PROMPT = "你是一名资深分布式系统架构师。" + ("请严格遵循高可用与低延迟设计原则。" * 80)
async def run_single_stream(client: httpx.AsyncClient, gw_url: str, user_idx: int, turn: int):
headers = {
"X-User-Id": f"user-{user_idx % 20}",
"Content-Type": "application/json",
}
payload = {
"model": "qwen-32b",
"stream": True,
"messages": [
{"role": "system", "content": SHARED_SYSTEM_PROMPT},
{"role": "user", "content": f"第 {turn} 轮提问:如何优化多级缓存一致性?用户={user_idx}"},
],
}
t0 = time.perf_counter()
ttft = None
chunks = 0
async with client.stream("POST", f"{gw_url}/v1/chat/completions", json=payload, headers=headers) as resp:
hit_ratio = resp.headers.get("X-Gateway-Prefix-Hit-Ratio", "0")
canary = resp.headers.get("X-Gateway-Canary", "false")
async for chunk in resp.aiter_bytes():
if chunk:
if ttft is None:
ttft = time.perf_counter() - t0
chunks += 1
total = time.perf_counter() - t0
return resp.status_code, ttft, total, chunks, hit_ratio, canary
async def benchmark(gw_url: str = "http://localhost:8000", concurrency: int = 32, total_requests: int = 128):
limits = httpx.Limits(max_connections=concurrency * 2, max_keepalive_connections=concurrency)
async with httpx.AsyncClient(timeout=httpx.Timeout(120.0), limits=limits) as client:
sem = asyncio.Semaphore(concurrency)
results = \[\]
async def _worker(idx: int):
async with sem:
res = await run_single_stream(client, gw_url, user_idx=idx, turn=(idx % 5) + 1)
results.append(res)
start = time.perf_counter()
await asyncio.gather(*_worker(i) for i in range(total_requests))
elapsed = time.perf_counter() - start
ok = r for r in results if r\[0 == 200]
avg_ttft = sum(r1 for r in ok if r1 is not None) / max(len(ok), 1)
avg_total = sum(r2 for r in ok) / max(len(ok), 1)
avg_hit = sum(float(r4) for r in ok) / max(len(ok), 1)
canary_cnt = sum(1 for r in ok if r5 == "true")
print(
f"Completed {len(ok)}/{total_requests} in {elapsed:.2f}s | "
f"RPS={len(ok)/elapsed:.2f} | Avg TTFT={avg_ttft*1000:.1f}ms | "
f"Avg Total={avg_total:.2f}s | Avg PrefixHit={avg_hit:.2%} | Canary={canary_cnt}"
)
if name == "main":
asyncio.run(benchmark())
四、 生产上线检查清单
* 负载均衡器探针联动:将 NLB / K8s readinessProbe 指向 /healthz,并确保 terminationGracePeriodSeconds 大于 DRAIN_TIMEOUT_SECONDS,保证流式请求有充足时间排空。
* 多副本配置一致:在调用 /internal/config/reload 时,建议由控制面通过广播或配置中心统一推送到所有网关 Pod,避免部分实例灰度比例滞后。
* 真实分词器接入:压测与上线前将 extract_prompt_tokens 替换为模型对应的分词器(如 transformers / tiktoken),并结合真实 KV 驱逐事件回调验证前缀命中率提升。