JsonMind
API & Contracts16 min readUpdated Nov 17, 2026

HTTP Compression: Accept-Encoding, Brotli, zstd, and Cache Safety

How HTTP content coding works: Accept-Encoding and Content-Encoding, gzip vs Brotli vs zstd, Vary correctness, BREACH, decompression limits, and verification.

JMBy JsonMind EngineeringLast reviewed: Nov 17, 2026Reviewed against primary specifications and linked sources.
Quick answer

HTTP compression is negotiated per response: the client advertises codings in Accept-Encoding, and the server confirms its choice in Content-Encoding. Prefer gzip for compatibility, Brotli for text, and zstd where both ends support it; compress only bodies above roughly 1 KB, send Vary: Accept-Encoding, and keep secrets out of compressed responses to avoid BREACH.

Key takeaways
  • Accept-Encoding is a ranked request for content codings, and Content-Encoding names the coding actually applied; q=0 means unacceptable, and identity is acceptable by default.
  • gzip is the universal baseline, Brotli wins on text at higher CPU cost, zstd favors speed and internal traffic, and deflate is legacy zlib-wrapped DEFLATE.
  • Compress text-like bodies above a measured threshold, never compress JPEG, PNG, MP4, ZIP, or other already-compressed data, and watch CPU on small high-volume responses.
  • Vary: Accept-Encoding plus per-coding ETags keeps shared caches from serving gzip bytes to a client that asked for identity; double compression usually means two layers claimed ownership.
  • Compression plus reflected input plus a secret enables BREACH, and decompression of untrusted input needs decoded-size, ratio, and time limits.

Compression is the cheapest bandwidth optimization in HTTP and one of the easiest to get wrong. A correctly configured server can cut a JSON response by 80-95%, but a missing Vary header, a second compression layer, or an aggressive threshold can turn that win into cache corruption, wasted CPU, or a security incident. HTTP/2 and HTTP/3 did not make the problem obsolete: they compress headers with HPACK or QPACK, but response bodies still rely on content codings.

This guide covers the negotiation, the codecs, where compression belongs in your stack, and the failure modes that show up in production.

How Accept-Encoding and Content-Encoding negotiate a coding

HTTP compression is negotiated per response. The client sends Accept-Encoding, the server selects one or more content codings, and the response declares them in Content-Encoding.

Accept-Encoding: gzip, deflate, br, zstd means the client can decode all four. Quality values rank them: Accept-Encoding: br;q=1.0, gzip;q=0.8, identity;q=0.1 prefers Brotli, accepts gzip, and treats an uncompressed response as a last resort. A q-value of 0 means "not acceptable", not "lowest preference". The * wildcard covers codings that are not listed.

Two special rules matter in practice:

  • identity (no content coding) is acceptable by default, even when it is not listed. It becomes unacceptable only with identity;q=0, or with *;q=0 and no more specific identity entry.
  • If no coding is acceptable, RFC 9110 says the server should return 406 Not Acceptable. Plenty of servers ignore that and send identity bytes anyway; a client that truly cannot handle them fails later.

Accept-Encoding is representation negotiation, not a transfer mechanism. It is unrelated to Transfer-Encoding: chunked, which is hop-by-hop framing. A response can legitimately have Content-Encoding: br and Transfer-Encoding: chunked at the same time; one describes the representation, the other the connection.

Content-Encoding lists the codings in the order they were applied. In normal deployments it appears exactly once. Content-Encoding: gzip, br means the body was gzipped and then Brotli-compressed, which is almost always a bug rather than an optimization.

One more nuance: RFC 9110 treats a request with no Accept-Encoding as accepting any coding, but real servers usually send identity in that case. A proxy or SDK that strips the header can therefore disable compression without any error.

GET /v1/orders?limit=50 HTTP/1.1
Host: api.example.com
Accept-Encoding: br;q=1.0, gzip;q=0.8, zstd;q=0.6, identity;q=0

HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: br
Vary: Accept-Encoding
Content-Length: 1841
ETag: "o7f3-br"
Cache-Control: private, max-age=0

{"orders":[{"id":"ord_8241","status":"shipped","total":12900}, ...]}

The response is 1,841 bytes on the wire. The same JSON without a content coding is 9,470 bytes in this example, and the client knows to decode Brotli only because of Content-Encoding. Vary tells every cache that the selected representation depends on Accept-Encoding.

