TTFT延迟 网关设置了 SSE 响应头但在首个数据帧之前从不 flush
部署来源
本仓库 Release / 官方镜像(自行部署)
您当前的 newapi 版本
v1.0.0-rc.30
提交确认
- [x] 非重复 issue: 我已搜索现有 Issues,确认目前没有类似 issue。
- [x] 提交前必读: 我已完整阅读上方“提交前必读”,并已查看文档 https://docs.newapi.ai/、项目 README 且向 AI 提问,确认这不是使用、配置或接入类问题。
- [x] 受支持版本: 我已提供准确的版本号、commit 或镜像标签(不是
latest或unknown),并确认问题可在本仓库未修改的受支持版本中复现。 - [x] 非第三方服务: 我确认这不是第三方托管站、中转站、API 服务或未经本仓库原版验证的 fork 所独有的问题;第三方实例问题应联系其运营方。
- [x] 问题归属: 我已提供足以区分客户端、new-api 和上游的证据;转发问题已使用等价的脱敏请求对比直连上游与经过 new-api 的结果,确认错误由 new-api 引入或改变,而非仅原样转发上游报错。
- [x] 渠道与协议边界: 我确认问题不是由 Coding Plan、逆向渠道、第三方封装接口、Codex 反代接口,或 Codex API 自身特有行为导致;若问题最初出现于此类接口,我已在本仓库支持的标准 API 协议上复现。
- [x] 维护成本: 我理解项目维护者精力有限,不遵循模板要求的 issue 可能会被无视或直接关闭。
问题描述
流式请求下,网关设置了 SSE 响应头但在首个数据帧之前从不 flush,导致 200 状态码与响应头被推迟到第一次写入数据帧时才随之提交。客户端收到响应头的时刻等于上游第一个可用 chunk 到达的时刻,整个上游 TTFT 都落在客户端的"等 response header"阶段。
helper.SetEventStreamHeaders(relay/helper/common.go:45-59)只调用 c.Writer.Header().Set(...) 写 header map,不产生任何网络写入。Go 的 net/http 在第一次 Write、显式 WriteHeader 或 Flush 之前不会发送响应头。
代码里现有的 5 处 FlushWriter 调用(relay/helper/common.go:73、:84、:94、:107、:122)全部位于数据写入函数内部——ClaudeData、ClaudeChunkData、ResponseChunkData、StringData、PingData——即先写数据再 flush。没有任何一条流式路径在等待上游期间提前提交响应头。
受影响范围覆盖全部流式渠道:
主路径 StreamScannerHandler(relay/helper/stream_scanner.go:138-140,SetEventStreamHeaders 之后直接进入扫描循环)。经由它的调用点:
| 位置 | 覆盖渠道 |
|---|---|
relay/channel/openai/relay-openai.go:147 |
openai 兼容系:openai、deepseek、moonshot、volcengine、ali、siliconflow、minimax、mistral、perplexity、zhipu_4v、baidu_v2、submodel、newapi、advancedcustom、vertex(OpenSource) 等 |
relay/channel/claude/relay-claude.go:203 |
claude |
relay/channel/gemini/relay-gemini.go:153 |
gemini(OpenAI 格式) |
relay/channel/baidu/relay-baidu.go:119 |
baidu |
relay/channel/dify/relay-dify.go:231 |
dify |
relay/channel/xai/text.go:46 |
xai |
relay/channel/openai/relay_responses.go:88、responses_via_chat.go:91、chat_via_responses.go:270 |
responses 格式 |
relay/channel/openai/audio.go:41、relay_image.go:116 |
audio / image 流式 |
自建流式循环(各自实现,同样缺提前 flush):
| 位置 | 形态 |
|---|---|
relay/channel/cohere/relay-cohere.go:113-115 |
c.Stream,gin 在每次 render 之后 才 flush |
relay/channel/zhipu/relay-zhipu.go:188-189 |
同上 |
relay/channel/xunfei/relay-xunfei.go:137-139 |
同上 |
relay/channel/palm/relay-palm.go:89-90 |
同上(该渠道另有整体 buffer 问题) |
relay/channel/cloudflare/relay_cloudflare.go:36-41 |
直接进 for scanner.Scan() 阻塞等上游 |
relay/channel/tencent/relay-tencent.go:98-100 |
同上 |
relay/channel/coze/relay-coze.go:103-111 |
同上 |
relay/channel/gemini/relay-gemini-native.go:82 |
首次 flush 发生在第一个 helper.StringData |
唯一实际不受影响的是 relay/channel/ollama/stream.go:104-121:它在扫描循环前主动写了一个空的 role: assistant 帧,顺带把头部一起提交了。可作为对照实现。
附带影响:X-Accel-Buffering: no 也在这批 header 里(relay/helper/common.go:58),同样被推迟,前置 nginx/CDN 在这段时间内收不到禁用缓冲的指示。
一个容易掩盖该现象的因素:PingIntervalEnabled 默认为 false(setting/operation_setting/general_setting.go:28)。开启时 startPingKeepAlive(relay/channel/api_request.go:520)会在等上游期间写 ping 帧,从而顺带提交头部。也就是说当前"头部及时送达"实际上依赖一个默认关闭的可选功能。
复现步骤
- 配置任意流式渠道(默认的 openai 兼容渠道即可)。
- 确认 ping 保活关闭(
ping_interval_enabled,默认即为false)。开启时 ping 帧会掩盖该现象。 - 用能区分"收到响应头"和"收到首个数据帧"两个时刻的方式发起
stream: true请求,例如curl -N -w '%{time_starttransfer}\n',或抓包观察响应头所在的 TCP 段。 - 对比响应头到达时刻与上游首个 chunk 到达时刻。选首个 token 前停顿明显的模型(推理模型)效果最清楚。
预期结果
网关确认上游已开始流式响应后,应立即 flush 200 与 SSE 头,此后客户端在已建立的流上等待首个 token。响应头到达时刻应与上游首个 chunk 到达时刻解耦,且该行为不依赖 ping 保活是否开启。X-Accel-Buffering: no 随这次 flush 一起送出。
修复应优先落在 StreamScannerHandler(覆盖面最大),并同步处理上表中的自建循环渠道;倾向于收敛成共用入口,避免新增渠道时再次漏掉。
同时,上游在响应头到达前失败时,现有的错误响应与渠道重试语义必须保持不变——flush 点不能提前到 relay/channel/api_request.go:515(relayClient.Do 之前)。那里虽然已经调用了 SetEventStreamHeaders,但在此 flush 会提交 200 状态码,之后就无法把上游失败转成非 200 错误响应,也无法执行渠道重试。正确的 flush 点必须在上游响应头到达并通过校验之后。
相关截图
No response
[Bot Review]
感谢提交!你的 issue 已按照模板提供必要信息,我们会进一步跟进处理。若有其他补充或相关发现,请随时留言更新。
Another reproduction on v1.0.0-rc.51 (the latest release), this time on the native Gemini path, where the keep-alive ping cannot be used as a workaround.
Setup. The client is Antigravity CLI 1.5.17 and 1.5.18 (Google's agy) in gateway mode with the genai wire protocol. It sends POST /v1beta/models/gemini-4-neon:streamGenerateContent?alt=sse to new-api, which uses a Gemini channel (type 24) whose upstream is copilot-api. For long-reasoning turns on large prompts (median 329k prompt tokens in the session), the upstream returns 200 headers within a few seconds but sends its first data: frame more than 60 s later.
What happens. agy waits at most 60 s for response headers. Because new-api only commits headers on the first data frame, agy fails with http2: timeout awaiting response headers, resends the same request 8 more times, then abandons the turn. In one session this happened 5 times, and the session had 57 timed-out requests in total:
- upstream logged
200within 7 s for every attempt of a failed turn; - new-api ended every failed relay with
stream ended: reason=client_gone end_error="context canceled", received=0; - successful turns in the same session already took up to 59.7 s to their first byte.
Why the ping does not help here. GetRequestURL in relay/channel/gemini/adaptor.go sets info.DisablePing = true for RelayModeGemini streams (commit 20c132bf13). DoApiRequest calls it before both ping checks, the request keep-alive in doRequest and the ping in StreamScannerHandler. Upstream SSE comments are also dropped by StreamScannerHandler. So no setting gets bytes to a native Gemini client before the first data frame.
Client compatibility. Against a loopback stub, agy accepted : PING\n\n before and between data events. With pings every 15 s it kept a silent stream open for 200 s and parsed the reply normally. For this client, a ping on native Gemini streams would be safe. Note that the default 60 s interval would still be too late, because the ping ticker restarts when the upstream response arrives.
Would you consider letting native Gemini relays honor PingIntervalEnabled (or a per-channel option) instead of hardcoding DisablePing? I understand the #6982 trade-off that an early ping commits 200 before the first frame. That cost could be accepted per deployment.
A correction to my comment above. I wrote that the upstream returned 200 within 7 s on every attempt of a failed turn. That holds only for the first failed turn. Across all five, the upstream's headers took 4–27 s, so new-api still had no data frame at least 33 s later, when the client gave up.
A further 5 of the 57 timeouts were different: there the upstream (copilot-api, waiting on GitHub Copilot) held its own response headers for 127–251 s. new-api's request keep-alive in doRequest is the only thing that could have kept the client waiting through those. For native Gemini relays it is also turned off by DisablePing.