当连接池被耗尽时,如何自动重试并降低并发 worker 数?
解读
国内一线互联网公司在跑 Pytest 分布式(pytest-xdist)或并发 IO 测试时,常把数据库、Redis、HTTP 连接池配得很小,用来模拟线上“突发流量打满”场景。
面试官真正想考察的是:
- 你能否把“测试代码”与“重试/限流策略”解耦,不污染业务逻辑;
- 能否用 pytest 的 fixture、hook 与插件生态,把“失败→退避→降并发”做成自动化、可验证、可回滚;
- 是否理解连接池耗尽的本质(文件描述符、TIME_WAIT、池锁竞争),而不仅仅是“睡几秒再试”。
一句话:让测试在资源受限时依旧“自愈”,并且用 pytest 原生机制就能跑通 CI。
知识点
- pytest 失败重试官方插件:pytest-rerunfailures,支持条件重试与延迟。
- pytest-xdist 的“–max-worker-processes”与“–max-worker-restart”参数,以及 worker 异常退出时的 hook:pytest_worker_interrupted。
- fixture 作用域(session/module/class/function)与缓存回退:通过“request.config.workerinput”判断当前是 xdist 的哪个 worker,动态降级。
- tenacity / backoff 库:与 pytest 断言无缝集成,可捕获“PoolError、TooManyConnections”等具体异常。
- pytest 自定义 cmdopt:在 conftest.py 里加“–adaptive-workers”,让运维在流水线里一键调低并发。
- pytest-html / allure 报告:把“重试次数、最终 worker 数”写进测试元数据,方便复盘。
- 资源池耗尽常见信号:mysqlclient.OperationalError 1040、redis.ConnectionError、urllib3.MaxRetryError、asyncio.TimeoutError。
- 国内 CI 常见镜像源与容器限额:GitLab-Runner K8s 默认 CPU 限 2 核、内存 4 Gi,连接池默认 10,需要显式调大 ulimit。
答案
整体思路:用 pytest 插件体系把“检测耗尽→退避→降并发→重试”封装成一条闭环,不改动被测代码。
步骤如下:
- 在 conftest.py 注册自定义命令行参数,方便流水线动态调节
def pytest_addoption(parser):
parser.addoption("--adaptive-workers", action="store_true",
help="连接池耗尽时自动降低并发 worker 数")
- 写一个 session 级 fixture,提前探测连接池上限
@pytest.fixture(scope="session", autouse=True)
def probe_pool_limit(request):
if not request.config.getoption("--adaptive-workers"):
return
# 假设被测服务提供 /health/pool 接口返回最大连接数
max_conn = requests.get(f"{BASE_URL}/health/pool", timeout=2).json()["max"]
# 把上限写入 worker 共享缓存
request.config.cache.set("pool/max", max_conn)
- 利用 pytest-rerunfailures 的“条件重试”钩子,只在连接池异常时触发
def pytest_rerun_condition(err, item, nextitem):
# err 是 ExceptionInfo 对象
if "TooManyConnections" in str(err.value) or "PoolError" in str(err.value):
return True
return False
- 在 tenacity 里封装退避,与 fixture 结合
from tenacity import retry, stop_after_attempt, wait_exponential_jitter
@pytest.fixture
def db_conn():
@retry(stop=stop_after_attempt(3),
wait=wait_exponential_jitter(initial=0.5, max=8),
retry_error_cls=MyPoolExhaustedError)
def _create():
return create_pool(max_overflow=0, pool_size=5)
return _create()
- 当重试依旧失败时,通过 xdist 的 hook 主动下线部分 worker
def pytest_worker_interrupted(config, workerinfo):
if config.getoption("--adaptive-workers"):
current = int(config.getoption("-n")[0]) # 例如 -n 8
new = max(1, current // 2)
# 把新并发数写进环境变量,供下一轮 pytest 命令读取
os.environ["PYTEST_XDIST_WORKERS"] = str(new)
# 同时把事件写进 allure 报告
allure.dynamic.description(f"池耗尽,worker 数由 {current} 降至 {new}")
- 在 CI 里用“失败再调起”策略
# .gitlab-ci.yml
script:
- pytest -n 8 --adaptive-workers --reruns 3 --reruns-delay 2
after_script:
- |
if [ $CI_JOB_STATUS == "failed" ]; then
export NEW_WORKERS=${PYTEST_XDIST_WORKERS:-4}
echo "retry with workers=$NEW_WORKERS"
pytest -n $NEW_WORKERS --adaptive-workers
fi
- 覆盖率与回归
把“重试次数、最终 worker 数”写入 junitxml 的 <properties>,sonar 解析后可直接在质量看板看到“池耗尽频率”趋势;若连续 3 天出现降并发,则触发运维扩容或池配置调优。
通过以上 7 步,测试代码零侵入,pytest 原生插件即可完成“自动重试 + 并发降级”,且所有指标可追踪、可回滚。
拓展思考
-
如果测试跑在本地开发机,没有 xdist,怎么做到“单进程内降并发”?
答:用 pytest-parallel 的 ThreadRunner,在 fixture 里动态改 threadpool 大小;或者把“并发度”抽象成 fixture 参数,通过 pytest-lazy-fixture 按需注入。 -
连接池耗尽往往伴随端口耗尽,如何提前预警?
答:在 session 级 fixture 里用 psutil.net_connections() 统计本地 TIME_WAIT 数量,超过阈值(如 3w)就自动把并发降到 1,并给报告打“环境异常”标签。 -
国内金融公司要求“测试不可重试”,怕掩盖缺陷,怎么办?
答:把重试逻辑拆到“环境预检”阶段,用 pytest 的“–stage=pre”单独跑一条冒烟流水线;正式测试阶段禁止重试,但允许“动态降级并发”,既保证可靠性又不掩盖问题。