gzip, deflate, br, and zstd compared

All four are widely deployed, but they solve different problems.

CodingSpecificationBest useMain cost or risk
gzipRFC 1952 over DEFLATEUniversal fallback for text and JSONWeakest ratio of the modern codecs
deflateRFC 1950 zlib over DEFLATELegacy clients onlyHistorical raw-deflate interop bugs
brRFC 7932HTML, CSS, JavaScript, JSON, SVGHigh quality levels are CPU-expensive
zstdRFC 8878Service-to-service and large payloadsNewer browser support; verify the header
identityRFC 9110Already-compressed and tiny bodiesNo bandwidth savings

gzip is the compatibility baseline. It uses a 32 KB window, a CRC32 checksum, and an uncompressed-length trailer, so truncation is detectable. Every browser, proxy, and HTTP library supports it, which is why it remains the safe fallback even when better codecs are available.

deflate has a naming trap. The HTTP coding means a zlib stream (RFC 1950) wrapping DEFLATE data (RFC 1951), not a raw DEFLATE stream. Some early servers sent raw DEFLATE, and some clients accepted it, so interop scars remain. Treat deflate as legacy: accept it if a client insists, but prefer gzip when you control the response.

br is Brotli, standardized in RFC 7932. It adds a built-in dictionary of common web text and supports larger windows than gzip. On HTML and JavaScript it often produces 15-25% fewer bytes than gzip at comparable speed. Browsers generally advertise br only over HTTPS, so plain-HTTP clients fall back to gzip. The catch is quality: Brotli quality 11 is excellent for files built ahead of time and far too slow to run on every dynamic response.

zstd (Zstandard, RFC 8878) is the speed-oriented option. Its default level 3 compresses much faster than Brotli at a ratio similar to gzip, and its high levels approach Brotli for offline work. It is excellent for internal service-to-service traffic, log shipping, and large API payloads. Browser support is newer and less uniform than gzip or Brotli, so only offer it when Accept-Encoding actually contains zstd.

To estimate the payoff for a specific payload before changing server configuration, paste a representative JSON document into the Gzip tool and compare the Base64-encoded output size with the original. It is not a wire-level test, but it quickly shows whether the payload has enough redundancy to be worth compressing.

What compresses well and what does not

Compression works by finding repetition. The more predictable the bytes, the better the result.

Text-like formats compress very well:

  • JSON, especially arrays of objects with repeated keys. A 50 KB API response often drops below 5 KB.
  • HTML, CSS, JavaScript, SVG, XML, CSV, Markdown, and plain logs.
  • Source maps and minified bundles, which still contain repeated identifiers and syntax.

Formats that are already compressed barely benefit:

  • JPEG, PNG, WebP, AVIF, GIF, MP4, WebM, MP3, and most PDFs.
  • ZIP, gzip, Brotli, and zstd archives.
  • Encrypted payloads and random tokens, which have no exploitable structure.
  • Base64-encoded binary data: it is roughly 33% larger than the original and usually incompressible.

Compressing those is not neutral. It spends CPU, adds framing bytes, and can make the response larger. Configure compression by an allowlist of text media types, not by "everything except images", because new binary formats keep appearing.

Small responses deserve their own rule. A gzip stream adds at least 18 bytes of header and trailer around the compressed data, and DEFLATE block headers add more. A 300-byte JSON response can easily grow, and the server still pays the CPU cost on every request. Most stacks default their minimum length somewhere between 20 bytes and 1 KB; set it deliberately, typically 256-1,024 bytes, and measure rather than guess.

Finally, compression ratio is not the only metric. A response that shrinks by 70% but adds 8 ms of p95 latency and saturates a CPU core at peak traffic is a regression for interactive APIs. For static assets, compress once at build time. For dynamic responses, measure CPU per request, not just bytes saved.

Origin, CDN, and reverse-proxy compression

Compression can happen in three places, and the most common production bug is that two of them do it.

At the origin. The application compresses each response. This is the most flexible option because the application knows which endpoints are compressible and which contain secrets. It is also the most expensive: in a single-threaded runtime such as Node.js, Brotli quality 11 on a large JSON response can block the event loop for hundreds of milliseconds. Origins should use a fast setting, or delegate.

