如何为 WebSocket 测试做性能基准?
解读
国内面试官问“如何为 WebSocket 测试做性能基准”,并不是想听“用 JMeter 就行”这种一句话答案,而是想确认候选人能否把“Pytest 体系”与“高并发长连接场景”结合起来,给出可落地、可量化、可融入 CI 的完整方案。核心考察点:
- 是否理解 WebSocket 与 HTTP 在性能指标上的差异(连接数、帧速率、心跳、内存泄漏、重连风暴)。
- 能否用 Pytest 的插件生态把“功能正确性”和“性能基准”写在同一条用例里,做到“一次编写,回归即压测”。
- 是否熟悉国内常用 CI(GitLab-CI、Jenkins、阿里云效)的资源限制与并行策略,保证基准数据可复现、可告警。
- 对结果分析是否专业:P99 延时、CPU 上下文切换、goroutine/线程数、文件句柄、网卡 PPS,能否定位“框架层”还是“业务层”瓶颈。
知识点
- Pytest-asyncio / pytest-trio:把异步协程测试写成普通 test 函数,兼容 assert。
- Pytest-benchmark:提供 BenchmarkFixture,可自动计算均值、标准差、IQR,支持内存统计
--benchmark-autosave。 - Pytest-xdist + pytest-parallel:本地多进程并发,适合 I/O 密集型 WebSocket 连接,避免 GIL。
- Pytest-html / pytest-allure:生成中文可视化报告,方便国内项目组评审。
- WebSocket 客户端选型:websockets(纯 Python,支持压测级并发)、aiohttp(与现有业务代码复用)、websocket-client(同步,不适合高并发)。
- 指标口径:连接建立时延(TCP+TLS+HTTP Upgrade)、帧往返时延(RTT)、每秒上行/下行帧数(fps)、错误率(关闭码 1006/1008/1011)、内存泄漏(RSS 增长斜率)。
- 国内云主机常见限制:单实例 6 万端口、单 ENI 50 万 PPS、ulimit 65535,需要提前调优。
- CI 策略:GitLab-CI 使用 docker:dind 服务,挂载宿主机 /sys/fs/cgroup 做资源隔离;Jenkins 使用 kubernetes 插件,给 Pod 注入 sidecar 采集 cAdvisor 指标。
- 基准版本化:把“性能基线”当作代码,pytest-benchmark 的 JSON 结果存入 LFS,MR 触发
--benchmark-compare=HEAD~1,差异超过 10% 自动驳回。 - 合规:若 WebSocket 传输用户数据,需符合《个人信息保护法》要求,压测环境必须脱敏,日志分级存储。
答案
给出一套可直接落地的 Pytest 方案,分四层:用例层、驱动层、指标层、CI 层。
- 用例层(test_ws_bench.py)
import asyncio, json, os, pytest, websockets
from pytest_benchmark.fixture import BenchmarkFixture
@pytest.mark.asyncio
async def test_ws_performance(benchmark: BenchmarkFixture):
uri = os.getenv("WS_URI", "wss://api.xxx.com/live")
concurrency = int(os.getenv("WS_CONCURRENCY", "500"))
duration = int(os.getenv("WS_DURATION", "30"))
async def one_connection(_id: int):
async with websockets.connect(uri, subprotocols=["json"]) as ws:
await ws.send(json.dumps({"type": "ping", "id": _id}))
await ws.recv() # 等待 pong
await asyncio.sleep(duration)
def run():
loop = asyncio.new_event_loop()
tasks = [one_connection(i) for i in range(concurrency)]
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
loop.close()
benchmark.extra_info["concurrency"] = concurrency
benchmark.extra_info["duration"] = duration
benchmark(run)
- 驱动层 使用 pytest-xdist 做并行采集:
pytest test_ws_bench.py -n auto --benchmark-only --benchmark-autosave
单进程 GIL 瓶颈时,改用“多进程 + 多协程”混合模型:每个 worker 启动 500 协程,worker 数=CPU 核心数。
- 指标层 pytest-benchmark 默认输出均值、P99,但缺少系统指标。编写 conftest.py 钩子:
@pytest.hookimpl(tryfirst=True)
def pytest_benchmark_update_json(config, benchmarks, output_json):
import psutil, time
mem = psutil.virtual_memory()
output_json["system"] = {
"timestamp": time.time(),
"cpu_percent": psutil.cpu_percent(interval=1),
"memory_percent": mem.percent,
"memory_used_gb": mem.used / 1024**3
}
把 output_json 通过阿里云 SLS SDK 直接上传,统一看板展示。
- CI 层(.gitlab-ci.yml 片段)
variables:
WS_URI: "wss://staging.xxx.com/live"
WS_CONCURRENCY: "1000"
WS_DURATION: "60"
performance:
stage: test
image: python:3.11
services:
- docker:dind
before_script:
- pip install pytest pytest-asyncio pytest-benchmark websockets psutil
script:
- pytest test_ws_bench.py --benchmark-json=result.json
artifacts:
reports:
performance: result.json
expire_in: 30 days
only:
- merge_requests
GitLab 13.10+ 原生支持 performance 报告,MR 页面直接展示回归曲线,差异超过阈值自动失败。
- 基线管理 把 result.json 存入仓库的 perf-baseline 分支;CI 自动对比:
pytest --benchmark-compare=perf-baseline/result.json --benchmark-compare-fail=mean:10%
若均值上涨 10% 或 P99 上涨 20%,MR 不可合并,强制要求开发同学出具根因报告。
- 常见坑与调优
- 本地端口耗尽:linux 默认 28232~60999,仅 3 万可用,需
echo 1024 65535 > /proc/sys/net/ipv4/ip_local_port_range。 - TIME_WAIT 堆积:打开
tcp_tw_reuse=1,并让服务端支持 SO_REUSEPORT。 - 证书校验耗时:压测环境可复用自签证书,加
--no-check-certificate选项,但需注释明确“仅限测试”。 - 日志打爆磁盘:websockets 库默认 debug 日志关闭,pytest 加
-o log_cli=false。
通过上述四层,面试官可以看到你不仅会用 Pytest 写用例,还能把“性能基准”做成产品交付流程的一部分,符合国内“质量门禁”的合规要求。
拓展思考
- 如果 WebSocket 服务端是 Go 写的,想验证“单 Pod 10 万连接”是否达标,可以把 pytest-benchmark 结果作为“客户端水位”,再对接 Prometheus 的 pod 指标,用 pytest-prometheus 插件直接查询 container_memory_working_set_bytes,实现“客户端+服务端”联合断言。
- 国内金融场景常用“双活+域名切流”,压测时需模拟 DNS TTL 过期瞬间的重连风暴,可在用例里动态调用
aiodns刷新解析,观察重连耗时是否出现毛刺,从而验证 SLB 的优雅发布策略。 - 当业务帧体大于 8KB,TCP 会出现分包,pytest 用例可故意发送 64KB 单帧,验证服务端是否支持“消息压缩扩展”(permessage-deflate),并对比压缩前后 P99 延时,量化带宽成本。
- 未来演进:把 pytest-benchmark 结果推送到 Grafana 的 PostgreSQL 数据源,配合 Annotation 标记版本发布时间,形成“性能回归长周期看板”,让管理层一眼看出“哪个迭代引入了性能债”,实现真正的“测试左移+右移”一体化。