All notes

HTTP Compression Must Preserve Representation Semantics

Coordinate encoding negotiation, cache variants and validators rather than measuring size alone.

English edition, edited for length. Read the complete Chinese original.

The HTML source, the gzipped version, and the Brotli version may represent the same page, but they are not the same number of bytes. After compression, the old Content-Length is still retained, which may cause the client to read incomplete data or encounter errors due to incorrect lengths. Compression optimization must maintain the representation of metadata simultaneously.

This article discusses the use of publicly available HTML, CSS, and JavaScript. Images, videos, and other media that have already been compressed often do not yield the same results; whether or not to compress should be determined based on the specific content type and its intended outcome, rather than applying a single, uniform compression strategy to all content.

Separating Selection and Transmission Optimization

The original HTML represents the content, while the compressed bytes represent a coded representation of that content. The server first verifies the requested resource and its permissions, then selects the encoding accepted by the client, and finally ensures consistency between the content and metadata. Compression algorithms do not change the content type, but rather change the bytes, length, and some validation behaviors. This model explains why compression rate is only one of the results and cannot replace protocol correctness.

Assume the browser accepts Brotli, while older clients only support gzip, and the command-line requires an identity. All three should be able to decode the same content, without being affected by which request was served first due to caching. The client must explicitly specify quality values and disable options, and the presence of an algorithm name in the string does not imply that it is allowed. Mature platforms have already implemented these rules, so any hand-written implementation must handle full decoding and testing.

If the client does not accept any encoding provided by the server, it should be handled according to HTTP semantics, without forcibly sending uninterpretable encodings. The compatibility strategy should clearly state this, and should not silently remove the Content-Encoding header, pretending that the content is plain text. Decoding failures typically have a greater negative impact on the user experience than slightly larger file sizes, so the default fallback should prioritize correct and readable content.

GET /writing/a/
Accept-Encoding: br, gzip

HTTP/1.1 200 OK
Content-Encoding: br
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8

Client declares the accepted encoding, and the server specifies this in the response. Content-Type The description should still refer to the type of media after decoding, and should not become an arbitrary binary type simply due to compression. Transfer-Encoding and Content-Encoding are not at the same level and cannot be used interchangeably.

The following factors need to be considered: quality weighting, identity, and clients that do not support encoding. It is best to use standard negotiation mechanisms provided by the server or edge platform. Making decisions based on the presence of “br” in the string can easily lead to overlooking explicit prohibitions or prioritization rules.

Building Pre-Compressed and Runtime Compressed Solutions: Balancing Different Costs

Pre-compression can be calculated at the time of publication and then selected directly at runtime, making it suitable for resources that remain unchanged over long periods. It requires storing both the original and encoded versions, along with the correct file type and negotiation rules, and ensuring that the cache and resource hashes are consistent. Applications cannot simply upload a single .br file and expect all servers to automatically understand the filename. To determine whether a hosting platform supports pre-compression, you must check its configuration and actual responses.

Runtime compression is suitable for dynamic content, but each calculation increases CPU usage and latency. Cache compression allows for reducing redundant calculations, but still requires correct variant keys. The highest level typically increases computational costs, which may not be worthwhile for short response times. When comparing, it’s important to record compression time, first byte, size, and cache reuse, rather than relying solely on a single compression rate number. Already compressed media and minimal text can use different strategies.

Edge-based automatic compression reduces application code size, but it requires knowing which content types, states, and sizes will be involved, whether to rewrite the ETag, and how the requesting end can obtain the decoded stream. Default platform values may change with product updates, so key rules should be continuously checked against acceptance samples. Do not assume that if an application does not explicitly compress, then the bytes are not compressed on the server, or that if a header exists, the data should be re-compressed.

Compression requires computing resources, and decompression also requires the client to execute. Pre-compressing static resources during build can reduce runtime overhead, but it requires publishing multiple files and proper negotiation. Edge-based automatic compression eliminates the need for application maintenance, but the scope of control and support depends on the product.

A small response might limit the achievable compression gains, and frequently changing data may not be suitable for the highest compression levels. When choosing a compression method, consider factors such as transmission size, first byte time, computational cost, and cache hit rate, rather than just compression ratio. For sensitive dynamic responses, compression may also involve side-channel vulnerabilities, which should be reviewed according to a threat model. Do not directly apply public site policies to secret data.