At a reverse proxy. nginx, Envoy, Caddy, and HAProxy can compress before the response leaves the host. This centralizes policy and removes CPU work from the application. nginx exposes gzip, gzip_comp_level, gzip_min_length, gzip_types, gzip_vary, and gzip_proxied; its defaults are conservative, and text/html is always included when gzip is on. Brotli and zstd usually require a module or a newer build.

At a CDN. Edge compression is attractive because it scales with the edge fleet, supports Brotli cheaply, and can cache one compressed variant per coding. The tradeoff is that the origin-to-edge hop may stay uncompressed, and cache behavior now depends on Vary and on how the CDN normalizes Accept-Encoding.

Choose one owner per response path. If the CDN compresses, the origin should send identity for cacheable text and let the edge do the work. If the origin compresses, the CDN must pass the body through and must not compress it again. Document the decision; "someone in the middle compresses it" is how double compression starts.

Compression also interacts with caching. Compressing a response after the cache stores it is wasteful; compressing before the cache stores it means the cache holds encoded bytes and must key them correctly. Compress early in the response pipeline, then cache the encoded representation with the right metadata.

Vary: Accept-Encoding and cache correctness

A shared cache stores one response per URL unless told otherwise. If the origin returns Brotli bytes to one client and identity bytes to another, the cache needs to know that the representation depends on the request's Accept-Encoding. That is exactly what Vary: Accept-Encoding declares.

Without it, the failure is intermittent and confusing. A browser that asked for gzip receives a cached Brotli body, or an API client that asked for identity receives gzip bytes and renders them as text. Symptoms include ERR_CONTENT_DECODING_FAILED, "incorrect header check", and truncated JSON.

Send Vary: Accept-Encoding on every response whose body can vary by coding: 200 responses, 304 responses, error bodies, and anything generated dynamically. A 304 must repeat the headers that describe the selected representation, including Vary and Content-Encoding; otherwise a client can revalidate and reuse the wrong cached body.

ETags need the same discipline. A strong ETag identifies exact bytes. "abc123" for the gzip variant and "abc123" for the identity variant is a lie that conditional requests will eventually expose. Either give each coding its own strong ETag, or use a weak ETag and accept weaker byte-range guarantees. Precompressed sidecar files often need a suffix or a content hash in the ETag.

Cache keys are the other half of the problem. Accept-Encoding: gzip, br and Accept-Encoding: br, gzip select the same representation but are different header values. A CDN that keys blindly on the raw header fragments its cache into many near-duplicates. Modern CDNs normalize the header to a small set of variants, or ignore it and handle compression internally. Verify which behavior yours has, because the difference shows up as a low hit ratio, not as an error.

Double compression and broken intermediaries

Double compression is exactly what it sounds like: a body is compressed, then compressed again. Sometimes the second layer is declared (Content-Encoding: gzip, gzip), but usually the header still says gzip once, and the client decodes one layer and hands the application another compressed blob.

Typical causes:

  • The application gzips a response and sets Content-Encoding: gzip; a proxy configured to compress text ignores the existing coding and compresses the bytes again.
  • A precompressed .gz file is served as a static asset without Content-Encoding, so the proxy compresses the already-compressed file.
  • A middleware compresses based on filename or MIME type and does not check the current Content-Encoding.
  • A CDN decompresses an upstream body, recompresses it, and forwards a stale Content-Length.

The result is larger than identity in the worst case, and corrupt in the common case. A useful diagnostic is to decode exactly once and inspect the first bytes: gzip starts with 1f 8b, zstd with 28 b5 2f fd, and a zlib-wrapped deflate stream usually starts with 78. If the decoded output still starts with gzip magic, you have two layers.

Prevention is organizational more than technical: one component owns compression for a given route, proxies must skip bodies whose Content-Encoding is not identity, and precompressed files must be served with the matching header. If you genuinely apply two codings, list both in the correct order, but treat that as an exception that needs a reason.

BREACH and compression side channels with secrets

Compression makes response size depend on content. That is the whole point, and it is also a side channel. BREACH, published in 2013, uses response-length differences to recover secrets from compressed HTTPS responses.

The attack needs four ingredients: the response is compressed, the attacker can make the victim's browser send requests, attacker-controlled text is reflected into the same response as a secret, and the attacker can observe ciphertext lengths. A classic target is an HTML page that contains a CSRF token and echoes a query parameter. If the guess matches the secret, compression produces a shorter response; the attacker measures the length and learns one more byte.

