Repository navigation
Compress static file responses behind an opt-in (Fix #2545) - #2572
Merged
Merged
Conversation
There is no size threshold anywhere in the compression path. encoding_type() gates on the content type and Accept-Encoding only, and apply_ranges() compresses whatever body it is given, so a two-byte text/plain response comes back gzipped at 22 bytes. Say what actually happens and leave the decision to the handler.
apply_ranges() runs the compressor inside the branch it takes when res.body is non-empty. A response served from a file leaves res.body empty and sets content_length_, so it took the other branch, which writes Content-Length and returns; encoding_type() was computed before the split and never consulted on that side. The same bytes handed to set_content() came back gzipped, which left set_mount_point() and Response::set_file_content() as the one path that missed out. Add Server::set_static_file_compression(), off by default so nothing about an existing server changes. When it is on, the file-backed provider is run through the compressor into res.body ahead of the rest of apply_ranges(), so the response is framed the way set_content() already frames one: it keeps its Content-Length, and HEAD still reports the size a GET would return. Ranges are answered from the identity representation, since RFC 9110 applies Range after content coding and slicing a compressed body would mean compressing the whole file first. The ETag carries the coding it belongs to, so a client that cached the compressed form revalidates against its own validator rather than the identity one. Both the ETag and the body take their coding from static_file_encoding(), so the two cannot disagree. Providers registered with set_content_provider() are left alone. zlib buffers until its window fills, so running one through a compressor would hold back writes that a caller expects to reach the peer as they are produced. The compressed bytes stay in memory until the response has been written, so the peak cost scales with requests in flight. set_static_file_compression_max_length() bounds it, defaulting to 4MB.
yhirose
force-pushed
the
fix/2545-compress-static-file-responses
branch
from
August 27, 2026 04:31
b83c976 to
94f50ae
Compare
Compressing a file that already fits in a single 1500-byte MTU does not get it to the client any sooner, and a file of a few bytes comes back larger than it went in once gzip's header and trailer are added. Every other server draws this line: nginx's gzip_min_length, Caddy's minimum_length, IIS's minFileSizeForComp, CloudFront's 1000-byte floor. The note this replaces told callers to decide in the handler. A response served through set_mount_point() has no handler to decide in, so the floor has to live in the server. It defaults to 1400 bytes, the size that fits inside one MTU with room for headers. set_static_file_compression_min_length() moves it, and CPPHTTPLIB_STATIC_FILE_COMPRESSION_MIN_LENGTH sets the default at compile time. The empty-file case keeps its own early-out so that a zero floor still cannot turn an empty body into a 20-byte gzip stream. The two bounds now read as a pair, so the documentation says what each one is for: the lower bound is about what is worth compressing, the upper bound about what one request is allowed to cost. Every file under test/www except 1MB.txt is below the default floor, so the tests that need a small file compressed lower it explicitly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
set_content()returns gzipped bytes, but the same bytes served throughset_mount_point()orResponse::set_file_content()were sent as is. This addsServer::set_static_file_compression(), off by default, to close that gap.Cause
Server::apply_ranges()runs the compressor inside the branch it takes whenres.bodyis non-empty. A response served from a file leavesres.bodyempty and setscontent_length_, so it took the other branch, which writesContent-Lengthand returns.detail::encoding_type()was computed before the split and never consulted on that side.Decisions
Issue #2545 listed four things to settle before changing anything. Here is where each one landed.
Default or opt-in. Opt-in.
set_static_file_compression(false)is the default, so no existing server changes behavior and no existing test needed editing.Range requests. Answered from the identity representation. RFC 9110 applies Range after content coding, so a compressed 206 would mean compressing the whole file and then slicing it.
Cost per request. The file is compressed on every hit, and only when its size is worth it. Two bounds, for two different reasons:
set_static_file_compression_min_length(), 1400 bytes by default. A file that already fits in one 1500-byte MTU does not reach the client any sooner for being smaller, and a file of a few bytes comes back larger than it went in. Every other server draws this line somewhere (nginxgzip_min_length, Caddyminimum_length, IISminFileSizeForComp, CloudFront's 1000-byte floor), and a response served throughset_mount_point()has no handler where a caller could decide for themselves.set_static_file_compression_max_length(), 4MB by default. This one bounds what a single request may cost, and says nothing about how well large files compress.Either takes
0to turn it off, and each has a compile-time default. Caching and pre-compressed sidecar files are bigger features and are left out.Zero-copy. Compressing an mmap'd file gives up the zero-copy path, which is why this is opt-in. Nothing is buffered in identity form though: the mmap-backed provider hands the compressor a pointer straight into the mapping, so peak memory is the compressed size.
Framing
The compressed body goes into
res.body, so the response is framed the wayset_content()already frames one. It keeps itsContent-Length, andHEADstill reports the size aGETwould return.Chunked framing was considered and rejected. It drops
Content-Length, leavesHEADunable to report a size, and needs a second write path alongsidewrite_content().ETag
A compressed response carries
W/"<mtime>-<size>-gzip". Two representations need two validators, otherwise a client that cached the compressed form revalidates against the identity ETag. The coding is decided inServer::static_file_encoding()before the conditional check runs, so the ETag and the body always agree and a 304 still works in both directions.Scope
Providers registered with
set_content_provider(length, ...)are deliberately left alone.gzip_compressor::compress()passesZ_NO_FLUSHuntil the final call, so a provider that writes 100 bytes and then waits produces only the 10-byte gzip header. Running these through a compressor would stall exactly the incremental delivery callers expect.set_chunked_content_provider()remains the way to compress a generated body.Two tests pin this down:
KnownLengthProviderUnaffectedandIncrementalProviderUnaffected. Both fail if the scope is widened to all known-length providers.Testing
New standalone
StaticFileCompressionTestwith its own server, 14 tests: default-off, mount point,set_file_content(), HEAD, Range, non-compressible type, empty file, min length with the floor lowered, max length, per-encoding ETag with 304 in both directions, and the two scope regression tests.Every file under
test/wwwexcept1MB.txtis below the default floor, so the three tests that need a small file compressed lower it explicitly rather than the fixture doing it for all of them.No existing test was modified (
git diff --numstat test/test.ccshows 277 insertions, 0 deletions). Turning compression on for the sharedServerTestfixture would have silently rewritten what nine existing static file tests assert, so these run their own server instead.make test: 879/879 pass (830/830 with-*_Online, as CI runs them)make test_split: pass-fno-exceptions -DCPPHTTPLIB_NO_EXCEPTIONS: compiles cleanPerformance
Measured with
-O2on darwin/arm64, comparing against master in a separate worktree with the same benchmark source.The default path is unchanged.
detail::find_content_type()runs astd::regex_search(~2.1 us/call measured, 200k calls x 9 trials, best-of), and it is kept out of the 304 early-out unless compression is on, which is where it was before. The only measurable delta iscompute_etag()at 73 -> 77 ns/call from its new suffix parameter, which is 0.004% of a ~100 us request. End-to-end over loopback the two are indistinguishable.