Test requests with different Accept-Encoding headers, using a tool to verify that the decoded body is consistent and that the original bytes match the Content-Length. Check for duplicate proxies, 304 responses, and Range requests with cached variations. Compression is a means of reducing transmission costs, but protocol correctness must come first, even if it means a smaller file size.

The platform may automatically unzip or recompress files.

The fetch operation, along with communication between the worker and upstream/client, may involve different encoding handling. When reading the response body, it’s important to verify whether the decoded content is being received or the original encoded stream. Similarly, when reconstructing the Response, it’s crucial to understand how the platform handles Content-Encoding.

Don’t re-compress the body after seeing “gzip” in the header, as this will prevent the client from decoding it according to the header’s declaration. Also, don’t read the text and then retain the original compressed header. The specific runtime behavior should be verified against the actual response bytes according to the official documentation, rather than relying on experience from another server.

After reading response.text, adding content and then returning the original Content-Encoding is a typical error because the application now holds a potentially decoded text. Content-Length, strong-encoding tags, and summary headers may also be invalid. The converter should explicitly define the input and output representations, removing any metadata that is no longer valid or recalculating it based on the mature server. Copying all headers from the upstream source at hand can hide this error within a convenient encapsulation.

Transfer-Encoding describes the message transmission framework, not the content compression itself. Modern HTTP versions and platform proxies can handle it, but applications should not manually add chunked encoding for streaming purposes. The framing and content compression (e.g., gzip) are independent issues at the HTTP layer. Range requests rely on the selected byte representation, and after conversion, the original range cannot be used. It’s best to review these related headers as a set of checks.

Error responses and the 304 status code should also be tested. Responses without a body should not include error messages; client reuse after cache validation must be consistent with the encoding. A generic middleware that compresses all responses may disrupt these special states. Prioritize using mature server-side processing, and business code should only define necessary content and caching policies.

Cache keys and entity labels must be used in conjunction.

Different encoding schemes prevent the indiscriminate sharing of the same complete cache object. While standard HTTP caching uses “Vary” headers to handle variations, the actual rules of a CDN need to be verified. The manual Cache API must understand the relationship between keys and stored content to avoid returning Brotli bytes to clients that do not support Brotli.

Strong ETag corresponds to a byte-level representation, and the compressed version may require different tags or platform-specific conversions. For weak tags and conditional requests, compare according to the specified rules. Do not claim that all strongly-tagged versions are the same solely for the purpose of simplifying cache hits.

First, use a Brotli request to populate the cache. Then, use a client that doesn’t support Brotli to make a request. Finally, reverse the process. After decoding, the content is the same, and the original encoding conforms to the capabilities of the requesting client. Testing with a clean cache shows that each client can only prove that the original site negotiated correctly, but cannot prove that the variations are isolated. Check if the “Vary” header is retained along with other variations, and verify that the configuration truly respects this field.

When using the manual Cache API to store a single, uncompressed object, and then encode it in the response layer, the key strategy differs from directly storing compressed bytes. It’s important to clearly define which layer is responsible for representing the selection, to avoid redundant conversions between layers. Using the same strong ETag to describe different encoded bytes should not be assumed to be valid; weak tags also have rules for expressing semantic equivalence. Cache state, object version, and encoding fields should be recorded together to avoid misinterpreting decoding failures as network jitter.

Sensitive Dynamic Content Requires a Separate Threat Model

Certain side-channel attacks targeting compression rely on the attacker controlling the input and the secret appearing together in the response, and observing changes in length. This is not the same scenario as publicly available technical articles or dynamic pages containing authentication secrets. It is not possible to directly apply a publicly available static compression policy to all account responses, nor is it appropriate to broadly claim that disabling compression will fix all leaks. Choosing the appropriate protection based on content, attacker capabilities, and the protocol remains important. Minimizing the secret is still crucial.

When evaluating using fixed, publicly available samples, it’s important to:

  • Save both the original bytes and the decoded results.
  • Compare the media type, encoding, length, and validator against the original content.
  • Control and measure performance based on caching and network conditions.
  • Compare transmission and execution performance.
  • Avoid pre-assuming that every algorithm will always be faster.
  • If the gains are small and maintenance is complex, allow the platform to handle it automatically.
  • Prioritize correct variations and readability over compression rate to avoid turning a single performance optimization into a protocol failure.

Reaching an Agreement Through Three Consumer Assessments