Mitigations, in order of robustness:

  • Do not compress responses that combine secrets with attacker-controlled input. Serve the secret in a separate response or a separate origin.
  • Mask secrets per response with fresh randomness, so the compressed length no longer correlates with guesses. Random prefixes, random chunking, or XOR with a per-request pad all work if the mask is unpredictable.
  • Add random padding to responses that must be compressed and contain secrets. Padding must vary per response; a fixed pad hides nothing useful.
  • Rate-limit and monitor requests that probe the same endpoint with many similar inputs.

Cache-Control: no-store does not mitigate BREACH. Neither does HTTPS by itself; the attack observes the length of the encrypted response. TLS-level compression is disabled in modern stacks, but HTTP content coding is a separate layer and remains under your control.

Do not disable compression everywhere as a reflex. A JSON API that returns account data but never reflects request text has a different risk profile from an HTML page with a CSRF token and a search box. Make the decision per response class, document it, and test the risky ones.

Decompression bombs, size limits, and precompressed assets

Compression changes the relationship between bytes on the wire and bytes in memory. A 1 KB gzip body can expand to gigabytes. Any component that decompresses untrusted input, including an API server that accepts Content-Encoding: gzip request bodies, needs a limit.

Content-Length describes the encoded size, not the decoded size, so it cannot protect you. Enforce at least three bounds:

  • A maximum decoded size, such as 10 MB, checked while streaming rather than after buffering.
  • A maximum expansion ratio, such as 100:1, which catches bombs that stay under the absolute limit.
  • A wall-clock timeout on decoding, so a crafted stream cannot pin a worker.

Node's zlib accepts a maxOutputLength option on its convenience methods, but the stream API ignores it: enforce a decoded-byte counter on the readable side. Python's zlib.decompressobj().decompress(data, max_length) returns at most max_length bytes and leaves the rest in unconsumed_tail, which lets you stop early. A reverse proxy's client_max_body_size limits the encoded request body and is not a substitute for a decoded limit.

Precompressed static assets take the opposite approach: pay the CPU once at build time and serve the result. A build step produces app.js, app.js.br, app.js.gz, and optionally app.js.zst. nginx serves them with brotli_static on and gzip_static on, setting Content-Encoding automatically. The benefits are real: Brotli quality 11 for every static file with zero runtime CPU, and deterministic bytes that cache well.

The risks are operational. Sidecar files go stale when the build pipeline changes. A deploy can delete the original but leave the .gz. A CDN can cache the identity variant and never see the compressed one. Byte-range requests against a precompressed file may return ranges of the compressed stream, which the client cannot use. Hash the filenames, keep the variants in one build artifact, and add a CI check that every compressible asset has the variants you expect.

Brotli quality, zstd use cases, and small-response economics

Brotli's quality parameter runs from 0 to 11. The useful range is narrower than the full scale:

  • 0-1: fastest, useful when CPU is the bottleneck.
  • 4-6: the practical range for dynamic responses. Quality 4 or 5 is often within a few percent of quality 11 on JSON, at a small fraction of the CPU.
  • 9-11: offline compression for static files. Quality 11 can be an order of magnitude slower than quality 5 and is rarely appropriate per request.

Window size matters too. The default lgwin of 22 gives a 4 MB window, enough for most web assets. Larger windows can improve ratio on big files but cost memory on both ends and may exceed what a decoder accepts.

zstd's default level 3 is the speed champion among the three modern codecs. Use it when both ends are yours: service-to-service HTTP, gRPC payloads, log forwarding, and bulk exports. Levels 1-5 suit latency-sensitive paths; levels 19-22 are for files and archives. For browser traffic, check Accept-Encoding and keep gzip or Brotli as the fallback.

Small responses are where compression economics invert. The CPU cost per response is roughly constant, while the byte savings scale with size. At 20,000 requests per second, one millisecond of compression CPU per request is twenty cores. A 400-byte JSON response that saves 150 bytes may still be a net loss once you count framing overhead, CPU, and the extra cache variants.

Set a minimum length and verify it with real traffic. If a small endpoint is hot, consider returning a compact representation, a 204, or a cached response instead of compressing it.

Verification checklist with pass criteria

Start with the wire, not with configuration files. These commands show what a client actually receives:

# 1. Send the same codings a modern browser advertises and inspect the headers.
curl -sS -D - -o /dev/null \
  -H 'Accept-Encoding: gzip, deflate, br, zstd' \
  https://api.example.com/v1/orders?limit=50

