perf(server): gzip large thread snapshots #4788
main fromrefs/pull/4788/head·merged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubThread snapshots still crossed HTTP uncompressed, so large histories remained expensive to load even after activity payload projection.
This adds content-negotiated gzip for JSON responses above 1 KB. On cloned real T3 data, a 6,852,257-byte thread snapshot was delivered in 1,306,499 bytes (80.9% smaller), and decompression reproduced the original payload byte-for-byte. Browser, desktop, and React Native clients use their native HTTP stacks to decode it transparently.
Tests:
- vp test run apps/server/src/http.test.ts apps/server/test/ActivityPayloadProjection.test.ts apps/server/src/server.test.ts --testNamePattern='http compression|projectActivityPayload|negotiates permessage-deflate'
- vp run --filter t3 typecheck
Built with GPT-5.6-sol in T3 Code using the Codex harness.
Note
Medium Risk Global middleware changes how every large JSON response is sent (streaming body, no Content-Length when compressed), which can affect caching and clients that assume fixed-length bodies.
Overview
Adds global HTTP middleware that gzip-compresses eligible application/json responses (≥1 KB, in-memory body, no existing Content-Encoding) when the client’s Accept-Encoding allows gzip, using a streaming CompressionStream('gzip') body and dropping Content-Length.
Eligible responses always get Vary: Accept-Encoding, merged with any existing Vary without changing * or duplicate values. Clients that decline gzip keep the original body; only Vary may be added.
httpCompressionLayer is wired into the composed server stack so all routes get this behavior. Unit tests cover compressHttpResponse and an integration test hits a real route with accept-encoding: gzip.
Note
Add gzip compression middleware for large JSON thread snapshots in the server#
- Adds
compressHttpResponsein http.ts that gzip-compresses JSON responses ≥1024 bytes when the client sendsAccept-Encoding: gzip, using a streamingCompressionStream('gzip')body. - Always sets a
Vary: Accept-Encodingheader on eligible responses, preserving any existingVaryvalue (including*). - Wires in
httpCompressionLayeras a global middleware in server.ts so all routes benefit automatically. - Behavioral Change: compressed responses drop
Content-Lengthand switch to a streaming body; uncompressed responses are unchanged except for the addedVaryheader.
Summary by CodeRabbit#
New Features
- Added automatic gzip compression for eligible large JSON responses when the client supports it.
- Updated compression handling to set the correct negotiation headers (including
Vary: Accept-Encoding) and stream compressed output. - Preserves existing
Varyheaders and avoids recompressing responses already encoded.
Tests
- Added HTTP and router-level coverage for gzip-compressed responses, accurate decompression, and correct behavior when gzip is declined.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
@coderabbitai review
✅ Action performed
Review finished.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Approvability#
Verdict: Approved
Performance optimization adding gzip compression for large JSON responses (>= 1024 bytes). The middleware is self-contained with conservative conditions, proper HTTP header handling, and good test coverage.
You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@apps/server/src/http.ts`: - Around line 78-83: Update the Vary header handling in the variedResponse construction to preserve a wildcard value of "*" unchanged and avoid appending Accept-Encoding when it is already present. Keep appending Accept-Encoding only for non-wildcard values that do not already contain that token. In `@apps/server/src/server.ts`: - Line 376: Add a focused request-level test in the existing HTTP test suite that serves the makeRoutesLayer configuration and sends Accept-Encoding: gzip, then assert the compressible response is gzip-encoded. Ensure the test exercises the global httpCompressionLayer registration through the route-serving path rather than testing compressHttpResponse directly.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
4ccb6b05-3688-49b1-ad4e-4714d096577b📥 Commits
Reviewing files that changed from the base of the PR and between b64ae880e0f88cd35e2f7e1f5fab868546fbe29b and 1aa1d1da15c101c32b76be3c15897acd3f5b9ed1.
📒 Files selected for processing (3)
apps/server/src/http.test.tsapps/server/src/http.tsapps/server/src/server.ts
apps/server/src/http.ts lines 78 to 83OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -44,0 +63,21 @@63+64+export function compressHttpResponse(65+ response: HttpServerResponse.HttpServerResponse,66+ acceptEncoding: string | undefined,67+): HttpServerResponse.HttpServerResponse {68+ const body = response.body;69+ if (70+ body._tag !== "Uint8Array" ||71+ body.contentLength < GZIP_MIN_BYTES ||72+ !body.contentType.startsWith("application/json") ||73+ response.headers["content-encoding"]74+ ) {75+ return response;76+ }77+78+ const vary = response.headers.vary;79+ const variedResponse = HttpServerResponse.setHeader(80+ response,81+ "vary",82+ vary ? `${vary}, Accept-Encoding` : "Accept-Encoding",83+ );🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Preserve a wildcard
Varyvalue.Line 82 turns
Vary: *intoVary: *, Accept-Encoding, which is invalid and can break cache handling. Preserve*unchanged; also avoid appending a duplicateAccept-Encodingtoken.Proposed fix
const vary = response.headers.vary; +const alreadyVariesByEncoding = + vary === "*" || + vary?.split(",").some((value) => value.trim().toLowerCase() === "accept-encoding"); const variedResponse = HttpServerResponse.setHeader( response, "vary", - vary ? `${vary}, Accept-Encoding` : "Accept-Encoding", + alreadyVariesByEncoding ? vary : vary ? `${vary}, Accept-Encoding` : "Accept-Encoding", );📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change78- const vary = response.headers.vary;79- const variedResponse = HttpServerResponse.setHeader(80- response,81- "vary",82- vary ? `${vary}, Accept-Encoding` : "Accept-Encoding",83- );78+ const vary = response.headers.vary;79+ const alreadyVariesByEncoding =80+ vary === "*" ||81+ vary?.split(",").some((value) => value.trim().toLowerCase() === "accept-encoding");82+ const variedResponse = HttpServerResponse.setHeader(83+ response,84+ "vary",85+ alreadyVariesByEncoding ? vary : vary ? `${vary}, Accept-Encoding` : "Accept-Encoding",86+ );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server/src/http.ts` around lines 78 - 83, Update the Vary header handling in the variedResponse construction to preserve a wildcard value of "*" unchanged and avoid appending Accept-Encoding when it is already present. Keep appending Accept-Encoding only for non-wildcard values that do not already contain that token.✅ Confirmed as addressed by @t3dotgg
[gpt-5.6-sol] RESPONDING ON BEHALF OF THEO
Fixed in 3882cb98b. The Vary helper now preserves wildcard and existing Accept-Encoding values case-insensitively, with regression coverage for both cases.
@t3dotgg, thanks for fixing this and adding regression coverage for both wildcard and case-insensitive existingAccept-Encodingcases.
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
@@ -372,3 +373,4 @@372373 Layer.provide(PreviewAutomationBroker.layer),373374 Layer.provide(ServerSelfUpdate.layer),374375 Layer.provide(browserApiCorsLayer),376+ Layer.provide(httpCompressionLayer),📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash set -euo pipefail vp test run apps/server/src/http.test.tsRepository: pingdotgg/t3code
Length of output: 194
🏁 Script executed:
#!/usr/bin/env bash set -euo pipefail echo "Repository files around apps/server/src:" git ls-files apps/server/src | sed -n '1,120p' echo echo "Locate server/http test files:" fd -a 'server\.ts$|http\.test\.(ts|tsx)$' apps/server/src 2>/dev/null || true echo echo "Search compression symbols:" rg -n "compressHttpResponse|httpCompressionLayer|makeRoutesLayer|Accept-Encoding|gzip" apps/server/src apps/server || trueRepository: pingdotgg/t3code
Length of output: 9339
🏁 Script executed:
#!/usr/bin/env bash set -euo pipefail echo "apps/server/src/http.ts relevant section:" sed -n '1,130p' apps/server/src/http.ts echo echo "apps/server/src/server.ts relevant section:" sed -n '330,390p' apps/server/src/server.ts echo echo "apps/server/src/server.test.ts imports and serve/compression related sections:" sed -n '1,90p' apps/server/src/server.test.ts sed -n '520,555p' apps/server/src/server.test.ts echo echo "apps/server/src/http.test.ts full file size/head tail:" wc -l apps/server/src/http.test.ts sed -n '1,90p' apps/server/src/http.test.tsRepository: pingdotgg/t3code
Length of output: 14655
Exercise gzip through
makeRoutesLayer.apps/server/src/http.test.tsonly testscompressHttpResponse; it cannot catch a broken globalLayer.provide(httpCompressionLayer)registration. Add a focused request-level test that servesmakeRoutesLayerand assertsAccept-Encoding: gzipon a compressible response.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server/src/server.ts` at line 376, Add a focused request-level test in the existing HTTP test suite that serves the makeRoutesLayer configuration and sends Accept-Encoding: gzip, then assert the compressible response is gzip-encoded. Ensure the test exercises the global httpCompressionLayer registration through the route-serving path rather than testing compressHttpResponse directly.Source: Coding guidelines
✅ Confirmed as addressed by @t3dotgg
[gpt-5.6-sol] RESPONDING ON BEHALF OF THEO
Added in 3882cb98b. The server router seam now boots the composed routes, requests a large JSON descriptor with gzip accepted, and verifies the encoding, Vary header, and decoded body.
@t3dotgg, thanks — that covers the missing integration seam and verifies the global compression-layer wiring, not just the helper behavior.
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
@coderabbitai review
✅ Action performed
Review finished.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
d4117db2-9300-4d72-9c68-224602a51616📥 Commits
Reviewing files that changed from the base of the PR and between 1aa1d1da15c101c32b76be3c15897acd3f5b9ed1 and b51dd02d4a6e71a2f8b90690f9b3f5676dd28418.
📒 Files selected for processing (4)
apps/server/src/http.test.tsapps/server/src/http.tsapps/server/src/server.test.tsapps/server/src/server.ts🚧 Files skipped from review as they are similar to previous changes (3)
📝 Walkthrough
Walkthrough#
Adds gzip compression for eligible JSON HTTP responses, exposes it as middleware, integrates it into server routes, and tests compressed, uncompressed, and end-to-end response behavior.
Changes#
HTTP compression
apps/server/src/http.tsVary,content-encoding, andcontent-lengthhandling for eligible JSON responses.apps/server/src/server.tshttpCompressionLayerin the composed server routes layer.apps/server/src/http.test.ts,apps/server/src/server.test.tsVarypreservation, decoded payloads, and route-level compression.Estimated code review effort: 3 (Moderate) | ~20 minutes
Suggested reviewers:
juliusmarminge,d3oxySequence Diagram(s)#
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share