Prepare to handle clients that accept Brotli, clients that only accept gzip, and clients that require uncompressed representations. First, establish the public content, then access it sequentially. Record the actual Content-Encoding, the original byte length, and the decoded summary. Reverse the request order and repeat the process to check if the cache has been corrupted by the first encoding. Mature negotiation implementations still require this end-to-end validation, as proxy configurations and manual caching can bypass its original guarantees.

Furthermore, we include samples with a zero quality value, multiple weights, wildcards, and short positions. The acceptance set, which is determined after parsing, dictates the selection, not a string inclusion algorithm. The server handles the representation acceptable to the client according to the protocol, rather than deleting the encoding header to disguise compressed bytes as plaintext. The expected results come from the specifications and project support sets, not automatically generated from existing code output; otherwise, incorrect judgments will lead to an incorrect answer.

The automatic decompression settings for client tools should be documented. The text saved in the command line may have been decoded, and the resource size displayed by the browser tool may differ from the transmitted size. The length of JavaScript strings is another unit of measurement. The presence of Chinese characters and emoji samples helps distinguish between characters and bytes. Content-Length and strong tag checks only have meaning when the original representation is explicitly known, and cannot be directly interpreted from all online metadata.

What metadata changes are required for a single content rewrite?

The agent reads the upstream text and adds a footer, resulting in a different main content. The old length, byte summary, and strong validator may become invalid, and whether the encoding header is still applicable depends on the semantic information returned at runtime. The conversion module should declare whether the input is a compressed stream or decoded text, and specify the encoding layer for the output, and handle related headers consistently. While copying headers individually may seem convenient, it can easily lead to inconsistencies between the representation and the actual bytes.

If the agent doesn’t need to modify the text, direct streaming forwarding is often simpler, but the platform’s automatic processing still requires verification. A possible path is gzip compression upstream, worker decoding, and edge re-compression, without inferring the final client bytes from a header upstream. The controlled source returns identifiable content, saving necessary diagnostic information at each layer, allowing you to pinpoint where the conversion occurred without logging the actual user content. Actual behavior depends on the current platform documentation and testing, and does not simply copy experiences from other servers.

There is no identical “HEAD” request for 304, and the range response is targeted at the specific bytes indicated in the representation. The universal compressor must recognize these states and append compression data to all responses, regardless of the situation. Error pages also require the correct content type and decodable representation; failure to compress cannot simulate a normal 200 response. Protocol testing covers special states, but the volume experiment only covers normal content, which is far from sufficient.

Pre-release publication: A comprehensive list of considerations

Static assets can be generated during the build process in raw and gzip/Brotli variants, and the manifest records the logical resources and their corresponding summaries. The deployment endpoint needs to support selecting and correctly handling headers; simply uploading files with the “.br” extension is not sufficient. HTML references logical resources, and the server determines the specific representation. If using independent encoded URLs, their identity and linking strategy must be clearly defined. It is not possible to allow certain clients to only access resources that do not support the specified algorithms.

Old pages may still request resources using older logic, and all supported implementations will retain this functionality. Only Brotli is retained because most modern browsers support it, which could cause long-tail gzip clients to fail. When algorithms or levels are upgraded, the validator must correspond to the current representation, and cache clearing should cover any variations. The relationship between the source version and the encoding version, as expressed by the resource name, must be clear, and it should not be claimed that different bytes have the same strong identity.

The pre-compression cost is moved to the build stage but does not disappear. More candidates increase storage and upload times, while higher levels increase build times. A limited set of options is selected based on actual request distribution, content type, and publishing frequency, rather than unconditionally generating all algorithms for complete formatting. For dynamic content, the focus is on CPU usage, first bytes, and concurrency, and the static compression rate results cannot be directly derived from the dynamic interface benefits.

Deciding on a Solution Based on Task Metrics, Not Compression Rate

Compare fixed page content, caching status, and network conditions, focusing on transmission speed, first byte transfer, overall loading time, and computational overhead. A reduction in file size and slower first byte transfer might be a reasonable trade-off, but it may not align with user goals. Observe decompression and subsequent parsing on low-performance clients, and do not rely solely on server output for development machines. Clearly state the measurement methods and supported ranges, and avoid fabricating fixed percentage improvements.