# 2. Compare on-the-wire bytes for identity, gzip, and Brotli.
for enc in identity gzip br; do
  printf '%-8s ' "$enc"
  curl -sS -o /dev/null -w '%{size_download} bytes in %{time_total}s\n' \
    -H "Accept-Encoding: $enc" \
    https://api.example.com/v1/orders?limit=50
done

size_download reports bytes transferred. Without --compressed, curl does not decode the body, so the number is the encoded size; that is exactly what you want for the comparison. Use curl --raw ... | xxd | head when you need to confirm the first bytes match the declared coding. Paste a captured response into the HTTP headers tool to normalize field names and catch duplicate or malformed headers before you reason about them.

Pass criteria for a production review:

  • A request with Accept-Encoding: gzip returns Content-Encoding: gzip; a request with identity returns no Content-Encoding; identity;q=0 returns a coded response or 406, never an identity 200.
  • A response never lists more than one coding, and decoding it once produces the expected payload. The first bytes match the declared format.
  • Wire size for representative JSON above 2 KB is at least 60% smaller than identity, and HTML is at least 65% smaller. Below that, check thresholds, codec choice, and whether the proxy is compressing at all.
  • Every response that can vary by coding, including 304 and error responses, carries Vary: Accept-Encoding. ETags differ per coding or are explicitly weak.
  • A second request with a different Accept-Encoding never receives the first variant from cache, even behind a CDN.
  • No Content-Encoding is applied to JPEG, PNG, WebP, AVIF, MP4, ZIP, or other already-compressed types. Responses under 1 KB stay identity unless a measured win justifies them.
  • Request-body decompression enforces a decoded-size limit, an expansion-ratio limit, and a timeout. Oversized input returns 413 or 400, not an out-of-memory crash.
  • No compressed response mixes a secret with attacker-controlled input; masked tokens change length on every request.
  • p95 latency and CPU stay inside the budget at peak traffic, and static assets are precompressed at high quality rather than compressed per request.
  • Content-Length, when present, equals the encoded wire size, and HEAD returns the same representation headers as GET.

The HTTP request workbench is useful for checking response headers and timing from a browser against a test endpoint, but browsers control Accept-Encoding; use curl when you need to force a specific coding.

Compression is a small configuration surface with a large blast radius. Negotiate honestly, compress once, describe the result accurately, and measure the bytes and the CPU. The rest is maintenance.

Frequently asked questions

What is the difference between Accept-Encoding and Content-Encoding?

Accept-Encoding is a request header where the client lists the content codings it can decode, with optional q-values. Content-Encoding is a response header that names the coding the server actually applied. The client advertises capabilities; the server reports the result, and intermediaries must preserve both accurately.

Should I use gzip or Brotli for web responses?

Use gzip as the universal fallback and Brotli for text when clients advertise br over HTTPS. Brotli usually saves another 15-25% on HTML, CSS, and JavaScript, but high quality levels are expensive per request. For dynamic responses, Brotli quality 4-5 is often the practical compromise; reserve quality 11 for precompressed files.

Does compression help small JSON API responses?

Often not. A gzip stream adds at least 18 bytes of framing, and the per-request CPU cost is the same whether the body is 300 bytes or 300 KB. Below roughly 1 KB, measure the wire size and the p95 latency before enabling compression. Highly repetitive JSON just above that threshold can still benefit significantly.

Why is Vary: Accept-Encoding required?

A shared cache stores one response per URL unless the response declares otherwise. Without Vary: Accept-Encoding, a CDN can serve a cached Brotli body to a client that asked for identity, or the reverse, producing decode errors or binary garbage. Send Vary on 200, 304, and error responses whose body depends on the negotiated coding.

Can HTTP compression leak secrets?

Yes. BREACH uses differences in compressed response length to recover a secret when attacker-controlled input is reflected into the same compressed response. Do not compress pages that mix secrets with reflected input, or mask secrets with fresh randomness per response and add random padding. Cache-Control: no-store does not mitigate this attack.

Reviewed against primary specifications and linked sources.

JsonMind guides are written and reviewed by the engineering team. We check each guide against the relevant RFC or vendor documentation, link the primary sources, and update the guide when behavior changes.

Primary sources are linked at the end of each guide.

References

Put this guide into practice

Browse all tools

Open the browser tool. Inputs stay in your browser and are not uploaded to the business server.

Related guides

All guides