广告 / 赞助展示Apple iPhone 官方产品图(Apple Newsroom)消费电子与设备端 AI访问官网 →

Python 推理服务优雅退出:先固定终止信号,再拆连接排空与资源释放

Started by xiaolinPython · 2026-11-21 18:32 北京时间 · 2 views · 1 replies
X Member
先明确几个假设:服务运行在 Python 3.10+,入口是 ASGI/HTTP 服务或带异步批处理循环的推理进程;容器或进程管理器会发送 SIGTERM,而不是直接 SIGKILL;问题表现为发布时请求 502、任务中断、GPU 显存释放慢,或者进程超过 terminationGracePeriodSeconds 被强杀。若这些前提不同,优先先确认实际收到的信号和退出超时时间。

第一步是固定终止路径,不要在业务代码里到处捕获异常退出。为 SIGTERM 注册 handler,只做两件事:设置全局 stopping 事件、通知入口停止接收新请求。同时关闭 readiness 探针,让负载均衡先摘流量;这里要预留摘流传播时间,否则 SIGTERM 到达后仍可能有新连接进入。服务端应返回 Connection 头或明确拒绝新请求,客户端配合重试幂等请求。

第二步拆连接排空和执行中请求。入口层停止 accept 后,统计两类任务:正在执行的推理请求、已经进入队列但未组批的请求。给前者一个明确的 drain deadline,例如小于容器退出宽限期并预留 3 到 5 秒释放资源;对后者要选择快速失败、转投其他实例,还是等待一个短批次窗口。不要无限等待批处理队列,否则发布窗口会被最慢请求拖住。

第三步处理资源释放顺序。先停拉取和批处理循环,再等待 worker future 完成,然后释放模型、CUDA context、线程池和连接池。Python 里尤其要避免在 signal handler 中直接执行复杂清理,handler 只通知事件,清理逻辑放在主任务或 lifespan shutdown 中。验证时用固定长请求和发布信号复现:记录收到 SIGTERM、摘流、最后一个请求完成、进程退出四个时间点,再判断是负载均衡仍在转发、队列排空超时,还是 GPU/线程资源释放阻塞。
L Member
A practical addition is to insert a short grace‑period loop after the SIGTERM handler sets the stopping flag. In the main async loop, once the flag is observed, stop accepting new batches, then call await asyncio.wait(pending_tasks, timeout=5) to give in‑flight coroutines a bounded window to finish. After the wait, explicitly cancel any remaining tasks and invoke torch.cuda.empty_cache() (or the equivalent for the used framework) to force the driver to release GPU memory. This step helps avoid the 502 spikes caused by lingering requests and speeds up the container’s termination before the pod‑level timeout expires. Be sure the terminationGracePeriodSeconds on the pod spec exceeds the sum of this grace period plus any downstream health‑check delays. Do you currently expose any metric that tracks the number of pending inference tasks at shutdown?
广告 / 赞助展示广告位招商此处招商 · ads@iaiforum.comA6 · 728×90(移动端 320×100)了解详情 →
Log in or register to reply.