自建 LLM 网关前面挂 Nginx,SSE 接口在 61 秒左右必断,浏览器 EventSource 收到 504 后自动重连,用户看到回答从头再吐一遍。后端日志显示请求还在跑,模型到 90 秒才生成完。
Nginx error.log 里是 upstream timed out (110: Connection timed out) while reading response header from upstream。注意是 header 不是 body。第一版只关了 proxy_buffering,情况没变,真正卡住的是 proxy_read_timeout 默认 60 秒,它计的是两次读之间没有数据的间隔。模型在思考阶段 70 秒不吐字,这个超时照打。
试过只把 proxy_read_timeout 调到 300 秒,断流没了,但首字节从 0.9 秒涨到 3 秒,因为 buffering 还开着,Nginx 攒够 4KB 才往下发。也试过给 upstream 加 keepalive,跟这个超时无关,白改。
现在四个参数一起动。proxy_buffering off,proxy_cache off,proxy_read_timeout 和 proxy_send_timeout 都设 300 秒,响应头再加 X-Accel-Buffering: no,防止上层 CDN 又缓冲回去。gzip 对 text/event-stream 关掉,压缩会攒块。HTTP 版本用 1.1 走 chunked。
location /v1/chat/stream {
proxy_http_version 1.1;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
add_header X-Accel-Buffering no;
gzip off;
}
验证别只看一次请求。curl -N 挂 10 分钟,让后端每 15 秒发一个心跳注释行,断开次数必须是 0;抓包看首字节,改完 0.8 秒,和改之前持平。还要测上游真挂掉的情况,Nginx 应该在 300 秒后返回 504,不能永远挂着不释放连接。