Images and videos may have already been compressed, and further compression offers diminishing returns while increasing workload. The small response times of headers and algorithms also need to be considered, and strategies should be established based on type and size. Sensitive dynamic responses should independently review length-related side channels, and should not treat publicly available articles as a security proof for private pages. Performance policies and information risk are two constraints that cannot be offset by simply saving bytes.

When pre-compressed files are corrupted during construction, reliance solely on file existence should not be the only criterion. Decode representative or all supported variants, verify their consistency with the original resource’s content summary, and explicitly determine whether byte differences are permitted during encoding while requiring equivalent decoding. The valid output of the algorithm can have different sizes, which needs to be distinguished from corruption. The summaries in the list should clearly differentiate between the original content and the encoded representation, avoiding the combination of both into an ambiguous hash.

Failure to compress during dynamic response can be reverted to the correct, unencoded representation based on a predefined strategy, provided that inconsistent headers and partial bytes have not already been transmitted. Once the output has begun, it is not possible to arbitrarily change to another representation and continue the same stream. The recovery boundary depends on the response phase, and testing should also cover both the start of calculation and the two intermediate stop points during transmission to avoid further disruption of the protocol due to error handling.

Failed samples provide a counter-argument for deployment checks

When testing in an isolated environment, we injected plain data with a gzip header, an incorrect length, an outdated strong tag, and an incorrect cache encoding, to confirm that the checks could detect these errors, rather than simply verifying that all valid samples passed. After restoring the correct configuration, we re-decoded and compared the plaintext summaries. Tests that only showed negative results may simply have replicated the assumptions of the implementation, and would not protect against future middleware modifications. The ability to compress must be consistent with consumer capabilities, field semantics, and actual bytes. This is the minimum requirement for deploying a compression solution.

Using Layered Observation to Avoid Misinterpretations Due to Automatic Decoding

Browser development tools may display both the number of bytes transferred and the size of the decoded data, but neither of these values corresponds to the actual length of the string obtained by the code. When comparing compression gains, it is important to record the actual network transmission, and not to treat the length of the JavaScript string as a byte count. Chinese characters and emojis are particularly prone to causing length errors. When using a tool that automatically decompresses, it is essential to specify whether it does so, and to verify both the original response length and the summary of the decoded content separately.

If a worker forwards the compressed body, it should verify whether the code reads, modifies, or rebuilds the response, and whether content encoding is automatically handled at runtime. A proxy chain might first decompress the content for the application to process, then compress it before sending it to the client, with each header having its own meaning. It’s not sufficient to only check the upstream header to assume that the client receives the same encoding. Controlled endpoints provide known bytes, which helps pinpoint which layer is making the change in representation, without exposing internal addresses within the response.

Creating pre-compressed resources can reduce runtime calculations, but version releases must preserve both the original and variant versions. Older HTML may request older JavaScript, and different clients may require different encodings. Removing a specific variant can cause some users to fail. The release list should record the encoding available for each logical resource, and verify that all supported combinations are accessible. Generating variants that are not used by users will increase storage, and should not be done unconditionally for format completeness.

The cache hit rate is also explained in terms of Brotli’s new client performance. While Brotli’s new clients show good performance, this doesn’t necessarily mean that gzip’s long-tail clients also benefit. Splitting the cache across different variants is the correct approach. If the algorithm is upgraded to change the number of compressed bytes, the strong validator must be updated accordingly, and the content hash source must remain consistent with the variant’s identity strategy. The cleanup operation confirms which object is being targeted, and it doesn’t just assume that all encoded copies disappear if the original path is deleted.

When compressing input for consumption, it’s also necessary to budget for the decoded volume. Third-party responses can be very small, but they can expand into extremely large, repetitive text. Even if you limit the size of the encoded file, the parsing stage can still consume a large amount of memory. After receiving the response, clearly define which layer the size limit applies to, and use a mature processing path that can limit the output. A smaller Content-Length does not grant unlimited decoding; the specific automatic decompression behavior still needs to be verified at runtime.

The synthetic tests provide data with both large and small decoding sizes, as well as both normal and truncated files, to check for triggering limits or failure categories. When the limit is reached, reading stops, and the truncated JSON is not processed normally, nor are all errors attributed to network timeouts. The tests do not aim for extreme compression ratios, nor do they use real, untrusted resources. They demonstrate that the transmission budget and content budget are applied separately, preventing the optimization from shifting costs from the network to unlimited memory.

References: Content-Encoding, Cloudflare Compression.