[Feature] Compress OAuth Codex Backend `/responses` request bodies with zstd level 3
Summary
When Sub2API forwards an HTTP /responses request through an OpenAI OAuth account to the official ChatGPT Codex Backend, compress the final transformed upstream JSON body with zstd level 3 and send:
Content-Encoding: zstd
Content-Type: application/json
The decision must be based on the selected upstream account and final target endpoint, not on the client's sk-* key used to access Sub2API.
Target flow:
client request
-> Sub2API decompresses and parses it
-> audit, model mapping, and field transforms
-> final upstream JSON
-> zstd level 3
-> ChatGPT Codex Backend
Current behavior
Based on Sub2API main snapshot b74024c:
httputil/body.goaccepts and decompresses client request bodies encoded with zstd, gzip, or deflate.- After decompression, the client
Content-Encodingis removed before JSON parsing, audit, and transformation. - Both
buildUpstreamRequestandbuildUpstreamRequestOpenAIPassthroughsend the final JSON upstream as plaintext viabytes.NewReader(body).
Therefore client-side zstd only saves bandwidth from the client to Sub2API, not from Sub2API to the Codex Backend.
The project already depends on github.com/klauspost/compress/zstd; no new compression dependency is required.
Codex reference behavior
In OpenAI Codex snapshot 5825699:
request.rsserializes the complete JSON body, compresses it with zstd level 3, setsContent-Encoding: zstd, and suppliesContent-Type: application/jsonwhen missing.client.rsenables compression only when request compression is enabled, authenticationuses_codex_backend(), and the provider is OpenAI.- The feature is stable and enabled by default.
- Codex includes a specific API-key request must remain uncompressed test.
The feature originated in openai/codex#8767. One log sample from that PR reported:
pre_compression_bytes=28914
post_compression_bytes=11485
compression_duration_ms=0
That single sample is about a 60.3% reduction (2.52:1); it is not a formal benchmark, and 0ms may simply reflect millisecond-level truncation.
Proposed first-phase scope
Include only:
- OpenAI OAuth accounts;
- the official
chatgpt.com/backend-api/codex/.../responsestarget; - HTTP streaming Responses requests;
- both the normal transform path and
openai_passthrough; - WebSocket ingress bridged to the same HTTP Codex Backend, if it reuses the same outbound request builder.
Exclude by default:
- OpenAI API-key accounts;
- custom
base_url; - arbitrary OpenAI-compatible providers;
- WebSocket frames;
- SSE responses;
/responses/compact,input_tokens, and other endpoints not independently verified.
Implementation notes
Compress only the final upstream JSON
Compression must happen after all body-changing work, including:
- prompt audit/content moderation;
- model mapping and OAuth/Codex transforms;
- normalization of
store,stream, and related fields; - namespace, tool, and session field handling;
- rejected-field and
invalid_encrypted_contentrecovery rewrites.
Do not forward the client's original compressed bytes.
Use zstd level 3 explicitly, for example:
zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(3))
Produce the compressed bytes before constructing http.Request, then use bytes.NewReader(compressedBody) so Go can set ContentLength and a replayable GetBody.
Headers and reuse
When compression is selected:
- set
Content-Encoding: zstd; - set
Content-Type: application/json; - ignore the client's original
Content-Encoding; - reuse the compressed bytes for network retries/replays of the same body;
- recompress only when recovery logic changes the final JSON body.
Configuration and rollout
Suggested initial global configuration:
gateway:
openai_request_compression:
enabled: false
fallback_uncompressed: true
Keep the level fixed at 3. An optional account-level override could be:
{
"openai_request_compression": true
}
The first release can default to disabled and be enabled gradually while observing CPU use, compression ratio, and upstream compatibility.
Compatibility fallback
A Sub2API-specific compatibility enhancement may retry once without compression only for:
- HTTP 415;
- a response explicitly reporting unsupported
Content-Encoding: zstd; - a recognizable zstd decode/request-body parse error.
Do not retry every HTTP 400: that could duplicate invalid POSTs and hide genuine field-validation failures.
Optionally cache temporary zstd incompatibility by accountID + endpoint to avoid one failed compressed request per subsequent call.
Observability
Log without request-body content:
- bytes before and after compression;
- compression ratio and duration;
- whether uncompressed fallback occurred;
skip_reasonwhen compression is not enabled.
Acceptance criteria
- [ ] With the switch enabled, an OpenAI OAuth normal-path request to the official HTTP Codex Backend includes
Content-Encoding: zstd. - [ ] The OpenAI OAuth
openai_passthroughpath also supports it. - [ ] Decompressing the outbound body produces exactly the fully transformed final JSON.
- [ ] API-key accounts, custom
base_url, and other providers remain uncompressed. - [ ] Disabling the switch preserves existing behavior.
- [ ] Network retries of an unchanged body reuse the same compressed bytes.
- [ ] Rewritten bodies are recompressed and never reuse stale compressed content.
- [ ] HTTP 415 or an explicit encoding error causes at most one uncompressed retry.
- [ ] Ordinary business-validation HTTP 400 responses do not cause an uncompressed retry.
- [ ] WebSocket frames and SSE response encoding, buffering, and flush behavior are unchanged.
+1 on this proposal.
Two arguments for making it enabled by default for OpenAI OAuth accounts, rather than starting at enabled: false:
1. It matches what the official client actually sends.
The codex CLI compresses these request bodies by default — EnableRequestCompression is on, and responses_request_compression() returns Zstd whenever the auth is ChatGPT and the provider is OpenAI. So a gateway that forwards OAuth traffic to chatgpt.com/backend-api/codex/.../responses with a plaintext body differs from a direct codex CLI connection in a way that is visible on the wire, for no functional benefit. Since this path is by definition OAuth + official endpoint — exactly the conditions under which the official client compresses — staying byte-for-byte closer to upstream client behaviour seems like the safer default, not the riskier one.
2. For a gateway, upload bandwidth is a shared, recurring cost.
The response direction is already compressed through ordinary Accept-Encoding negotiation. That leaves the request direction as the only leg paying full price — and it is the leg that grows with conversation history, since the full context is re-sent every turn. A single CLI user pays this once; a gateway pays it for every user it serves, on its own egress link.
Worth noting that downstream clients cannot work around this themselves: if a client sends a gzip- or zstd-encoded body, the gateway decodes it and forwards plaintext upstream, so the compression is lost precisely on the segment that costs the most.
A conservative shape that still defaults to on:
- default on for OAuth accounts targeting the official Codex backend (the scope already described in this issue)
- keep
fallback_uncompressed: trueso any upstream rejection degrades to plaintext instead of failing the request - leave API-key and custom
base_urlaccounts uncompressed, as proposed
For cross-reference: I filed openai/codex#41662 asking for per-provider request compression on the client side, which would cover the client→gateway hop. The gateway→upstream hop can only be addressed here.
@Wei-Shaw 可否看一下这个问题 Sub2api 后续能否支持请求Oauth上游时 启用Zstd压缩,实现方式可以讨论 这个表现和codex也是一致的,也能节省很多服务器流量
关闭 用插件实现
+1,补充一组生产实测数据,支持推进这个 feature。
环境:sub2api 0.2.19,约 15 个 Codex OAuth 账号,出口走按字节计费的代理,内部约 40 用户。
一周实测:
网关 → chatgpt.com 上行约 55GB,基本全是 /responses 全量上下文重传 单请求上传体 0.3–18.8MB(带图长会话可达 18MB+),单个用户一个会话 115 次 × 18.8MB ≈ 2.1GB 按载荷拆分:纯文本约 5.5 B/token;带图片/附件的请求约占总上行 47% HTTP/2 连接复用后单连接累计可达 1.5GB,代理流量成本非常显性 对方案的看法:压缩必须发生在所有 transform(审计/模型映射/字段归一)之后、而非透传客户端压缩字节——同意;限 OAuth + 官方端点 + zstd-3 对齐官方 CLI 行为——同意;415/编码错误回退重试一次——必须有,否则单账号异常会放大成通道故障。
默认值我倾向 默认开启(官方客户端本来就压缩,默认开启才符合“原生工具无缝使用”的定位)。
关于“用插件实现”:目前没看到实现此功能的社区插件。压缩时机和回退策略深嵌在请求管线里,插件做未必更简单,还是建议主程序落地。如果有 WIP 插件,求个仓库链接。需要数据/测试/环境复现随时 @ 我。