Compression: Entropy, Huffman, LZ77, gzip/zlib/deflate, Brotli, zstd, lz4, snappy
"The ratio of the entropy of a source to the maximum value it could have while still restricted to the same symbols will be called its relative entropy. This is the maximum compression possible when we encode into the same alphabet." — Claude E. Shannon, A Mathematical Theory of Communication, Bell System Technical Journal, 1948
Summary: Compression removes predictability from bytes: an entropy coder gives short codes to common symbols, a dictionary coder replaces repeats with back-references, and every real codec (gzip, Brotli, zstd, lz4, snappy) is a mix of the two tuned for a different point on the speed / ratio / memory triangle. Focus: Entropy and why random or encrypted data never shrinks, Huffman and ANS, LZ77 and DEFLATE byte by byte, the raw / zlib / gzip wrappers, Brotli, zstd with dictionaries, lz4 and snappy, measured numbers, and where compression lives in HTTP, databases, Kafka, logs and backups. Learning goal: Pick a codec and level for each place data is stored or sent, read a compressed byte stream's header, wire HTTP compression correctly in Go, Laravel, nginx and Caddy, and avoid the three production traps: compressing secrets next to attacker input, decompression bombs, and burning CPU on bytes that cannot shrink.
This page is the complete reference for lossless data compression as a backend engineer meets it: the information theory that sets the limit (Shannon entropy, redundancy, the pigeonhole argument), the two families of algorithms (entropy coders: run-length, Huffman, arithmetic coding, ANS/FSE; dictionary coders: LZ77, LZ78, LZW), the formats built from them (DEFLATE and its three containers raw / zlib / gzip, zip, Brotli, Zstandard, lz4, snappy, xz/LZMA, bzip2), and the places they run (HTTP Content-Encoding, PostgreSQL TOAST, Parquet, Kafka batches, MongoDB WiredTiger, Cassandra and ScyllaDB SSTables, Redis RDB files, log shipping and backups). Every number in the speed and ratio tables was measured on one machine for this page, and every format is shown as a hex dump. It sits between Bits, Bytes & Text Encoding (what the bytes are), Serialization Formats (how structures become bytes, which decides how compressible they are) and Checksums & Hashing (the CRC-32 and Adler-32 inside gzip and zlib are explained there, not here). Base64 after compression is in Binary-to-Text Encoding; HTTP versions and header compression design are in HTTP/1.1, HTTP/2, HTTP/3; CDN edge compression is in CDNs; a Go middleware chain is in Go middlewares; TOAST storage layout is in Database Internals; columnar encodings are in OLTP vs OLAP & Columnar Storage; and Kafka batching is in Kafka in Depth.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why we compress, and what it costs | Why compression exists |
| Shannon, Huffman, Ziv-Lempel, DEFLATE, Brotli, zstd: who and when | Where it comes from |
| Entropy, redundancy, why random and encrypted data do not shrink | Information theory you actually need |
| Lossless vs lossy (JPEG, MP3, WebP, AVIF) | Lossless vs lossy |
| RLE, Huffman, arithmetic/ANS, LZ77, LZ78/LZW, one block each | The concept catalogue |
| DEFLATE, raw vs zlib vs gzip, zip, Brotli, zstd, lz4, snappy, xz, bzip2 | Formats and codecs |
| Measured ratio and speed on JSON logs, Persian text, a PNG, random bytes | Measured: the speed / ratio / memory triangle |
| Magic numbers, hex dumps, DEFLATE token trace, every knob and error message | Mechanics |
| HTTP compression, BREACH, bombs, small payloads, databases, Kafka, logs, archives | Solving the classic problems |
| Symptoms and fixes | Troubleshooting |
| Which codec where | Choosing a codec and a level |
| Monolith to distributed system | In architecture |
| Reproduce every number on your laptop | Lab |
| Wrong beliefs, a cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The codecs. Ratio and single-thread speed measured on the same 146.6 MB of JSON access logs (Apple M5, CLI tools, best of three; see Measured).
| Codec (level) | Family | Ratio | Compress MB/s | Decompress MB/s | Where you meet it |
|---|---|---|---|---|---|
| lz4 -1 | LZ77, byte-aligned, no entropy stage | 3.25 | 3626 | 3232 | Cassandra/ScyllaDB default, Kafka, PostgreSQL TOAST, RPC |
| snappy (Go, 9.8 MB) | LZ77, byte-aligned | 3.37 | 755 | 3376 | MongoDB WiredTiger default, Parquet default, Kafka |
| zstd -1 | LZ77 + Huffman + FSE (ANS) | 5.66 | 1102 | 2121 | Kafka, backups, Parquet, HTTP zstd |
| zstd -3 (default) | same | 5.33 | 748 | 2047 | the general-purpose default today |
| gzip -6 (default) | DEFLATE = LZ77 + Huffman | 5.54 | 134 | 1619 | HTTP gzip, .gz, .tar.gz, PNG (zlib), zip |
| brotli -q 5 | LZ77 + Huffman + context modelling + static dictionary | 5.75 | 129 | 1124 | HTTP br on the fly |
| brotli -q 11 | same | 7.28 | 1 | 893 | pre-compressed web assets |
| zstd -19 | same as zstd -3 | 6.99 | 4 | 2697 | archives, release artifacts, cold storage |
| xz -6 | LZMA2 (LZ77 + range coder) | 6.65 | 5 | 176 | .tar.xz source releases, Linux packages |
| bzip2 -9 | Burrows-Wheeler + Huffman | 7.66 | 19 | 87 | legacy archives; slow to decompress |
HTTP rules.
| Header | Meaning | Rule |
|---|---|---|
Accept-Encoding: gzip, br, zstd | Client lists codings it can decode (with optional ;q=) | Absent = anything goes; identity;q=0 = must encode |
Content-Encoding: zstd | The representation was encoded; decode before using the media type | One coding per response in practice; never twice |
Vary: Accept-Encoding | The response depends on that request header | Always send it when you negotiate, or caches serve gzip to clients that cannot read it |
Transfer-Encoding: chunked | Message framing (HTTP/1.1 only) | Not compression; Transfer-Encoding: gzip exists in RFC 9112 but browsers do not use it |
The five things to do.
| Situation | Do this |
|---|---|
| API JSON, HTML, JS, CSS, SVG over HTTP | Compress at the proxy (nginx gzip, Caddy encode zstd gzip), level 4-6, min length ~1 KB, Vary: Accept-Encoding |
| Static assets | Pre-compress at build time with brotli -q 11 and zstd -19, serve with gzip_static / brotli_static / Caddy precompressed |
| Logs, backups, Kafka, Parquet | zstd (levels 1-3 for hot paths, 19 for archives); lz4 or snappy when CPU per byte matters more than size |
| Many small messages (< 1 KB) | Batch them, or train a zstd dictionary; per-message gzip saves almost nothing |
| Untrusted compressed input | Cap compressed bytes AND decompressed bytes; never io.ReadAll a decoder |
Why compression exists
Every byte you store is paid for on disk, in backups, in replicas and in cache memory; every byte you send is paid for in bandwidth, in latency on slow links and in egress fees. Most data that applications produce is extremely repetitive: JSON repeats the same keys in every object, logs repeat the same service name and paths on every line, HTML repeats tags. Compression trades CPU time for fewer bytes. The trade is good when the bytes are expensive (WAN, mobile, cloud egress, cold storage) and the data is predictable; it is bad when the data is already compressed (JPEG, MP4, PNG, zip), when the payload is tiny, or when the CPU is the bottleneck.
| Without compression | With compression |
|---|---|
| Zero CPU per byte | CPU on both ends: cheap decode, expensive encode at high levels |
| Bytes on the wire = bytes in memory | 3x-10x fewer bytes for text, JSON, logs; nothing saved for media |
| Random access to any offset | Need block or frame boundaries (or a seek table) to read the middle |
Easy debugging with tcpdump, cat, less | Need zcat, zstdcat, curl --compressed |
| No new security surface | Length leaks (BREACH), decompression bombs, decoder memory |
The analogy we reuse on this page: a court stenographer. A stenographer does two things. First, common words get tiny pen strokes and rare words get long ones: that is an entropy coder (Huffman, arithmetic, ANS), which spends fewer bits on frequent symbols. Second, when a witness repeats a phrase from earlier, the stenographer writes "same as line 12, 11 words" instead of the phrase: that is a dictionary coder (LZ77 and friends). A stenographer who already knows the legal vocabulary before the trial starts is using a preset dictionary (Brotli's static dictionary, zstd trained dictionaries). And a recording of white noise cannot be shortened by any stenographer: that is random or encrypted data.
Three common misunderstandings, up front
- "Higher level always means smaller." On our JSON logs zstd -1 produced a smaller file than zstd -3 (5.66 vs 5.33), and klauspost's "default" lost to "fastest" the same way. Levels are presets of search strategies, not a monotonic dial. Measure on your data.
- "Compress everything; it can only help." Compressing a PNG, a JPEG, an encrypted blob or a 60-byte JSON reply costs CPU and makes the output slightly larger (our 4 MB of random bytes grew by 1,238 bytes under gzip). Compressing an HTTPS response that mixes a secret with attacker-controlled text leaks the secret (BREACH).
- "gzip, zlib and deflate are the same thing." They share one compressed stream format (DEFLATE, RFC 1951) but wrap it differently: raw has no header, zlib adds 2 bytes and an Adler-32, gzip adds 10 bytes and a CRC-32 plus length. Feeding one to the other's reader fails with "invalid header".
Where it comes from
1948, Shannon. Claude Shannon's A Mathematical Theory of Communication defined the entropy H = -Σ p_i log p_i of a source; quantities of that form, he wrote, "play a central role in information theory as measures of information, choice and uncertainty" and showed it is the limit for lossless coding. He also measured redundancy: "The redundancy of ordinary English, not considering statistical structure over greater distances than about eight letters, is roughly 50%."
1952, Huffman. David A. Huffman's A Method for the Construction of Minimum-Redundancy Codes (Proceedings of the IRE, September 1952) gave the optimal prefix code for known symbol frequencies: repeatedly merge the two least frequent symbols. (The copy we fetched is a scan without a text layer, so we cite it without quoting.) Every DEFLATE, Brotli and zstd stream still contains Huffman codes.
1977-1978, Ziv and Lempel. A Universal Algorithm for Sequential Data Compression (IEEE Transactions on Information Theory, May 1977) introduced the sliding-window method now called LZ77; its abstract says the algorithm's compression ratio uniformly approaches "the lower bounds on the compression ratios attainable by block-to-variable codes and variable-to-block codes designed to match a completely specified source." The 1978 follow-up (LZ78) built an explicit phrase dictionary instead of a window. Terry Welch's 1984 variant LZW powered Unix compress and GIF; RFC 9110 still registers the compress coding as "an adaptive Lempel-Ziv-Welch (LZW) coding".
1996, DEFLATE, zlib and gzip as RFCs. RFC 1951 (May 1996, L. Peter Deutsch) specified DEFLATE as "a lossless compressed data format that compresses data using a combination of the LZ77 algorithm and Huffman coding"; RFC 1950 and RFC 1952 specified the zlib and gzip wrappers. These three are why "gzip" is the lowest common denominator of the web, of tar.gz, of PNG and of zip.
2009-2021, ANS, Brotli, Zstandard. Jarek Duda's Asymmetric Numeral Systems (arXiv 0902.0271, 2009) gave an entropy coder with arithmetic coding's precision at Huffman-like speed. Brotli became RFC 7932 in July 2016 with LZ77, Huffman, context modelling and a built-in static dictionary. Zstandard's format was published as RFC 8478 and is now RFC 8878 (February 2021), whose FSE entropy stage "is an entropy codec based on [ANS]". lz4 and Google's snappy took the opposite direction: no entropy stage at all, byte-aligned output, decompression at memory speed.
Today. Browsers advertise gzip, deflate, br, zstd (MDN browser-compat-data: zstd from Chrome 123, Firefox 126, Safari 26.3), and RFC 9842 (Compression Dictionary Transport) adds dcb/dcz: Brotli or zstd compressed against a previously downloaded resource as the dictionary.
Information theory you actually need
Entropy Must-know
In plain words: entropy is the average number of bits you truly need per symbol if you know how often each symbol appears. Common symbols carry little surprise and deserve short codes; rare ones carry a lot.
Common misunderstanding: "Entropy is a property of the file." It is a property of the model you use to predict the file. Counted byte by byte with no context (order-0), our JSON logs have 5.10 bits/byte, which promises only a 1.57:1 ratio; gzip got 5.54:1 because LZ77 exploits repeats that an order-0 model cannot see.
Definition: for symbol probabilities p_i, H = -Σ p_i log2 p_i bits per symbol. A coder that uses exactly the model can approach H, never beat it. The order-0 bound on the compression ratio is 8 / H for byte data.
Order-0 entropy measured with go run ./entropy <file> (snippet below)
1 logs.jsonl 9,766,722 bytes 63 distinct bytes H0 = 5.097 bits/byte -> order-0 bound 1.57:1 gzip -6 got 5.53:1
2 persian.txt 1,465,736 bytes 159 distinct bytes H0 = 4.140 bits/byte -> order-0 bound 1.93:1 gzip -6 got 3.81:1
3 image.png 699,984 bytes 256 distinct bytes H0 = 7.951 bits/byte -> order-0 bound 1.01:1 gzip -6 got 1.01:1
4 random.bin 4,000,000 bytes 256 distinct bytes H0 = 8.000 bits/byte -> order-0 bound 1.00:1 gzip -6 got 0.9997:1Real scenarios: estimating whether a column, a log stream or a message type is worth compressing before you add CPU; explaining why a field full of UUIDs or hashes barely shrinks (hex digits are 4 bits of entropy in an 8-bit byte, so the best you can do is about 2:1, and only with an entropy stage); detecting that an "uncompressed" upload is actually already compressed or encrypted (H0 close to 8).
| Data | Typical order-0 H | What a good codec reaches | Why |
|---|---|---|---|
| JSON / NDJSON logs | 5-5.5 bits/byte | 5-8x | Keys, values and paths repeat: LZ77 wins far beyond order-0 |
| English text | not measured here | depends on length | Shannon estimated "roughly 50%" redundancy from letter statistics alone; phrases repeat on top |
| Persian (UTF-8) text | ~4.1 bits/byte | 3.8-5.5x | Two bytes per letter, first byte nearly constant (0xD8-0xDB) |
| Hex / UUID strings | ~4 bits/byte | ~1.5-2x with Huffman; ~1x with lz4/pglz | Only 16 symbols, but no repeats |
| PNG, JPEG, MP4, zip, gz | ~7.95-8 bits/byte | ~1x | Already compressed |
| Encrypted / random | 8 bits/byte | ≤ 1x | No model predicts it |
Fix / how to use it: measure before choosing. The Go snippet counts bytes and prints H0 and the order-0 bound:
// Command entropy prints the order-0 Shannon entropy of a file and the best
// ratio an order-0 coder (one that ignores context) could reach on it.
package main
import (
"bufio"
"fmt"
"io"
"math"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: entropy <file>")
os.Exit(2)
}
f, err := os.Open(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer f.Close()
var counts [256]uint64
var total uint64
r := bufio.NewReaderSize(f, 1<<20)
buf := make([]byte, 1<<16)
for {
n, err := r.Read(buf)
for _, b := range buf[:n] {
counts[b]++
}
total += uint64(n)
if err == io.EOF {
break
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
if total == 0 {
fmt.Println("empty file")
return
}
// H = -sum(p * log2 p) over the byte values that occur.
h, distinct := 0.0, 0
for _, c := range counts {
if c == 0 {
continue
}
distinct++
p := float64(c) / float64(total)
h -= p * math.Log2(p)
}
fmt.Printf("%d bytes, %d distinct byte values\n", total, distinct)
fmt.Printf("order-0 entropy: %.3f bits/byte\n", h)
if h > 0 {
fmt.Printf("best order-0 ratio: %.2f:1\n", 8/h)
}
}Redundancy and models Important
In plain words: redundancy is the part of the data you could have guessed. A compressor is a predictor plus a coder: the better it predicts the next byte, the fewer bits it spends.
Common misunderstanding: "Compression finds patterns by magic." It finds exactly the patterns its model can express: LZ77 sees repeated strings within its window; Huffman sees skewed symbol frequencies; Brotli adds the previous two bytes as context; bzip2 sorts the data so similar contexts end up together. A pattern outside the model (a repeat 100 MB back for a 32 KiB gzip window) is invisible.
Definition: Shannon: "One minus the relative entropy is the redundancy." Practical codecs combine a model (how probabilities or matches are found) with a coder (how bits are emitted).
Model -> coder in each codec
1 RLE : "same byte again" -> count + byte
2 Huffman : order-0 symbol counts -> whole-bit prefix codes
3 LZ77 : repeats inside a window -> literal / (distance, length) tokens
4 DEFLATE : LZ77 tokens -> two Huffman codes
5 zstd : LZ77 tokens -> Huffman (literals) + FSE/ANS (sequences)
6 Brotli : LZ77 + 2-byte context + 122,784-byte static dictionary -> Huffman
7 bzip2 : Burrows-Wheeler sort + move-to-front -> RLE + Huffman
8 xz/LZMA : LZ77 with large window -> adaptive binary range coderReal scenarios: JSON with stable key order compresses better than JSON with shuffled keys; sorting rows by a low-cardinality column before writing Parquet improves its run-length and dictionary encodings; zstd --long finds repeats 128 MB apart in a database dump that gzip's 32 KiB window misses.
Fix: give the model what it can use: group similar data (one log stream per service, one Kafka topic per event type), keep field order stable, compress large batches instead of single records, and pick a window large enough for the repeat distance.
Why random and encrypted data do not compress Must-know
In plain words: there are more possible 1000-byte files than there are shorter files, so no lossless method can shrink all of them. It can only shrink the predictable ones and must expand the rest a little. Good encryption output looks random by design.
Common misunderstanding: "Encrypt, then compress" is just a different order. It is not: after encryption there is nothing left to compress. Compress first, then encrypt; and know that compress-then-encrypt leaks length (see BREACH).
Definition: the pigeonhole principle: 2^n inputs of n bits cannot map one-to-one onto the 2^n - 1 strings shorter than n bits. Every format also adds framing (an empty input becomes 20 bytes of gzip, 13 of zstd, 15 of lz4, 32 of xz, 1 of Brotli), so incompressible input grows.
4,000,000 random bytes, measured
1 gzip -6 -> 4,001,243 bytes (+1,243: stored blocks + header/trailer)
2 zstd -3 -> 4,000,103 bytes (+103: raw blocks)
3 brotli -q5 -> 4,000,009 bytes
4 lz4 -1 -> 4,000,019 bytes
5 bzip2 -9 -> 4,018,071 bytes (+18,071)Real scenarios: an nginx gzip_types * that compresses JPEGs (CPU for nothing); a backup pipeline that runs gzip on already-encrypted pg_dump output; a service that zstd-compresses AES-GCM ciphertext before putting it on Kafka; "compressing" an .mp4 upload before sending it to S3.
| Input already... | What happens | What to do |
|---|---|---|
| Compressed (PNG, JPEG, WebP, MP4, zip, gz, docx, xlsx) | Ratio ~1.00, CPU wasted | Exclude by content type or magic bytes |
| Encrypted (TLS payload, AES-GCM blob, age/gpg file) | Ratio ≤ 1.00 | Compress before encrypting, or not at all |
| Random IDs, hashes, tokens | Small gain at best | Do not build a design around compressing them |
Fix: decide by content type, not by hope. Both the Go and Laravel middlewares on this page skip image/*, video/* and application/zip, and all good codecs fall back to stored/raw blocks so the damage is bounded.
Lossless vs lossy
Lossless vs lossy compression Must-know
In plain words: lossless compression gives back exactly the same bytes; lossy compression gives back something that looks or sounds close enough, and throws the rest away for good.
Common misunderstanding: "WebP and PNG are both images, so both are lossy." PNG is lossless (it uses zlib/DEFLATE inside: PNG "compression method 0 is deflate compression with a sliding window"); JPEG and MP3 are lossy; WebP and AVIF support both modes.
Definition: lossless: decompress(compress(x)) == x for every x. Lossy: decode(encode(x)) ≈ x under a perceptual model (MDN describes JPEG as "Lossy; based on the discrete cosine transform"; AVIF "encodes AV1 bitstreams" from a video codec).
Never use lossy for data
1 JSON, SQL rows, logs, protobuf, backups, code: lossless only (one changed bit = a different amount, a broken signature)
2 photos, video, audio for humans: lossy is the right choice and saves 10-100x
3 lossless images (PNG, lossless WebP): screenshots, diagrams, UI, anything with text| Format | Lossless? | Inside | Notes |
|---|---|---|---|
| PNG | Yes | Filters + zlib (DEFLATE) | Never gzip it again over HTTP |
| GIF | Yes (8-bit indexed colour) | LZW ("GIF uses the Lempel-Ziv-Welch (LZW) algorithm") | Same LZW family as RFC 9110's compress coding |
| JPEG | No | Discrete cosine transform | "the most widely used lossy compression format for still images" |
| MP3, AAC, Opus (audio) | No | Perceptual audio coding | Same rule: lossy for media, never for data |
| WebP | Both | Lossy and lossless modes | Widely supported replacement for JPEG/PNG |
| AVIF | Both | AV1 bitstreams in a HEIF container | MDN: lossy AVIF "around 50% smaller than JPEG" |
Fix: store and ship media in a modern lossy or lossless image/video format chosen by the media pipeline; exclude those content types from HTTP and storage compression; keep every byte of data lossless.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, the precise definition, a step-by-step trace, real scenarios, which products use it, and code. The two families are entropy coders (spend fewer bits on frequent symbols) and dictionary coders (replace repeats with references); every production codec chains one of each.
Run-length encoding (RLE) Good to know
In plain words: write "this byte, 500 times" instead of the byte 500 times.
Common misunderstanding: "RLE is obsolete." It is everywhere in a specialised form: Parquet and ORC use RLE / bit-packing for repeated column values, bzip2 uses RLE around its Burrows-Wheeler stage, and LZ77 expresses a run as a match whose distance is smaller than its length.
Definition: a run of n copies of symbol s becomes the pair (n, s); non-repeating data needs an escape or literal-run marker so it does not double in size.
RLE of a sorted status column (Parquet-style)
1 input : paid paid paid paid paid shipped shipped cancelled
2 output: (5, paid) (2, shipped) (1, cancelled)
LZ77 doing RLE: "aaaaaaaaaaaaaaaaaaaa" (20 bytes)
3 literal 'a'
4 match distance=1 length=19 -> copies the byte it is writing, 19 timesReal scenarios: bitmap images with flat colours (BMP RLE, early fax), sorted columns in Parquet, status or country columns in a column store, sparse arrays, the zero pages in a VM image.
| Where | How runs are encoded |
|---|---|
| Parquet / ORC | RLE + bit-packing hybrid for levels and dictionary indices |
| DEFLATE, zstd, lz4, snappy | Overlapping match (distance 1 = repeat the last byte) |
| bzip2 | RLE before and after the Burrows-Wheeler transform |
| PNG | Filters turn smooth gradients into runs of small numbers, then DEFLATE |
Fix / how to use it: you rarely write RLE yourself; you enable it by sorting and clustering data so equal values sit next to each other. Our LZ77 tokenizer shows the overlapping-match form: go run ./lz77 'aaaaaaaaaaaaaaaaaaaa' prints literal 'a' then match distance=1 length=19.
Huffman coding Must-know
In plain words: count how often each symbol appears, then give the most frequent ones the shortest bit strings, so that no code is the beginning of another (a prefix code) and the decoder never needs separators.
Common misunderstanding: "Huffman is optimal, so nothing beats it." It is the optimal whole-bit prefix code. When a symbol has probability 0.9 it ideally costs 0.15 bits, but Huffman must spend at least 1 bit. Arithmetic coding and ANS remove that rounding loss, which is why zstd uses FSE for its sequence codes.
Definition: Huffman (1952): put every symbol in a priority queue by frequency; repeatedly remove the two least frequent nodes and insert a parent whose weight is their sum; label left edges 0 and right edges 1; a symbol's code is the path from the root. DEFLATE transmits canonical Huffman codes: only the code length per symbol, from which both sides rebuild the same codes.
go run ./huffman abracadabra (real output)
1 merge c(1) + d(1) -> 2
2 merge b(2) + r(2) -> 4
3 merge cd(2) + br(4) -> 6
4 merge a(5) + cdbr(6) -> 11
5 'a' freq=5 code=0 'b' freq=2 code=110 'c' freq=1 code=100
6 'd' freq=1 code=101 'r' freq=2 code=111
7 huffman: 23 bits (2.091 bits/symbol)
8 entropy bound: 22.44 bits (2.040 bits/symbol)
9 8-bit ASCII: 88 bitsThe average code length (2.091 bits) is above the entropy (2.040 bits) and below the entropy + 1 bound, exactly as theory says.
Real scenarios: the second stage of every DEFLATE stream (gzip, PNG, zip), Brotli's prefix codes, zstd's literals, JPEG's final stage, HPACK's static Huffman table for HTTP/2 header strings (RFC 7541), and flate.HuffmanOnly in Go for data that was already LZ-compressed by snappy or lz4.
| Product | Huffman variant |
|---|---|
| DEFLATE (gzip, zlib, zip, PNG) | Canonical, max 15-bit codes; fixed tables (BTYPE 01) or per-block dynamic tables (BTYPE 10) |
| Brotli | Canonical prefix codes per block type and context |
| zstd | Huffman for literals (max 11 bits); FSE for literal lengths, match lengths, offsets |
| HTTP/2 HPACK, HTTP/3 QPACK | One static Huffman table from the RFC, no per-message tables |
| JPEG baseline | Huffman tables in the file header |
Fix / how to use it: you never hand-write Huffman for production, but you should be able to explain the trade it makes. The snippet builds the tree and prints codes for any string:
// Command huffman builds a Huffman code for a string and prints the tree's
// codes, the total bit count and the entropy lower bound.
package main
import (
"container/heap"
"fmt"
"math"
"os"
"sort"
)
type node struct {
freq int
sym byte
leaf bool
order int // tie-breaker so the output is deterministic
left, right *node
}
type queue []*node
func (q queue) Len() int { return len(q) }
func (q queue) Less(i, j int) bool {
if q[i].freq != q[j].freq {
return q[i].freq < q[j].freq
}
return q[i].order < q[j].order
}
func (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
func (q *queue) Push(x any) { *q = append(*q, x.(*node)) }
func (q *queue) Pop() any {
old := *q
n := old[len(old)-1]
*q = old[:len(old)-1]
return n
}
func main() {
text := "abracadabra"
if len(os.Args) > 1 {
text = os.Args[1]
}
freq := map[byte]int{}
for i := 0; i < len(text); i++ {
freq[text[i]]++
}
syms := make([]byte, 0, len(freq))
for s := range freq {
syms = append(syms, s)
}
sort.Slice(syms, func(i, j int) bool { return syms[i] < syms[j] })
q := &queue{}
order := 0
for _, s := range syms {
heap.Push(q, &node{freq: freq[s], sym: s, leaf: true, order: order})
order++
}
// Repeatedly merge the two least frequent nodes (Huffman 1952).
for q.Len() > 1 {
a := heap.Pop(q).(*node)
b := heap.Pop(q).(*node)
fmt.Printf("merge %s(%d) + %s(%d) -> %d\n", label(a), a.freq, label(b), b.freq, a.freq+b.freq)
heap.Push(q, &node{freq: a.freq + b.freq, left: a, right: b, order: order})
order++
}
root := heap.Pop(q).(*node)
codes := map[byte]string{}
var walk func(n *node, prefix string)
walk = func(n *node, prefix string) {
if n.leaf {
if prefix == "" {
prefix = "0" // a one-symbol alphabet still needs one bit
}
codes[n.sym] = prefix
return
}
walk(n.left, prefix+"0")
walk(n.right, prefix+"1")
}
walk(root, "")
bits, h := 0, 0.0
for _, s := range syms {
p := float64(freq[s]) / float64(len(text))
h -= p * math.Log2(p)
bits += freq[s] * len(codes[s])
fmt.Printf("%q freq=%d code=%s\n", s, freq[s], codes[s])
}
fmt.Printf("huffman: %d bits (%.3f bits/symbol)\n", bits, float64(bits)/float64(len(text)))
fmt.Printf("entropy bound: %.2f bits (%.3f bits/symbol)\n", h*float64(len(text)), h)
fmt.Printf("8-bit ASCII: %d bits\n", 8*len(text))
}
func label(n *node) string {
if n.leaf {
return string(n.sym)
}
var s string
var collect func(*node)
collect = func(m *node) {
if m.leaf {
s += string(m.sym)
return
}
collect(m.left)
collect(m.right)
}
collect(n)
return s
}Arithmetic coding, ANS and FSE Important
In plain words: instead of giving each symbol a whole number of bits, an arithmetic coder turns the whole message into one very precise number, so a symbol with probability 0.9 really costs about 0.15 bits. ANS (asymmetric numeral systems) gets the same precision with a single integer state and table lookups, which makes it as fast as Huffman.
Common misunderstanding: "ANS is a compression format." It is an entropy-coding technique; Zstandard's FSE (Finite State Entropy) is a table-based ANS variant (tANS). Duda's paper presents it as an alternative to both Huffman and arithmetic/range coding.
Definition: arithmetic / range coding narrows an interval by each symbol's probability and emits bits as the interval's leading digits become fixed. Duda's ANS keeps one natural-number state x and maps (x, symbol) to a new state so that log2(x) grows by about -log2 p(symbol); Duda's later paper (arXiv 1311.2540) describes the benefit in its abstract: "using single natural number as the state, instead of two to represent a range". RFC 8878: "FSE, short for Finite State Entropy, is an entropy codec based on [ANS]. ... all FSE bitstreams are read from end to beginning."
Cost of one symbol with p = 0.9 (ideal = -log2 0.9 = 0.152 bits)
1 Huffman : 1 bit minimum per symbol -> 6.6x the ideal
2 Arithmetic / range : ~0.152 bits, more CPU per symbol (xz/LZMA)
3 tANS / FSE : ~0.152 bits, table lookups, Huffman-like speed (zstd)
Encoding order: FSE encodes backwards so the decoder reads forwards
4 encoder: symbols n..1 -> state updates -> bits written
5 decoder: reads bits from the end of the stream -> symbols 1..nReal scenarios: zstd beating gzip on ratio at much higher speed (part of the reason is FSE for sequence codes, part is the larger window and better match finder); xz/LZMA's slow but strong range coder.
| Coder | Used by | Speed | Precision |
|---|---|---|---|
| Huffman | DEFLATE, Brotli, zstd literals, JPEG, HPACK | Very fast | Whole bits per symbol |
| Adaptive binary range coder | xz / LZMA / LZMA2, 7z | Slow (decompress ~176 MB/s here) | Fractional bits, adaptive |
| tANS / FSE | zstd sequences (and literal-length, match-length, offset codes) | Fast | Fractional bits |
Fix / how to use it: choose zstd when you want this precision without paying xz's decompression cost; nothing to configure, FSE is always on in zstd (klauspost's WithNoEntropyCompression(true) only skips entropy coding of literals; its docs say "Usually the slight speed improvement is not worth enabling this").
LZ77: the sliding window Must-know
In plain words: keep the last N bytes you already wrote (the window). At each position, look back for the longest earlier copy of what comes next; if you find one, write "go back distance, copy length" instead of the bytes; otherwise write the byte itself as a literal.
Common misunderstanding: "The dictionary is stored in the file." In LZ77 the dictionary is the recently decoded output itself; the decoder rebuilds it as it goes, so nothing extra is stored. The cost is that a repeat further back than the window (32 KiB in DEFLATE) is invisible.
Definition: Ziv and Lempel (1977): a stream of tokens, each a literal or a (distance, length) back-reference into a sliding window of previous output. DEFLATE limits distance to 1-32,768 and length to 3-258; Brotli allows windows from 1 KiB - 16 B to 16 MiB - 16 B; zstd allows windows from 1 KB up to "(1<<41) + 7*(1<<38) bytes, which is 3.75 TB", with RFC 8878 recommending decoders support 8 MB. A match may overlap the cursor (distance smaller than length), which is how runs are encoded.
go run ./lz77 'abracadabra abracadabra' (real output)
1 0 literal 'a'
2 1 literal 'b'
3 2 literal 'r'
4 3 literal 'a'
5 4 literal 'c'
6 5 literal 'a'
7 6 literal 'd'
8 7 match distance=7 length=4 "abra"
9 11 literal ' '
10 12 match distance=12 length=11 "abracadabra"
11 23 bytes -> 8 literals + 2 matchesReal scenarios: every JSON array of objects (the second object's keys are matches into the first), access logs (the same path and user agent within the window), HTML templates, source code. It is also why compressing one small JSON message gains little: there is no earlier output to point into (see dictionaries).
| Codec | Window (max distance) | Min match | Token encoding |
|---|---|---|---|
| DEFLATE (gzip, zlib, zip) | 32 KiB | 3 | Huffman codes for literal/length and distance |
| Brotli | 1 KiB - 16 B to 16 MiB - 16 B | 2 (RFC 7932: minimum copy length two) | Huffman, plus references into the 122,784-byte static dictionary |
| zstd | 1 KB to 3.75 TB in the format; 8 MB recommended; --long = 128 MiB | 3 | Literals (Huffman) + sequences (FSE) |
| lz4 | 65,535 bytes (max offset) | 4 | Byte-aligned tokens, no entropy stage |
| snappy | ~32 KiB in practice (the compressor works in 32 kB blocks) | 4 | Byte-aligned tags, no entropy stage |
| LZMA / xz | dictionary up to 1.5 GiB (preset -6 = 8 MiB) | not covered by the .xz container spec | Range-coded with context models |
Fix / how to use it: the teaching tokenizer below is a brute-force LZ77 with DEFLATE's limits; real encoders use hash chains or binary trees and "lazy matching" (check whether starting one byte later gives a longer match). The compression level mostly controls how hard that search tries.
// Command lz77 is a teaching tokenizer: it scans the input once and emits
// literals and (distance, length) matches from a sliding window, the way
// LZ77 (Ziv and Lempel, 1977) and DEFLATE's match finder think about data.
// Real encoders use hash chains instead of this brute-force search.
package main
import (
"fmt"
"os"
)
const (
windowSize = 32 * 1024 // DEFLATE's window
minMatch = 3 // DEFLATE's shortest match
maxMatch = 258 // DEFLATE's longest match
)
func main() {
in := []byte("abracadabra abracadabra")
if len(os.Args) > 1 {
in = []byte(os.Args[1])
}
literals, matches, i := 0, 0, 0
for i < len(in) {
bestLen, bestDist := 0, 0
start := max(0, i-windowSize)
for j := start; j < i; j++ {
n := 0
// Matches may overlap the cursor: that is how runs are encoded.
for n < maxMatch && i+n < len(in) && in[j+n] == in[i+n] {
n++
}
if n > bestLen {
bestLen, bestDist = n, i-j
}
}
if bestLen >= minMatch {
fmt.Printf("%3d match distance=%d length=%d %q\n", i, bestDist, bestLen, in[i:i+bestLen])
i += bestLen
matches++
continue
}
fmt.Printf("%3d literal %q\n", i, in[i])
i++
literals++
}
fmt.Printf("%d bytes -> %d literals + %d matches\n", len(in), literals, matches)
}LZ78 and LZW Good to know
In plain words: instead of pointing back into raw output, LZ78 builds an explicit numbered phrase table as it goes ("phrase 17 plus the letter e") and LZW sends only phrase numbers, adding "previous phrase + next byte" to the table after each one.
Common misunderstanding: "LZW is what gzip uses." gzip is LZ77 (DEFLATE). LZW is Unix compress (.Z files), GIF and TIFF's LZW option; RFC 9110 keeps it as the compress content coding, which no browser sends.
Definition: LZ78 (Ziv and Lempel, 1978) emits (phrase index, next symbol); LZW (Welch, 1984) initialises the table with all single bytes and emits only indices, growing the code width as the table fills, and resetting it when full.
LZW on "TOBEORNOTTOBE" (table starts with all 256 single bytes)
1 emit T -> add 256 = "TO"
2 emit O -> add 257 = "OB"
3 emit B -> add 258 = "BE"
4 emit E -> add 259 = "EO"
5 emit O -> add 260 = "OR"
6 emit R -> add 261 = "RN"
7 emit N -> add 262 = "NO"
8 emit O -> add 263 = "OT"
9 emit T -> add 264 = "TT"
10 emit 256 ("TO") -> add 265 = "TOB"
11 emit 258 ("BE") -> endReal scenarios: reading legacy .Z archives and GIF images; understanding why GIF's LZW "was covered by patents until the early 2000s" (MDN); interview questions.
| Format | Algorithm |
|---|---|
Unix compress, .Z, HTTP compress coding | LZW |
GIF, TIFF (LZW option), PDF LZWDecode | LZW |
| gzip, zip, PNG, zlib | LZ77 (DEFLATE) |
Fix: for new systems, never choose LZW; decode it only for compatibility (Go has compress/lzw).
Formats and codecs
DEFLATE: LZ77 + Huffman Must-know
In plain words: DEFLATE first turns the input into literals and back-references (LZ77), then writes those tokens with Huffman codes, in blocks that each choose "stored", "fixed codes" or "custom codes".
Common misunderstanding: "Level 9 is a different format from level 1." Every level produces standard DEFLATE that any inflater reads; the level only changes how hard the encoder searches for matches. Likewise Go's compress/flate, zlib, zlib-ng and libdeflate produce different bytes for the same input, all valid.
Definition (RFC 1951): a sequence of blocks, each starting with BFINAL (1 bit: last block) and BTYPE (2 bits: 00 stored, 01 fixed Huffman, 10 dynamic Huffman, 11 reserved/error). Literal/length symbols 0-285 share one alphabet (0-255 literals, 256 end-of-block, 257-285 length codes plus extra bits for lengths 3-258); distances use a second alphabet of 30 codes plus extra bits for 1-32,768. Stored blocks carry up to 65,535 raw bytes with LEN and its one's complement NLEN.
Decoding zlib's 11-byte DEFLATE of "hello hello hello hello\n" (scripted trace, real bytes cb 48 cd c9 c9 57 c8 40 27 b9 00)
1 BFINAL=1 BTYPE=01 (fixed Huffman)
2 literal 'h' literal 'e' literal 'l' literal 'l' literal 'o' literal ' ' literal 'h'
3 match length=16 distance=6 (length code 267, distance code 4) <- overlaps itself: copies "ello hello hello"
4 literal '\n'
5 end-of-block (256)
Go's compress/flate on the same 24 bytes chose differently (real output, 31 bytes):
6 00 18 00 e7 ff -> BFINAL=0 BTYPE=00 stored, LEN=0x0018 (24), NLEN=0xffe7
7 68 65 6c ... 0a -> the 24 bytes verbatim
8 03 00 -> BFINAL=1 BTYPE=01, immediately end-of-blockReal scenarios: HTTP gzip and deflate, .gz, .tar.gz, .zip/.jar/.docx/.apk, PNG, PDF FlateDecode, WebSocket permessage-deflate, Kafka's gzip codec, Parquet GZIP, and the zip-based document formats (docx, xlsx, jar, apk).
| Implementation | Notes |
|---|---|
| zlib (C) | Reference implementation; levels 0-9, memLevel 1-9, windowBits 8-15 (+16 gzip, +32 auto-detect on inflate) |
| zlib-ng | zlib-compatible fork with SIMD, meant to "co-exist as a drop-in replacement" |
| libdeflate | "fast, whole-buffer" API, no streaming; levels up to 12 |
Go compress/flate | Pure Go; BestSpeed=1 ... BestCompression=9, HuffmanOnly=-2, DefaultCompression=-1 |
| klauspost/compress/flate | Drop-in faster Go implementation; gzip and zlib packages on top |
| pigz | "A parallel implementation of gzip" for multi-core machines; output is normal gzip |
Fix / how to use it: in Go, compress/flate gives raw DEFLATE; in PHP, gzdeflate() / zlib_encode($s, ZLIB_ENCODING_RAW). You almost never want raw DEFLATE on its own; use a container with a checksum (next block).
Containers: raw DEFLATE vs zlib vs gzip, zip and tar.gz Must-know
In plain words: the same compressed bytes can be shipped "naked" (raw DEFLATE), in a small envelope with a checksum (zlib), or in a bigger envelope with a checksum, the original length, an optional file name and timestamp (gzip). Zip is an archive: many files, each compressed separately, plus a directory at the end.
Common misunderstanding: "HTTP Content-Encoding: deflate means raw DEFLATE." RFC 9110: “The "deflate" coding is a "zlib" data format [RFC1950] containing a "deflate" compressed data stream”, followed by a boxed note that some non-conformant implementations send the deflate data without the zlib wrapper. That ambiguity is why everyone uses gzip instead.
Definition:
| Container | Header | Trailer | Checksum | Spec | Magic bytes |
|---|---|---|---|---|---|
| raw DEFLATE | none | none | none | RFC 1951 | none |
| zlib | 2 bytes: CMF (method 8, window), FLG (check bits, FDICT, level hint) | Adler-32, big-endian | Adler-32 of uncompressed data | RFC 1950 | 78 01 / 78 5e / 78 9c / 78 da |
| gzip | 10 bytes: ID1 ID2 CM FLG MTIME(4) XFL OS, plus optional FEXTRA / FNAME / FCOMMENT / FHCRC | CRC-32 then ISIZE (length mod 2^32), little-endian | CRC-32 of uncompressed data | RFC 1952 | 1f 8b 08 ("ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213)") |
| zip | Per-entry local header + central directory at the end | Data descriptor | CRC-32 per entry | PKWARE APPNOTE | 50 4b 03 04 ("PK") |
The same 11-byte DEFLATE stream in three containers (Python zlib / PHP / Apple gzip, real bytes)
1 raw : cb48cdc9c957c84027b900
2 zlib : 789c | cb48cdc9c957c84027b900 | 70be08bb -> Adler-32 = 0x70be08bb (big-endian)
3 gzip : 1f8b 08 00 00000000 00 03 | cb48cdc9c957c84027b900 | 0088590b 18000000
ID CM FLG MTIME XFL OS CRC-32 0x0b598800 (LE) ISIZE 24 (LE)
Feeding the wrong reader (Go, real output)
4 zlib.NewReader(gzip bytes) -> zlib: invalid header
5 gzip.NewReader(zlib bytes) -> gzip: invalid headerReal scenarios: a client sending Content-Encoding: deflate with raw bytes and your zlib decoder failing; a .gz produced by pigz or by concatenating two .gz files (gzip allows multiple members; Go's gzip.Reader reads them all by default, Multistream(false) stops after one); tar.gz vs zip (tar.gz compresses the whole archive as one stream, so cross-file repeats help but you cannot extract one file without decompressing everything before it; zip compresses each entry separately, so random access is cheap and the ratio is worse); reproducible builds breaking because gzip stored the file's MTIME (use gzip -n).
| Need | Choose | Why |
|---|---|---|
| HTTP body | gzip (or br, zstd) | Unambiguous; every client decodes it |
| File on disk, log rotation | .gz or .zst | Checksum + length, streamable, zcat/zstdcat |
| Many files, users pick one | zip | Central directory, per-file random access |
| Many files, one-shot transfer, best ratio | tar + zstd/xz/gzip | Cross-file matches; tar --zstd, tar -J, tar -z |
| Embedding in your own framed protocol | raw DEFLATE or zstd frame | Your protocol already frames and checksums |
Fix / how to use it: Go has one package per container (compress/flate, compress/zlib, compress/gzip, archive/zip, archive/tar); PHP has one function per container (gzdeflate, gzcompress, gzencode) plus zlib_encode() with ZLIB_ENCODING_RAW / ZLIB_ENCODING_DEFLATE / ZLIB_ENCODING_GZIP, and zlib_decode() which detects the wrapper.
// Command containers compresses one payload as raw DEFLATE, zlib and gzip
// and prints each as a hex dump, so the wrappers around the same DEFLATE
// stream are visible byte by byte.
package main
import (
"bytes"
"compress/flate"
"compress/gzip"
"compress/zlib"
"encoding/hex"
"fmt"
"hash/adler32"
"hash/crc32"
"log"
"time"
)
func main() {
payload := []byte("hello hello hello hello\n")
var raw bytes.Buffer
fw, err := flate.NewWriter(&raw, 6)
if err != nil {
log.Fatal(err)
}
fw.Write(payload)
fw.Close()
var z bytes.Buffer
zw, err := zlib.NewWriterLevel(&z, 6)
if err != nil {
log.Fatal(err)
}
zw.Write(payload)
zw.Close()
var g bytes.Buffer
gw, err := gzip.NewWriterLevel(&g, 6)
if err != nil {
log.Fatal(err)
}
// Header fields are optional metadata; a zero ModTime is written as 0.
gw.Header.Name = "hello.txt"
gw.Header.ModTime = time.Unix(0, 0)
gw.Write(payload)
gw.Close()
fmt.Printf("payload %d bytes, crc32=%08x adler32=%08x\n",
len(payload), crc32.ChecksumIEEE(payload), adler32.Checksum(payload))
for _, c := range []struct {
name string
b []byte
}{{"raw deflate (RFC 1951)", raw.Bytes()}, {"zlib (RFC 1950)", z.Bytes()}, {"gzip (RFC 1952)", g.Bytes()}} {
fmt.Printf("\n== %s: %d bytes\n%s", c.name, len(c.b), hex.Dump(c.b))
}
// Reading back: each reader only accepts its own wrapper.
if _, err := zlib.NewReader(bytes.NewReader(g.Bytes())); err != nil {
fmt.Println("\nzlib reader on gzip bytes:", err)
}
if _, err := gzip.NewReader(bytes.NewReader(z.Bytes())); err != nil {
fmt.Println("gzip reader on zlib bytes:", err)
}
}<?php
// Plain PHP (ext-zlib is compiled into the official php images).
// The same DEFLATE stream in three wrappers, and how to read each back.
$payload = "hello hello hello hello\n";
$raw = gzdeflate($payload, 6); // RFC 1951, no header (= zlib_encode(..., ZLIB_ENCODING_RAW))
$zlib = gzcompress($payload, 6); // RFC 1950: 2-byte header + Adler-32 (= ZLIB_ENCODING_DEFLATE)
$gzip = gzencode($payload, 6); // RFC 1952: 10-byte header + CRC32 + size (= ZLIB_ENCODING_GZIP)
foreach (['raw deflate' => $raw, 'zlib' => $zlib, 'gzip' => $gzip] as $name => $bytes) {
printf("%-11s %2d bytes %s\n", $name, strlen($bytes), bin2hex($bytes));
}
// zlib_decode() auto-detects the wrapper; the specific functions do not.
var_dump(zlib_decode($gzip) === $payload); // true
var_dump(gzinflate($raw) === $payload); // true
var_dump(gzuncompress($zlib) === $payload); // true
var_dump(@gzuncompress($gzip)); // false: wrong wrapper
// Always cap the output when the input is untrusted (decompression bombs).
$bomb = gzencode(str_repeat("\0", 50_000_000), 9);
printf("bomb: %d bytes on the wire\n", strlen($bomb));
var_dump(@gzdecode($bomb, 1_000_000)); // false: "insufficient memory"The PHP script's real output in php:8.5-cli-alpine is byte-identical to the Python/Apple gzip line above (gzencode → 1f8b0800000000000003cb48...0088590b18000000), because both use zlib with the same defaults.
Brotli Important
In plain words: Brotli is DEFLATE's idea upgraded for the web: bigger window, smarter context modelling, and a built-in dictionary of common words and HTML/CSS/JS fragments, so even a small page starts with useful "history".
Common misunderstanding: "Brotli is always better than gzip." At quality 11 it is much smaller (7.28 vs 5.54 on our logs) but compresses at about 1 MB/s, which is fine for build-time assets and terrible for dynamic API responses. At on-the-fly qualities (4-6) it is roughly gzip -9 ratio at gzip -6 speed. Its decompression (893-1124 MB/s here) is slower than zstd's.
Definition (RFC 7932): a sequence of meta-blocks, each "compressed using a combination of the LZ77 algorithm ... and Huffman coding", where "a string reference may instead refer to a static dictionary entry"; the static dictionary is 122,784 bytes; window sizes range "from 1 KiB - 16 B to 16 MiB - 16 B". Quality 0-11, window lgwin 10-24. Brotli has no magic number (a 1-byte empty stream is valid), which is why it is not used for files on disk.
HTTP negotiation for br (request -> response)
1 browser -> GET /app.js Accept-Encoding: gzip, deflate, br, zstd
2 nginx -> looks for app.js.br on disk (brotli_static on) -> found
3 nginx -> 200 Content-Encoding: br Vary: Accept-Encoding (no CPU spent)
4 curl -> GET /app.js (no Accept-Encoding) -> identity bytesReal scenarios: pre-compressed SPA bundles (app.js.br built by the CI), CDN edge compression, Content-Encoding: br for HTML on the fly at quality 4-5.
| Product | Brotli support |
|---|---|
| Browsers | Chrome 50, Firefox 44, Safari 11, Edge 15 (MDN browser-compat-data) |
| nginx | Not built in; ngx_brotli module: brotli, brotli_static, brotli_comp_level (default 6), brotli_window (default 512k), brotli_min_length (default 20) |
| Caddy | Serves pre-compressed .br via file_server precompressed; encode compresses on the fly with zstd and gzip |
| Go | github.com/andybalholm/brotli (pure Go): NewWriterLevel, NewReader, HTTPCompressor |
| PHP | Not in the official image (function_exists('brotli_compress') is false); PECL ext-brotli |
| Laravel | No built-in response compression; leave it to the web server or CDN |
Fix / how to use it: build time: brotli -q 11 -k dist/*.js; serve with brotli_static on; (nginx + ngx_brotli). On the fly: brotli on; brotli_comp_level 4;. In Go: brotli.NewWriterLevel(w, 5). See the nginx config.
Zstandard (zstd) Must-know
In plain words: zstd is a modern LZ77 compressor with a fast match finder, a large window, Huffman for literals and ANS (FSE) for the rest. One codec covers "faster than gzip -1 and smaller than gzip -6" (level 1-3) up to "close to xz" (level 19-22), and it always decompresses fast.
Common misunderstanding: "Higher zstd levels make decompression slower." Decompression speed is nearly flat across levels (2,047-2,697 MB/s here for -1/-3/-19); what grows is compression time and, for --ultra and --long, the window memory the decoder must allocate.
Definition (RFC 8878): “Zstandard, or "zstd" (pronounced "zee standard"), is a lossless data compression mechanism.” A stream is a sequence of frames (magic 0xFD2FB528, written 28 b5 2f fd), each with a frame header (window descriptor, optional dictionary ID, optional content size, checksum flag) and blocks (raw, RLE or compressed; max 128 KiB each). Skippable frames (magic 0x184D2A50-0x184D2A5F) carry metadata that decoders ignore. Levels: --fast=N (negative), 1-19, --ultra 20-22; CLI default 3. --long[=27] raises the window to 128 MiB for both sides; -T# multithreads compression; --rsyncable; --patch-from for binary diffs; --train builds dictionaries; -M/--memory limits the decoder (default 128 MiB).
zstd levels on 146.6 MB of JSON logs (CLI, -T1, real sizes in bytes)
1 --fast=5 45,341,645 6 -6 25,625,103
2 -1 25,895,194 7 -9 25,032,934
3 -2 26,537,297 8 -12 24,439,706
4 -3 27,482,535 9 -15 23,903,805
5 -4 28,092,790 10 -19 20,960,927
11 -3 --long=27 26,970,909 (repeats further than 8 MB back now count)
(File-argument runs store Frame_Content_Size, so they are 4 bytes larger than the stdin runs in the Measured table.)Levels 2-4 are larger than level 1 on this data. That is real and reproducible here (zstd -b1 -e5 shows the same dip), and it is exactly why you measure on your own corpus.
Real scenarios: Kafka compression.type=zstd, Parquet ZSTD, PostgreSQL wal_compression=zstd and pg_dump --compress=zstd, MongoDB zstd block compressor (default for time-series collections), HTTP Content-Encoding: zstd (Chrome 123, Firefox 126, Safari 26.3), Caddy's preferred on-the-fly encoding.
| Knob | CLI | Go (klauspost) | Effect |
|---|---|---|---|
| Level | -1 ... -19, --ultra -22, --fast=N | WithEncoderLevel(SpeedFastest / SpeedDefault / SpeedBetterCompression / SpeedBestCompression) | Search effort |
| Window | --long[=27], --memory= on decode | WithWindowSize, WithDecoderMaxWindow | Repeat distance vs memory |
| Threads | -T0 / -T# | WithEncoderConcurrency, WithDecoderConcurrency | Throughput on big inputs |
| Checksum | --check / --no-check | WithEncoderCRC | XXH64-based frame checksum (lower 32 bits) |
| Dictionary | --train, -D dict | WithEncoderDict, WithDecoderDicts, dict.BuildZstdDict | Small-payload ratio |
| Decoder memory limit | -M / --memory | WithDecoderMaxMemory | Defence against bombs |
Fix / how to use it: in Go, reuse one *zstd.Encoder / *zstd.Decoder (they are concurrency-safe for EncodeAll / DecodeAll and expensive to create); stream with NewWriter(w) / NewReader(r) and always Close(). The benchmark snippet and the dictionary snippet show both styles.
Dictionary compression Important
In plain words: small messages compress badly because the compressor has no past to point into. A dictionary is a pre-agreed "past" that both sides load before the first byte: typical keys, values and structure of your messages.
Common misunderstanding: "One dictionary for everything." The zstd README: “The more data-specific a dictionary is, the more efficient it is (there is no universal dictionary).” And "Dictionary gains are mostly effective in the first few KB."
Definition: zstd dictionaries are trained from samples (zstd --train, "The training set should contain a lot of small files (> 100)") and carry a 4-byte dictionary ID that the frame header records; decoding without the same dictionary fails. DEFLATE has preset dictionaries too (zlib's FDICT flag; PHP's deflate_init(..., ['dictionary' => ...]); Go's flate.NewWriterDict). Brotli's static dictionary is the built-in version of the same idea; RFC 9842 lets HTTP use a previous response as the dictionary (dcb, dcz).
1,000 order events, ~210 bytes of JSON each, compressed one by one (real output)
1 go run ./dictionary : no dict 174.0 B (1.21x) -> Go-built 16 KB dict 96.3 B (2.18x)
2 CLI zstd -3 (300 events) : no dict 173.9 B -> zstd --train 16 KB dict 71.5 B (2.93x)
3 gzip -6 (300 events) : 175.9 B (18 of them are header + trailer)
4 zstd -dc without the dict : "Decoding error (36) : Dictionary mismatch"Real scenarios: per-message compression on Kafka or Redis when batching is impossible, cache entries (one JSON per key), RPC payloads between two services you own, mobile API responses, database row/page compression with a shared dictionary.
| Tool | Train | Use |
|---|---|---|
| zstd CLI | zstd --train samples/* -o dict --maxdict=16384 | zstd -D dict, zstd -D dict -d |
| Go klauspost | dict.BuildZstdDict(samples, dict.Options{...}) | zstd.WithEncoderDict(d), zstd.WithDecoderDicts(d) |
| zlib (any language) | You pick the bytes (common strings at the end) | Go flate.NewWriterDict; PHP deflate_init / inflate_init dictionary option |
| HTTP | Server sends Use-As-Dictionary on a resource | Available-Dictionary request header, dcb / dcz coding (RFC 9842) |
Fix: version your dictionaries (the ID is in every frame), keep old ones available for decoding as long as data compressed with them exists, retrain when the schema changes. Code in Small payloads.
lz4 and snappy (and S2) Important
In plain words: LZ77 with no entropy stage and byte-aligned tokens: the ratio is modest (about 3.3x on our logs) but compression runs at gigabytes per second per core and decompression is close to memcpy. Use them where CPU per byte matters more than size: storage engines, RPC, in-memory caches.
Common misunderstanding: "lz4 is a weak gzip." It is a different trade: on our data lz4 -1 compressed 27x faster than gzip -6 and decompressed 2x faster, for 1.7x more bytes. In a database that reads and decompresses blocks on every query, that trade wins.
Definition: lz4 block format: sequences of a token (4-bit literal length, 4-bit match length), literals, a 2-byte little-endian offset ("The maximum offset value is 65535"), minimum match 4. The lz4 frame format adds magic 0x184D2204 (04 22 4d 18), block checksums and content size. snappy: "Snappy is a LZ77-type compressor with a fixed, byte-oriented encoding. There is no entropy encoder backend nor framing layer"; its framing format is a separate spec. S2 (klauspost) is a snappy extension that can decode snappy; on our logs it compressed 2x faster than snappy with a slightly lower ratio (3.24 vs 3.37).
Go in-process, 9.8 MB of logs (real output of go run ./bench)
1 lz4 block 2,914,808 B 3.35x 968 MB/s compress 7,344 MB/s decompress
2 snappy block 2,893,851 B 3.37x 755 MB/s 3,376 MB/s
3 s2 block 3,015,136 B 3.24x 1,584 MB/s 4,116 MB/s
4 zstd fastest 1,776,305 B 5.50x 656 MB/s 1,383 MB/sReal scenarios: Cassandra and ScyllaDB SSTables (LZ4Compressor default), MongoDB WiredTiger (snappy default), Parquet (SNAPPY codec), Kafka (lz4, snappy), PostgreSQL TOAST lz4, Elasticsearch stored fields (LZ4 by default).
| Product | lz4 / snappy role |
|---|---|
| Cassandra | LZ4Compressor default; chunk_length_in_kb default 16 KiB; also Snappy, Deflate, Zstd |
| ScyllaDB | LZ4Compressor default; SnappyCompressor, DeflateCompressor, ZstdCompressor |
| MongoDB WiredTiger | snappy for collections and the journal by default; zlib, zstd optional |
| PostgreSQL TOAST | pglz or lz4 per column |
| Kafka | lz4 (level 1-17, default 9), snappy |
Fix / how to use it: Go: github.com/pierrec/lz4/v4 (lz4.NewWriter, CompressBlock) and github.com/klauspost/compress/snappy / s2. The benchmark uses the block APIs.
xz / LZMA and bzip2 Good to know
In plain words: the "maximum ratio, slow" corner. xz (LZMA2) uses a huge window and a range coder; bzip2 sorts the input with the Burrows-Wheeler transform so similar contexts sit together, then codes it.
Common misunderstanding: "bzip2 is just slow gzip." It is a different algorithm family (block sorting) and gave the best ratio on our logs (7.66), but decompresses at 87 MB/s, 20x slower than zstd. xz decompresses at 176 MB/s. For data you read often, that read cost dominates.
Definition: xz file magic fd 37 7a 58 5a 00 ("\xFD7zXZ\0"), LZMA2 filter, CRC-32/CRC-64/SHA-256 integrity check, presets 0-9 (preset -6: 8 MiB dictionary, about 94 MiB to compress and 9 MiB to decompress per the xz man page). bzip2: magic 42 5a 68 ("BZh") plus the block size digit; "Burrows-Wheeler block-sorting text compression" with 100k-900k blocks.
Same 146.6 MB, real numbers
1 xz -6 22,029,324 B 6.65x 5 MB/s compress 176 MB/s decompress
2 bzip2 -9 19,145,851 B 7.66x 19 MB/s 87 MB/s
3 zstd -19 20,960,927 B 6.99x 4 MB/s 2,697 MB/sReal scenarios: .tar.xz source tarballs and OS package payloads, legacy .bz2 data dumps, 7-Zip archives (LZMA/LZMA2), any "write once, download many times" artifact where the publisher pays the CPU once.
| Use | Prefer |
|---|---|
| Archive written once, rarely read | xz -6/-9 or zstd -19 --long |
| Archive read often (CI caches, container layers) | zstd |
| Legacy compatibility | bzip2 / xz as required |
Fix: for new archives use tar --zstd (or zstd -19 --long=27 -T0); keep xz where your ecosystem expects it.
Streaming vs block compression, and seekable formats Important
In plain words: streaming compressors keep state across the whole input, so you can compress data as it arrives and get the best ratio, but you must read from the start to decompress. Block compression cuts data into independent chunks: worse ratio, but any chunk can be decompressed alone and in parallel.
Common misunderstanding: "I can seek inside a .gz." Not without decompressing everything before the target (tools can build an index of decompressor checkpoints, but the format has none). zstd solves it with the seekable format; storage engines solve it by compressing fixed-size blocks.
Definition: streaming APIs are writers/readers (gzip.NewWriter(w), zstd.NewWriter(w), PHP deflate_init + deflate_add); Flush() / ZLIB_SYNC_FLUSH emits everything buffered so far at a small ratio cost (needed for SSE and chunked streaming). Block APIs compress a whole buffer (EncodeAll, snappy.Encode, lz4.CompressBlock). zstd's seekable format splits input into independent frames and puts a seek table in a skippable frame: "subranges of the data can be efficiently decompressed without requiring the entire document to be decompressed."
Streaming an HTTP export through gzip (Go middleware on this page)
1 handler writes 32 KiB of NDJSON -> gzip.Writer -> compressed bytes buffered
2 handler calls Flush() -> gzip sync flush -> chunk sent to the client now
3 ... -> client decompresses incrementally
4 handler returns -> gzip.Close() -> final block + CRC-32 + ISIZE trailer
Block storage (Cassandra, chunk_length_in_kb=16)
5 read row at offset X -> find 16 KiB chunk via compression offsets -> decompress that chunk onlyReal scenarios: HTTP responses and log shippers (streaming), Server-Sent Events (stream with flushes), Parquet pages, Cassandra/Scylla chunks (block), seekable zstd for large logs read by range, pigz and zstd -T0 (parallel streaming by splitting into independently compressed jobs).
| Mode | Ratio | Random access | Parallel | Examples |
|---|---|---|---|---|
| One stream | Best | No | Encode only with tricks (pigz) | .gz, .zst, HTTP bodies |
| Independent blocks | Lower (no cross-block matches) | Yes | Yes | Parquet, Cassandra, zip entries |
| Seekable stream | Close to stream | Yes, via seek table | Yes | zstd seekable format |
Fix: for files you will query by range, compress in frames of 64 KiB-1 MiB and keep an index; for HTTP and pipes, stream and flush only when latency matters.
Compression levels and the speed / ratio / memory triangle Must-know
In plain words: every codec lets you pay more CPU (and sometimes memory) for fewer bytes. You can have two corners of the triangle (fast, small, low-memory) but not all three.
Common misunderstanding: "Pick the maximum level once and forget it." Compression cost is paid on every write (and on every HTTP response if you compress on the fly), while the saved bytes are often worth little after the first few levels: gzip -9 was 2.4x slower than gzip -6 for 4.7% fewer bytes; brotli -q 11 was more than 100x slower than -q 5 for 21% fewer bytes.
Definition: a level selects the match-finder strategy (hash chain depth, lazy matching, binary trees, optimal parsing) and sometimes the window size. Speed is MB/s of uncompressed data per core; ratio is original / compressed size; memory is the encoder's tables plus the window the decoder must keep.
What the level changes (zlib DEFLATE)
1 -1 : short hash chains, take the first decent match -> fast, bigger
2 -6 : longer chains, lazy matching -> default
3 -9 : longest chains, try harder at every position -> slow, a few % smaller
Decoder cost does not change with the level -> pay once at write time, read many timesReal scenarios: CI building assets once (max level), an API gateway compressing every response (low level), a Kafka producer at 100k msgs/s (zstd -1..3 or lz4), nightly backups (zstd -10..19 with -T0), an embedded device with 64 MB of RAM (avoid --long and xz -9).
| Codec | Level range | Default | Memory to note |
|---|---|---|---|
| gzip / zlib | 1-9 (0 = store) | 6 (nginx gzip_comp_level default 1) | 32 KiB window; trivial |
| Brotli | 0-11 | 11 in the CLI (--best is the default); ngx_brotli 6 | window up to 16 MiB |
| zstd | --fast=N, 1-19, 20-22 with --ultra | 3 | RFC 8878 recommends windows up to 8 MB; --long = 128 MiB on both sides; decoder limit -M default 128 MiB |
| lz4 | 1 (fast) to 12 (--best), higher levels use the HC match finder; --fast=N | 1 | 64 KB window |
| xz | 0-9, -e extreme | 6 | 94 MiB to compress, 9 MiB to decompress at -6 |
| bzip2 | 1-9 = 100k-900k block | 9 | -9: 7600k to compress, 3700k to decompress |
Fix: measure with zstd -b1 -e19 file, lzbench, or the Go benchmark; choose the level where the next step stops paying; set it explicitly in config so an upgrade does not change it silently.
Measured: the speed / ratio / memory triangle
All numbers on this page were measured on an Apple M5 laptop with Apple gzip 487 (zlib), brotli 1.2.0, zstd 1.5.7, lz4 1.10.0, xz 5.8.4 and bzip2 1.0.8, single-threaded (-T1 where the tool has threads), best of three runs, file in page cache. CLI timings include process start-up, so they are only meaningful on the 146.6 MB file; on the smaller files we report ratios only. The corpus: logs.jsonl (600,000 synthetic access-log lines, 146.6 MB, plus a 9.8 MB slice), persian.txt (12 Persian Wikipedia articles, 1.47 MB of UTF-8), image.png (a 700 KB macOS icon) and random.bin (4 MB from /dev/urandom). The Lab has the generator and the script.
JSON logs, 146,573,164 bytes (the chart's data):
| Tool and level | Compressed bytes | Ratio | Compress MB/s | Decompress MB/s |
|---|---|---|---|---|
| gzip -1 | 32,947,186 | 4.45 | 321 | 1,666 |
| gzip -6 | 26,475,872 | 5.54 | 134 | 1,619 |
| gzip -9 | 25,239,894 | 5.81 | 56 | 1,654 |
| brotli -q 1 | 27,865,849 | 5.26 | 688 | 953 |
| brotli -q 5 | 25,503,910 | 5.75 | 129 | 1,124 |
| brotli -q 11 | 20,141,927 | 7.28 | 1 | 893 |
| zstd -1 | 25,895,190 | 5.66 | 1,102 | 2,121 |
| zstd -3 | 27,482,531 | 5.33 | 748 | 2,047 |
| zstd -19 | 20,960,927 | 6.99 | 4 | 2,697 |
| lz4 -1 | 45,093,180 | 3.25 | 3,626 | 3,232 |
| lz4 -9 (HC) | 34,509,173 | 4.25 | 473 | 3,309 |
| xz -6 | 22,029,324 | 6.65 | 5 | 176 |
| bzip2 -9 | 19,145,851 | 7.66 | 19 | 87 |
Ratios on the other inputs (same tools):
| Tool and level | Persian text 1.47 MB | PNG 700 KB | Random 4 MB |
|---|---|---|---|
| gzip -1 / -6 / -9 | 2.79 / 3.81 / 3.94 | 1.01 / 1.01 / 1.01 | 1.00 (grew 1,238-1,243 B) |
| brotli -q 1 / 5 / 11 | 3.35 / 3.96 / 5.07 | 1.01 / 1.00 / 1.01 | 1.00 |
| zstd -1 / -3 / -19 | 3.50 / 3.76 / 5.04 | 1.01 / 1.01 / 1.01 | 1.00 (grew 103 B) |
| lz4 -1 / -9 | 2.21 / 3.42 | 1.00 / 1.01 | 1.00 |
| xz -6 | 5.11 | 1.01 | 1.00 |
| bzip2 -9 | 5.54 | 1.01 | 1.00 (grew 18,071 B) |
Persian text compresses less than the logs because natural language repeats less exactly than log lines; its UTF-8 lead bytes (0xD8-0xDB) are nearly constant, which entropy coders exploit (order-0 bound 1.93x) and lz4 (no entropy stage) cannot, which is why lz4 -1 trails at 2.21x. The PNG is already zlib-compressed inside, so nothing works on it.
In-process Go numbers (no process start-up), 9.8 MB slice of the logs:
| Codec (Go package) | Bytes | Ratio | Compress MB/s | Decompress MB/s |
|---|---|---|---|---|
stdlib compress/gzip -1 / -6 / -9 | 1,922,502 / 1,732,479 / 1,593,736 | 5.08 / 5.64 / 6.13 | 592 / 298 / 66 | 533-614 |
klauspost gzip -1 / -6 / -9 | 1,922,517 / 1,732,533 / 1,593,755 | 5.08 / 5.64 / 6.13 | 622 / 342 / 66 | 534-609 |
klauspost zstd fastest / default / better / best | 1,776,305 / 1,812,899 / 1,693,177 / 1,692,704 | 5.50 / 5.39 / 5.77 / 5.77 | 656 / 528 / 311 / 78 | 1,383-1,536 |
andybalholm brotli 1 / 5 / 11 | 1,857,437 / 1,657,697 / 1,356,085 | 5.26 / 5.89 / 7.20 | 444 / 83 / 1 | 439-576 |
pierrec lz4 block | 2,914,808 | 3.35 | 968 | 7,344 |
klauspost snappy / s2 block | 2,893,851 / 3,015,136 | 3.37 / 3.24 | 755 / 1,584 | 3,376 / 4,116 |
On Go 1.27 the standard library's gzip output is within a few bytes of klauspost's, and its fastest level is close in speed; the bigger Go win is switching codec (zstd decompresses 2.5x faster than gzip here), not switching gzip package.
// Command bench compresses one file in-process with several codecs and
// levels and prints ratio and single-core throughput. Same input, same
// machine, no process start-up in the numbers.
package main
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"log"
"os"
"time"
"github.com/andybalholm/brotli"
kgzip "github.com/klauspost/compress/gzip"
"github.com/klauspost/compress/s2"
"github.com/klauspost/compress/snappy"
"github.com/klauspost/compress/zstd"
"github.com/pierrec/lz4/v4"
)
type codec struct {
name string
encode func([]byte) []byte
decode func([]byte) []byte
}
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}
func stream(newW func(io.Writer) io.WriteCloser) func([]byte) []byte {
return func(in []byte) []byte {
var buf bytes.Buffer
w := newW(&buf)
must(w.Write(in))
if err := w.Close(); err != nil {
log.Fatal(err)
}
return buf.Bytes()
}
}
func readAll(newR func(io.Reader) io.Reader) func([]byte) []byte {
return func(in []byte) []byte { return must(io.ReadAll(newR(bytes.NewReader(in)))) }
}
func main() {
if len(os.Args) != 2 {
log.Fatal("usage: bench <file>")
}
in := must(os.ReadFile(os.Args[1]))
gunzip := readAll(func(r io.Reader) io.Reader { return must(gzip.NewReader(r)) })
zdec := must(zstd.NewReader(nil))
defer zdec.Close()
var codecs []codec
for _, l := range []int{1, 6, 9} {
l := l
codecs = append(codecs,
codec{fmt.Sprintf("stdlib gzip -%d", l), stream(func(w io.Writer) io.WriteCloser { return must(gzip.NewWriterLevel(w, l)) }), gunzip},
codec{fmt.Sprintf("klauspost gzip -%d", l), stream(func(w io.Writer) io.WriteCloser { return must(kgzip.NewWriterLevel(w, l)) }), gunzip})
}
for _, lvl := range []zstd.EncoderLevel{zstd.SpeedFastest, zstd.SpeedDefault, zstd.SpeedBetterCompression, zstd.SpeedBestCompression} {
enc := must(zstd.NewWriter(nil, zstd.WithEncoderLevel(lvl), zstd.WithEncoderConcurrency(1)))
codecs = append(codecs, codec{"zstd " + lvl.String(),
func(b []byte) []byte { return enc.EncodeAll(b, nil) },
func(b []byte) []byte { return must(zdec.DecodeAll(b, nil)) }})
}
for _, q := range []int{1, 5, 11} {
q := q
codecs = append(codecs, codec{fmt.Sprintf("brotli -q %d", q),
stream(func(w io.Writer) io.WriteCloser { return brotli.NewWriterLevel(w, q) }),
readAll(func(r io.Reader) io.Reader { return brotli.NewReader(r) })})
}
codecs = append(codecs,
codec{"lz4 block", func(b []byte) []byte {
dst := make([]byte, lz4.CompressBlockBound(len(b)))
var c lz4.Compressor
return dst[:must(c.CompressBlock(b, dst))]
}, func(b []byte) []byte {
dst := make([]byte, len(in))
return dst[:must(lz4.UncompressBlock(b, dst))]
}},
codec{"snappy block", func(b []byte) []byte { return snappy.Encode(nil, b) },
func(b []byte) []byte { return must(snappy.Decode(nil, b)) }},
codec{"s2 block", func(b []byte) []byte { return s2.Encode(nil, b) },
func(b []byte) []byte { return must(s2.Decode(nil, b)) }},
)
fmt.Printf("%-20s %12s %7s %10s %10s\n", "codec", "bytes", "ratio", "comp MB/s", "dec MB/s")
for _, c := range codecs {
// Best of three runs; one run is enough for the slow levels.
var out, back []byte
ct, dt := time.Duration(1<<62), time.Duration(1<<62)
for run := 0; run < 3 && ct < 2*time.Second || run == 0; run++ {
t := time.Now()
out = c.encode(in)
ct = min(ct, time.Since(t))
t = time.Now()
back = c.decode(out)
dt = min(dt, time.Since(t))
}
if !bytes.Equal(back, in) {
log.Fatalf("%s: round trip mismatch", c.name)
}
mb := float64(len(in)) / 1e6
fmt.Printf("%-20s %12d %7.2f %10.0f %10.0f\n", c.name, len(out),
float64(len(in))/float64(len(out)), mb/ct.Seconds(), mb/dt.Seconds())
}
}Per-product behaviour
Codec feature matrix
| gzip/DEFLATE | Brotli | zstd | lz4 | snappy | xz | bzip2 | |
|---|---|---|---|---|---|---|---|
| Spec | RFC 1951/1950/1952 | RFC 7932 | RFC 8878 | lz4 block + frame docs | format_description.txt | .xz file format | none formal |
| Entropy stage | Huffman | Huffman + context | Huffman + FSE | none | none | range coder | Huffman |
| Max window | 32 KiB | 16 MiB | 8 MB typical, --long 128 MiB+ | 64 KB | ~32 KiB in practice | 1.5 GiB | 900k block |
| Built-in dictionary | no (preset dict supported) | yes, 122,784 bytes | trained, by ID | raw dict API | no | no | no |
| Checksum | CRC-32 (gzip), Adler-32 (zlib) | none | optional XXH64 (low 32 bits) | optional xxHash32 (frame) | masked CRC-32C (framing format) | CRC-32/64, SHA-256 | CRC-32 per block |
| Magic | 1f 8b / 78 xx | none | 28 b5 2f fd | 04 22 4d 18 | ff 06 00 00 73 4e 61 50 70 59 (framing) | fd 37 7a 58 5a 00 | 42 5a 68 |
| HTTP coding | gzip, deflate | br | zstd | no | no | no | no |
Where each product compresses
| Product | What is compressed | Codec / knob | Default |
|---|---|---|---|
| PostgreSQL TOAST | Column values wider than ~2 kB (TOAST_TUPLE_THRESHOLD) | default_toast_compression, column COMPRESSION pglz / lz4 | pglz in 18; docs for 19: "lz4 (if available); otherwise, pglz" |
| PostgreSQL WAL | Full-page images | wal_compression = off / on / pglz / lz4 / zstd | off |
| PostgreSQL backups | pg_dump archives | pg_dump --compress=gzip / lz4 / zstd[:level] (zstd also long) | custom and directory formats: gzip "at a moderate level"; plain text: none |
| MongoDB WiredTiger | Collection blocks, journal, network | blockCompressor snappy / zlib / zstd; journalCompressor; net.compression.compressors | snappy (time-series: zstd); network snappy,zstd,zlib; indexes: prefix compression |
| Cassandra | SSTable chunks | compression = {'class': 'LZ4Compressor', 'chunk_length_in_kb': 16} | LZ4Compressor, 16 KiB |
| ScyllaDB | SSTable chunks | {'sstable_compression': 'LZ4Compressor'} (also Snappy, Deflate, Zstd) | LZ4Compressor |
| Redis | RDB snapshots (LZF on strings), quicklist nodes | rdbcompression yes, list-compress-depth | RDB yes; list compression 0 (off); values in memory: none |
| Kafka | Whole record batches | producer compression.type none/gzip/snappy/lz4/zstd; topic compression.type=producer | producer none; topic producer |
| Parquet | Column chunk pages | UNCOMPRESSED, SNAPPY, GZIP, LZ4_RAW, ZSTD, BROTLI | writer-specific |
| Elasticsearch | Stored fields | index.codec: default (LZ4) or best_compression (ZSTD) | default (LZ4) |
Product-specific deep dives: PostgreSQL TOAST layout, MongoDB, Cassandra & ScyllaDB, Redis, Kafka batching, backups.
HTTP support
| Client / server | gzip | br | zstd | Notes |
|---|---|---|---|---|
| Chrome / Edge | yes | 50 / 15 | 123 | dcb/dcz dictionary transport from Chrome 130 |
| Firefox | yes | 44 | 126 | |
| Safari | yes | 11 | 26.3 | |
| curl | --compressed | if built with brotli | if built with zstd | without --compressed curl sends no Accept-Encoding |
Go net/http client | transparent | no | no | Adds Accept-Encoding: gzip itself and decodes, unless you set the header or DisableCompression |
Guzzle / Laravel Http | decode_content true by default | curl-dependent | curl-dependent | withOptions(['decode_content' => false]) keeps raw bytes |
| nginx | gzip, gzip_static, gunzip | ngx_brotli module | third-party module | gzip_proxied default off |
| Caddy | encode gzip | precompressed br only | encode zstd (preferred) | default minimum_length 512 |
| Go server | compress/gzip, gzhttp | andybalholm/brotli | klauspost zstd | nothing automatic |
| PHP | zlib.output_compression, ob_gzhandler, gzencode | PECL ext-brotli | PECL ext-zstd | none of br/zstd in the official image |
Mechanics
Magic numbers: identify any compressed file Must-know
Run xxd -l 16 file and match the first bytes. Every line below is real output for the same 24-byte input hello hello hello hello\n (68656c6c6f2068656c6c6f2068656c6c6f2068656c6c6f0a).
| Format | First bytes | Total size for the 24-byte input | Real hex (start) |
|---|---|---|---|
| raw DEFLATE (zlib, level 6) | none | 11 | cb48 cdc9 c957 c840 27b9 00 |
| zlib | 78 9c (default level) | 17 | 789c cb48 ... 70be 08bb |
| gzip | 1f 8b 08 | 29 | 1f8b 0800 0000 0000 0003 cb48 ... |
| zstd | 28 b5 2f fd | 26 | 28b5 2ffd 2418 6d00 0038 6865 6c6c 6f20 |
| lz4 frame | 04 22 4d 18 | 34 | 0422 4d18 6440 a70f 0000 0069 6865 6c6c |
| Brotli | none (no magic) | 24 | a1b8 00c0 6fa4 74f3 26aa 32b4 5600 617b |
| xz | fd 37 7a 58 5a 00 | 80 | fd37 7a58 5a00 0004 e6d6 b446 04c0 1418 |
| bzip2 | 42 5a 68 39 ("BZh9") | 47 | 425a 6839 3141 5926 5359 ... |
| zip | 50 4b 03 04 ("PK") | - | local file header signature 0x04034b50 |
On tiny inputs most formats grow the data: the headers are fixed costs. That is the whole argument for a minimum length (nginx gzip_min_length, Caddy minimum_length).
Reading a gzip header and trailer byte by byte Important
Go compress/gzip with Header.Name = "hello.txt", ModTime = Unix 0 (real output, 59 bytes)
00 1f 8b ID1 ID2 (magic)
02 08 CM = 8 (deflate)
03 08 FLG = 0x08 -> FNAME present
04 00 00 00 00 MTIME = 0 (gzip -n also writes 0; otherwise the file time breaks reproducible builds)
08 00 XFL
09 ff OS = 255 (unknown); Apple gzip writes 03 (Unix)
0a 68 65 6c 6c 6f 2e 74 78 74 00 FNAME "hello.txt\0"
14 00 18 00 e7 ff ... 03 00 DEFLATE blocks (here: one stored block + empty final block)
33 00 88 59 0b CRC-32 = 0x0b598800, little-endian
37 18 00 00 00 ISIZE = 24 (input length mod 2^32), little-endianISIZE is why gzip -l reports the uncompressed size instantly, and why that report is wrong for files over 4 GiB or with several members. The CRC-32 is checked by every reader at the end of the stream: a truncated download fails there with unexpected EOF. CRC-32 vs Adler-32 vs xxHash is covered in Checksums & Hashing.
Reading a zstd frame header Good to know
hello.zst (26 bytes, real) 28b52ffd 24 18 6d0000 38 68656c6c6f20 0a 01 00 99 4b 11 a87c2ea8
1 28 b5 2f fd Magic_Number 0xFD2FB528 (little-endian)
2 24 Frame_Header_Descriptor = 0b0010_0100: Single_Segment=1, Content_Checksum=1, Dictionary_ID_Flag=0
3 18 Frame_Content_Size = 24
4 6d 00 00 Block_Header (LE 0x00006d): Last_Block=1, Block_Type=2 (compressed), Block_Size=13
5 38 ... 11 13 bytes: literals section ("hello " + "\n") and one sequence (match offset 6, length 17)
6 a8 7c 2e a8 Content_Checksum: low 32 bits of XXH64 (zstd -lv prints "Check: XXH64 a82e7ca8")
t.zst, one event compressed with a trained dictionary (real)
7 28 b5 2f fd 27 ea 17 79 66 d3 ... FHD 0x27 -> Dictionary_ID_Flag=3 (4 bytes): ID 0x667917ea = 1719212010; FCS = 0xd3 = 211The dictionary ID in the header is how a decoder knows which dictionary to load, and why zstd -dc t.zst without -D fails with Dictionary mismatch.
Every knob, in one table
| Where | Knob | Values / default | Effect |
|---|---|---|---|
| zlib / Go flate / PHP | level | -1 default (= 6), 0 store, 1-9; Go HuffmanOnly = -2 | Search effort |
zlib / PHP deflate_init | window (windowBits) | 8-15, default 15 (32 KiB) | Window; lower saves memory |
zlib / PHP deflate_init | memory (memLevel) | 1-9, default 8 | Hash table size |
zlib / PHP deflate_init | strategy | ZLIB_DEFAULT_STRATEGY, ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXED | Specialised match strategies |
| PHP ini | zlib.output_compression | 0 default; On or a buffer size | Transparent page compression when the client sends Accept-Encoding: gzip |
| PHP ini | zlib.output_compression_level | -1 | Level for the above |
| nginx | gzip, gzip_comp_level, gzip_min_length, gzip_types, gzip_proxied, gzip_vary, gzip_buffers, gzip_http_version, gzip_disable | off, 1, 20, text/html, off, off, 32 4k|16 8k, 1.1, none | See HTTP |
| nginx | gzip_static | on / off / always | Serve file.gz sidecars |
| ngx_brotli | brotli, brotli_static, brotli_comp_level, brotli_window, brotli_min_length, brotli_types | off, -, 6, 512k, 20, text/html | Same idea for br |
| Caddy | encode [gzip [level]] [zstd [level]] { minimum_length; match } | zstd + gzip, 512 B, a list of text types | On-the-fly encoding |
| Caddy | file_server { precompressed br zstd gzip } | br zstd gzip order | Sidecar files |
| zstd CLI | -#, --ultra, --fast, --long, -T, -M, -D, --train, --rsyncable, --patch-from, --adapt | 3, -, -, 27, 1-4 threads, 128 MiB | See zstd |
| Kafka producer | compression.type, compression.gzip.level, compression.lz4.level, compression.zstd.level, batch.size, linger.ms | none, -1, 9, 3, 16384, 5 | Batch codec and batch size |
| Kafka topic/broker | compression.type | producer | Re-compress on the broker if different |
| PostgreSQL | default_toast_compression, column COMPRESSION, wal_compression | pglz (18) / lz4 if available (19), off | TOAST and WAL full-page images |
| MongoDB | storage.wiredTiger.collectionConfig.blockCompressor, ...engineConfig.journalCompressor, ...indexConfig.prefixCompression, net.compression.compressors | snappy, snappy, true, snappy,zstd,zlib | Storage and wire |
| Cassandra | table compression = {'class', 'chunk_length_in_kb', 'lz4_compressor_type', 'lz4_high_compressor_level', 'compression_level'} | LZ4Compressor, 16 KiB, fast, 9, 3 (zstd) | SSTable chunks |
| Redis | rdbcompression, list-compress-depth | yes, 0 | LZF for RDB strings; quicklist node compression |
Go net/http | Transport.DisableCompression | false | Client auto gzip |
| Guzzle / Laravel | decode_content | true | Client auto decode |
Error messages you will see
| Message (verbatim) | Where | Meaning |
|---|---|---|
gzip: invalid header | Go gzip.NewReader | Input is not gzip (zlib, raw, brotli, plain text, an HTML error page) |
zlib: invalid header | Go zlib.NewReader | Not zlib (often gzip or raw deflate) |
flate: corrupt input before offset N | Go compress/flate (CorruptInputError) | Bad DEFLATE stream, or wrong wrapper stripped |
unexpected EOF | Go readers | Truncated stream: missing trailer or final block |
gzip: invalid checksum | Go gzip.Reader | CRC-32 or ISIZE mismatch: corruption |
gzdecode(): data error | PHP | Not gzip, or corrupt |
gzdecode(): insufficient memory | PHP with $max_length | Output would exceed $max_length (your bomb guard working) |
Decoding error (36) : Dictionary mismatch | zstd CLI | Frame needs a dictionary you did not pass with -D |
Decoding error (36) : Frame requires too much memory for decoding and Window size larger than maximum : 9766722 > 8388608 | zstd CLI with --memory=8MB | Frame's window exceeds the decoder limit (made with --long); real output |
gzip: stdin: not in gzip format | gzip CLI | Same as invalid header |
ERR_CONTENT_DECODING_FAILED | Chrome | Server said Content-Encoding: gzip but sent something else (double compression or none) |
http: request body too large | Go http.MaxBytesReader | Compressed body exceeded the cap |
415 Unsupported Media Type + Accept-Encoding | HTTP server | RFC 9110: request used a content coding the server does not accept |
Solving the classic problems
Compressing HTTP responses: proxy, Go, Laravel
The flow. RFC 9110 calls Content-Encoding a property of the representation: "Content-Encoding is primarily used to allow a representation's data to be compressed without losing the identity of its underlying media type." Transfer-Encoding (HTTP/1.1, RFC 9112) is a property of the message: "Unlike Content-Encoding ..., Transfer-Encoding is a property of the message, not of the representation." In practice only chunked is used as a transfer coding; compression rides in Content-Encoding. RFC 9113 forbids Transfer-Encoding in HTTP/2 ("An endpoint MUST NOT generate an HTTP/2 message containing connection-specific header fields", which include Transfer-Encoding).
Negotiation (real headers from the lab)
1 client -> GET /mw/export Accept-Encoding: gzip
2 server -> 200 Content-Encoding: gzip Vary: Accept-Encoding Transfer-Encoding: chunked (109,079 bytes)
3 client -> GET /mw/export (no Accept-Encoding) -> 200 identity (1,766,580 bytes)
4 client -> GET /mw/export Accept-Encoding: gzip;q=0, identity -> 200 identity
5 client -> GET /mw/export?n=3 Accept-Encoding: gzip -> 200 Content-Length: 249, not compressed (below 1 KiB)
6 client -> POST /ingest Content-Encoding: br -> 415 + Accept-Encoding: gzip, zstd| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Compress at the reverse proxy | nginx gzip on, Caddy encode, CDN | One place, every upstream, C-speed, app stays simple | Proxy CPU; must set gzip_proxied any (nginx default off) and types |
| Pre-compress static files | gzip -9 -k, brotli -q 11, zstd -19 at build | Best ratio, zero CPU per request | Only for files known at build time |
| Compress in the app (Go middleware, Laravel middleware) | Wrap the response writer | Per-route control, works without a proxy | Every app must get Vary, ETag, flush, HEAD, 204/304 right |
| Compress at the CDN edge | CDN compression settings | Offloads origin, br/zstd for browsers | Origin to CDN may still be uncompressed |
| Do not compress | - | No CPU | Bandwidth, latency on slow links |
Proxy configs (tested in the lab with nginx 1.31 and Caddy 2.11; the app behind them sends identity):
# nginx: compress at the reverse proxy, once, for every upstream.
# ngx_http_gzip_module is built in; brotli needs the ngx_brotli module.
events {}
http {
upstream app { server host.docker.internal:8080; }
gzip on;
gzip_comp_level 5; # default 1; 5-6 is the usual sweet spot
gzip_min_length 1024; # default 20: tiny bodies grow, skip them
gzip_vary on; # add "Vary: Accept-Encoding" for caches
gzip_proxied any; # default off: compress proxied responses too
gzip_types application/json application/x-ndjson application/javascript
text/css text/plain application/xml image/svg+xml;
# text/html is always compressed; never list image/png, image/jpeg, video/*.
# Pre-compressed assets: serve app.js.gz next to app.js without CPU per request.
# gzip_static on;
# With ngx_brotli loaded:
# brotli on; brotli_comp_level 5; brotli_static on;
# brotli_types application/json application/javascript text/css image/svg+xml;
server {
listen 80;
location / {
proxy_pass http://app;
proxy_http_version 1.1;
# Ask the app for identity so the proxy does the compression.
proxy_set_header Accept-Encoding "";
}
}
}# Caddy: `encode` negotiates zstd and gzip from Accept-Encoding.
# With no formats listed, zstd (preferred) and gzip are enabled.
# The default `match` covers JSON, JS, CSS, HTML, SVG... but NOT
# application/x-ndjson, so streams like that pass through uncompressed
# unless you list them (a custom match replaces the default list).
:80 {
encode {
zstd
gzip 5
minimum_length 1024
match {
header Content-Type application/json*
header Content-Type application/x-ndjson*
header Content-Type text/*
header Content-Type application/javascript*
header Content-Type image/svg+xml*
}
}
reverse_proxy host.docker.internal:8080
}Measured through each proxy, same 1,766,580-byte NDJSON export: nginx gzip_comp_level 5 → 109,045 bytes for gzip, and identity when the client asked only for zstd; Caddy → 107,533 bytes with gzip and 55,662 bytes with zstd (preferred when the client lists both without q-values). Before adding the custom match block Caddy sent all 1,766,580 bytes uncompressed: application/x-ndjson is not in its default type list.
Go: a streaming middleware that handles the details (minimum size, Vary, already-encoded responses, media types, weak ETags, Flush for streaming, a sync.Pool of writers), next to the same route wrapped by klauspost/compress/gzhttp, and a client showing Go's transparent decoding:
// Command httpgzip serves the same JSON-lines export three ways: plain,
// through a hand-written streaming gzip middleware, and through
// klauspost/compress/gzhttp. Try it with curl -H 'Accept-Encoding: gzip'.
package main
import (
"bufio"
"compress/gzip"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"github.com/klauspost/compress/gzhttp"
)
// acceptsGzip reports whether Accept-Encoding lists gzip (or *) with q > 0.
func acceptsGzip(r *http.Request) bool {
for _, part := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
name, params, _ := strings.Cut(strings.TrimSpace(part), ";")
name = strings.ToLower(strings.TrimSpace(name))
if name != "gzip" && name != "*" {
continue
}
if q, ok := strings.CutPrefix(strings.TrimSpace(params), "q="); ok {
if v, err := strconv.ParseFloat(q, 64); err == nil && v == 0 {
return false
}
}
return true
}
return false
}
var gzPool = sync.Pool{New: func() any {
w, _ := gzip.NewWriterLevel(nil, gzip.DefaultCompression)
return w
}}
// gzipWriter buffers up to minSize bytes; small responses go out as-is,
// larger ones are compressed as they stream.
type gzipWriter struct {
http.ResponseWriter
minSize int
buf []byte
gz *gzip.Writer
status int
passthrough bool // decided not to compress
headerSent bool
}
func (w *gzipWriter) WriteHeader(code int) {
if w.status == 0 {
w.status = code
}
}
func (w *gzipWriter) Write(p []byte) (int, error) {
if w.status == 0 {
w.status = http.StatusOK
}
if w.passthrough || w.gz != nil {
return w.write(p)
}
if w.skip() {
w.passthrough = true
return w.write(p)
}
w.buf = append(w.buf, p...)
if len(w.buf) >= w.minSize {
w.startGzip()
_, err := w.gz.Write(w.buf)
w.buf = nil
return len(p), err
}
return len(p), nil
}
// skip reports whether this response must not be compressed: never
// compress twice, never compress bodies that cannot have one, skip formats
// that are already compressed.
func (w *gzipWriter) skip() bool {
h := w.Header()
ct := h.Get("Content-Type")
return h.Get("Content-Encoding") != "" || w.status == http.StatusNoContent ||
w.status == http.StatusNotModified || strings.HasPrefix(ct, "image/") ||
strings.HasPrefix(ct, "video/") || ct == "application/zip"
}
func (w *gzipWriter) startGzip() {
h := w.Header()
h.Set("Content-Encoding", "gzip")
h.Del("Content-Length") // the compressed length is unknown until the end
if et := h.Get("ETag"); et != "" && !strings.HasPrefix(et, "W/") {
h.Set("ETag", "W/"+et) // different bytes, so a strong ETag would lie
}
w.ResponseWriter.WriteHeader(w.status)
w.headerSent = true
w.gz = gzPool.Get().(*gzip.Writer)
w.gz.Reset(w.ResponseWriter)
}
func (w *gzipWriter) write(p []byte) (int, error) {
if w.gz != nil {
return w.gz.Write(p)
}
if !w.headerSent {
w.ResponseWriter.WriteHeader(w.status)
w.headerSent = true
}
return w.ResponseWriter.Write(p)
}
// Flush pushes compressed bytes to the client now (for streaming / SSE).
// The first Flush commits to gzip or identity, because it sends the headers.
func (w *gzipWriter) Flush() {
if w.gz == nil && !w.passthrough {
if w.status == 0 {
w.status = http.StatusOK
}
if w.skip() {
w.passthrough = true
w.write(w.buf)
} else {
w.startGzip()
w.gz.Write(w.buf)
}
w.buf = nil
}
if w.gz != nil {
w.gz.Flush()
}
if !w.headerSent {
w.ResponseWriter.WriteHeader(w.status)
w.headerSent = true
}
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
func (w *gzipWriter) close() {
switch {
case w.gz != nil:
w.gz.Close() // writes the CRC32 + ISIZE trailer
gzPool.Put(w.gz)
case !w.headerSent:
if w.status == 0 {
w.status = http.StatusOK
}
w.Header().Set("Content-Length", strconv.Itoa(len(w.buf)))
w.ResponseWriter.WriteHeader(w.status)
w.ResponseWriter.Write(w.buf)
}
}
func Gzip(minSize int, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Accept-Encoding") // caches must key on it
if !acceptsGzip(r) || r.Method == http.MethodHead {
next.ServeHTTP(w, r)
return
}
gw := &gzipWriter{ResponseWriter: w, minSize: minSize}
defer gw.close()
next.ServeHTTP(gw, r)
})
}
// export streams n JSON lines; nothing is held in memory.
func export(w http.ResponseWriter, r *http.Request) {
n, _ := strconv.Atoi(r.URL.Query().Get("n"))
if n <= 0 {
n = 20000
}
w.Header().Set("Content-Type", "application/x-ndjson")
bw := bufio.NewWriterSize(w, 32<<10)
for i := 0; i < n; i++ {
fmt.Fprintf(bw, `{"id":%d,"service":"orders-api","level":"info","path":"/api/orders/%d","status":200}`+"\n", i, i%977)
}
bw.Flush()
}
// events flushes small chunks: the first Flush commits to gzip, later
// flushes push each chunk through the compressor immediately.
func events(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
for i := 0; i < 3; i++ {
fmt.Fprintf(w, "data: {\"tick\":%d}\n\n", i)
w.(http.Flusher).Flush()
}
}
func main() {
mux := http.NewServeMux()
mux.Handle("GET /mw/events", Gzip(1024, http.HandlerFunc(events)))
mux.HandleFunc("GET /plain/export", export)
mux.Handle("GET /mw/export", Gzip(1024, http.HandlerFunc(export)))
mux.Handle("GET /gzhttp/export", gzhttp.GzipHandler(http.HandlerFunc(export)))
addr := os.Getenv("ADDR")
if addr == "" {
addr = ":8080"
}
log.Println("listening on", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}// Command httpclient shows what Go's http.Transport does with compression:
// it asks for gzip by itself and decodes it transparently, unless you set
// Accept-Encoding yourself or disable it.
package main
import (
"fmt"
"io"
"log"
"net/http"
)
func fetch(c *http.Client, url string, setHeader bool) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
if setHeader {
req.Header.Set("Accept-Encoding", "gzip")
}
resp, err := c.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("explicit header=%-5v Content-Encoding=%q Uncompressed=%-5v ContentLength=%d body=%d bytes, first byte %#x\n",
setHeader, resp.Header.Get("Content-Encoding"), resp.Uncompressed, resp.ContentLength, len(body), body[0])
}
func main() {
url := "http://localhost:8080/mw/export?n=20000"
fetch(http.DefaultClient, url, false) // transport adds gzip and decodes
fetch(http.DefaultClient, url, true) // you asked: you get raw gzip bytes
noGzip := &http.Client{Transport: &http.Transport{DisableCompression: true}}
fetch(noGzip, url, false) // no Accept-Encoding sent: identity
}The /mw/events route exercises Flush: with Accept-Encoding: gzip each event leaves immediately as its own small DEFLATE block followed by the sync-flush marker 00 00 ff ff (real bytes: 1f8b 0800 0000 0000 00ff 0012 00ed ff64 6174 613a ...), so streaming works but every flush costs a few bytes of framing.
go run ./httpclient (real output against the server above)
1 explicit header=false Content-Encoding="" Uncompressed=true body=1766580 bytes, first byte 0x7b <- transport asked for gzip and decoded
2 explicit header=true Content-Encoding="gzip" Uncompressed=false body=109079 bytes, first byte 0x1f <- you asked, you decode
3 explicit header=false Content-Encoding="" Uncompressed=false body=1766580 bytes, first byte 0x7b <- DisableCompression: identityLaravel: Laravel has no response-compression feature of its own; production setups compress in nginx/Caddy or the CDN. When PHP is exposed directly or you need per-route control, a middleware does it for buffered responses, and a streamed export compresses chunk by chunk with deflate_init() / deflate_add():
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Compress buffered responses when the client accepts gzip.
* Register in bootstrap/app.php:
* ->withMiddleware(function (Middleware $middleware): void {
* $middleware->api(append: [\App\Http\Middleware\GzipResponse::class]);
* })
* Prefer doing this in nginx/Caddy; use this when PHP is exposed directly
* (php artisan serve, Octane without a proxy) or for per-route control.
*/
class GzipResponse
{
private const MIN_BYTES = 1024;
private const COMPRESSIBLE = [
'application/json', 'application/ld+json', 'application/xml',
'application/javascript', 'text/', 'image/svg+xml', 'application/x-ndjson',
];
public function handle(Request $request, Closure $next): Response
{
/** @var Response $response */
$response = $next($request);
$response->headers->set('Vary', 'Accept-Encoding', false); // append, do not replace
if (! $this->clientAcceptsGzip($request)
|| $request->isMethod('HEAD')
|| $response instanceof StreamedResponse // body is not in memory
|| $response instanceof BinaryFileResponse // let the web server send files
|| $response->headers->has('Content-Encoding')
|| ! $this->isCompressible((string) $response->headers->get('Content-Type'))) {
return $response;
}
$content = $response->getContent();
if ($content === false || strlen($content) < self::MIN_BYTES) {
return $response;
}
$compressed = gzencode($content, 6);
if ($compressed === false) {
return $response;
}
$response->setContent($compressed);
$response->headers->set('Content-Encoding', 'gzip');
$response->headers->set('Content-Length', (string) strlen($compressed));
$etag = $response->getEtag();
if ($etag !== null && ! str_starts_with($etag, 'W/')) {
$response->setEtag(trim($etag, '"'), true); // weak: bytes changed
}
return $response;
}
private function clientAcceptsGzip(Request $request): bool
{
foreach (explode(',', (string) $request->headers->get('Accept-Encoding')) as $part) {
[$name, $params] = array_pad(explode(';', trim($part), 2), 2, '');
$name = strtolower(trim($name));
if ($name !== 'gzip' && $name !== '*') {
continue;
}
if (preg_match('/q\s*=\s*0(\.0*)?\s*$/', $params) === 1) {
return false;
}
return true;
}
return false;
}
private function isCompressible(string $contentType): bool
{
foreach (self::COMPRESSIBLE as $prefix) {
if (str_starts_with($contentType, $prefix)) {
return true;
}
}
return false;
}
}<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Stream a large NDJSON export gzip-compressed chunk by chunk.
* deflate_init()/deflate_add() keep one compressor alive across chunks,
* so memory stays flat and the client starts receiving bytes immediately.
*/
class ExportController
{
public function orders(Request $request): StreamedResponse
{
$gzip = str_contains((string) $request->headers->get('Accept-Encoding'), 'gzip');
$headers = [
'Content-Type' => 'application/x-ndjson',
'Vary' => 'Accept-Encoding',
'X-Accel-Buffering' => 'no', // tell nginx not to buffer the stream
];
if ($gzip) {
$headers['Content-Encoding'] = 'gzip';
}
return response()->stream(function () use ($gzip): void {
$ctx = $gzip ? deflate_init(ZLIB_ENCODING_GZIP, ['level' => 6]) : null;
foreach (Order::query()->select(['id', 'status', 'total', 'created_at'])->lazyById(2000) as $order) {
$line = $order->toJson()."\n";
// ZLIB_NO_FLUSH lets zlib batch; it emits bytes when its buffer fills.
echo $ctx ? deflate_add($ctx, $line, ZLIB_NO_FLUSH) : $line;
}
// ZLIB_FINISH writes the last block and the CRC32 + size trailer.
echo $ctx ? deflate_add($ctx, '', ZLIB_FINISH) : '';
}, 200, $headers);
}
}The plain-PHP equivalent of "turn it on globally" is zlib.output_compression=On; in the lab a php -S endpoint returning 358,341 bytes of JSON answered Content-Encoding: gzip, Vary: Accept-Encoding, 26,079 bytes when the client sent Accept-Encoding: gzip. Do not combine it with the middleware or a proxy that also compresses: double compression produces ERR_CONTENT_DECODING_FAILED.
Outgoing calls: Laravel's HTTP client is Guzzle, whose decode_content option defaults to true ("any gzipped or deflated response will be decoded by Guzzle"):
<?php
namespace App\Services;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
/**
* Laravel's HTTP client is Guzzle underneath. Guzzle's `decode_content`
* option defaults to true: gzip/deflate responses are decoded for you.
*/
class HttpClientCompression
{
/** Normal call: ask for gzip, read plain JSON. */
public function fetchJson(string $url): array
{
return Http::withHeaders(['Accept-Encoding' => 'gzip'])
->timeout(10)
->get($url)
->throw()
->json();
}
/** Keep the compressed bytes, e.g. to store an archive as-is. */
public function fetchRawGzip(string $url): Response
{
return Http::withHeaders(['Accept-Encoding' => 'gzip'])
->withOptions(['decode_content' => false])
->get($url);
}
/** Send a compressed request body (the server must support it). */
public function pushLogs(string $url, array $events): Response
{
$ndjson = implode("\n", array_map('json_encode', $events))."\n";
return Http::withHeaders(['Content-Encoding' => 'gzip'])
->withBody(gzencode($ndjson, 6), 'application/x-ndjson')
->post($url);
}
}Caches, CDNs and Vary: Accept-Encoding
Without Vary (broken)
1 client A (gzip) -> CDN miss -> origin returns gzip -> CDN stores it under URL only
2 client B (no gzip) -> CDN hit -> receives gzip bytes it cannot decode -> garbage / ERR_CONTENT_DECODING_FAILED
With Vary: Accept-Encoding
3 CDN keys the object by URL + normalised Accept-Encoding -> A gets gzip, B gets identityRules: send Vary: Accept-Encoding on every negotiated response (nginx gzip_vary on, Caddy and gzhttp do it, both middlewares on this page do it); make strong ETags weak (W/"...") or suffix them when the bytes change, because a strong ETag promises byte-identical content; never compress Range responses on the fly unless you know what you are doing (gzhttp drops Accept-Ranges by default for that reason). CDN normalisation and cache keys are in CDNs and Caching.
BREACH and CRIME: never compress secrets next to attacker input
In plain words: compression makes output shorter when the same text appears twice. If an attacker can put a guess into a page that also contains a secret, and can observe the encrypted response length, a correct guess makes the response a few bytes shorter. Repeat character by character and the secret leaks, TLS or not.
Common misunderstanding: "TLS protects us, the bytes are encrypted." Encryption hides content, not length. CRIME used TLS-level and SPDY header compression; BREACH (2013) used ordinary HTTP response compression. TLS 1.3 removed compression (legacy_compression_methods "MUST contain exactly one byte, set to zero"), and HTTP/2's HPACK was designed after CRIME ("limits vulnerability to known security attacks"), but body compression is still your decision.
Definition (Gluck, Harris, Prado, BREACH: Reviving the CRIME Attack): "Many web applications routinely deliver secrets – such as CSRF tokens – in the bodies of HTTP responses. It is also common for web applications to reflect user input – such as URL parameters – in HTTP response bodies. Since DEFLATE ... takes advantage of repeated strings to shrink the compressed payload, an attacker can use the the reflected URL parameter to guess the secret one character at a time."
BREACH, one guess per request (illustrative lengths; attacker controls ?q= and sees ciphertext length)
1 victim page contains: csrf=d634cda8... and reflects q
2 GET /search?q=csrf=a -> response length 2,431
3 GET /search?q=csrf=d -> response length 2,430 <- "csrf=d" matched: one byte shorter
4 GET /search?q=csrf=d6 -> repeat for the next character ... thousands of requests totalReal scenarios: an HTML page with a CSRF token and a search box that echoes the query; a JSON API that returns the user's API key alongside an attacker-controlled name field; an account page that shows the email and reflects a URL parameter.
| Mitigation (from the paper and practice) | Effect |
|---|---|
| Separate secrets from user input (the paper: give user input a compression context of its own, apart from secrets) | Solves it; may be impractical |
| Disable compression on responses that contain secrets and reflected input | Solves it for those routes |
Mask the secret per request: embed P and P XOR S with a fresh one-time pad P (the paper's "Masking Secrets") | The bytes on the wire never repeat, so guesses never match |
Length hiding / random padding (gzhttp RandomJitter) | Slows the attack (averaging defeats plain padding) |
| SameSite cookies, CSRF protection on GETs that reflect input, rate limiting | Removes the attacker's ability to drive the victim's requests |
Fix: keep compression on for static assets and for API responses without secrets; for authenticated HTML that reflects input, mask tokens or turn compression off on that route (nginx gzip off; in that location, Caddy encode with a match that excludes it). The nginx docs warn: "When using the SSL/TLS protocol, compressed responses may be subject to BREACH attacks." Security architecture is in OWASP Top 10.
Token masking in Go and Laravel (real run: two responses carry different strings, both verify):
// Command masktoken shows the BREACH "masking secrets" countermeasure: on
// every response embed P || (P XOR S) with a fresh one-time pad P, so the
// bytes on the wire never repeat even though the secret S does.
package main
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"log"
)
func mask(secret []byte) string {
pad := make([]byte, len(secret))
if _, err := rand.Read(pad); err != nil {
log.Fatal(err)
}
out := make([]byte, 2*len(secret))
copy(out, pad)
subtle.XORBytes(out[len(secret):], pad, secret)
return base64.RawURLEncoding.EncodeToString(out)
}
func unmask(token string) ([]byte, error) {
raw, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(raw)%2 != 0 {
return nil, fmt.Errorf("malformed token")
}
n := len(raw) / 2
secret := make([]byte, n)
subtle.XORBytes(secret, raw[:n], raw[n:])
return secret, nil
}
func main() {
secret := []byte("d634cda866f14c73ac135ae858c0d894") // the CSRF token from the BREACH paper
a, b := mask(secret), mask(secret)
fmt.Println("response 1:", a)
fmt.Println("response 2:", b) // different bytes every time
got, err := unmask(b)
if err != nil {
log.Fatal(err)
}
fmt.Println("verifies:", subtle.ConstantTimeCompare(got, secret) == 1)
}<?php
namespace App\Support;
/**
* BREACH "masking secrets": embed P . (P XOR S) with a fresh pad P per
* response, so a compressed page never repeats the secret's bytes.
*/
final class BreachSafeToken
{
public static function mask(string $secret): string
{
$pad = random_bytes(strlen($secret));
return rtrim(strtr(base64_encode($pad.($pad ^ $secret)), '+/', '-_'), '=');
}
public static function unmask(string $token): ?string
{
$raw = base64_decode(strtr($token, '-_', '+/'), true);
if ($raw === false || strlen($raw) % 2 !== 0) {
return null;
}
$n = intdiv(strlen($raw), 2);
return substr($raw, 0, $n) ^ substr($raw, $n);
}
public static function verify(string $token, string $secret): bool
{
$got = self::unmask($token);
return $got !== null && hash_equals($secret, $got);
}
}Accepting compressed input safely: decompression bombs
In plain words: a tiny compressed file can expand into gigabytes. If your server decompresses a request body, an uploaded archive or a message without a limit on the output, one request can exhaust memory or disk.
Common misunderstanding: "client_max_body_size 1m protects me." It limits compressed bytes. Our 971,976-byte bomb.gz expands to 1,000,000,000 bytes (1,029:1, close to DEFLATE's ceiling of about 1,030:1 since one 258-byte match costs at least 2 bits); Brotli squeezed the same gigabyte of zeros into 788 bytes, bzip2 into 722, zstd -19 into 30,741.
Definition: a decompression bomb (zip bomb) is input whose decompressed size or resource use is far larger than its compressed size; variants include nested archives, overlapping zip entries, and zstd frames that declare a huge window.
POST /ingest with Content-Encoding (Go safedecompress, real output)
1 ok.gz 542,432 B -> 200 "accepted 3000000 decoded bytes"
2 bomb100m.gz 97,221 B -> 413 "decompressed body too large"
3 bomb100m.zst 3,084 B -> 413 "decompressed body too large"
4 bomb.gz 971,976 B -> 413 "decompressed body too large" (1 GB inside, under the 1 MiB wire cap)
5 Content-Encoding: br -> 415, Accept-Encoding: gzip, zstdReal scenarios: log/metrics ingestion endpoints that accept gzip bodies, file upload of .zip for import, Kafka consumers decompressing batches, image libraries (PNG is zlib inside), a Laravel job that gzdecode()s a payload from a third party.
| Layer | Guard |
|---|---|
| Wire | nginx client_max_body_size, Go http.MaxBytesReader |
| Decoder output | Count bytes produced; fail above a cap (Go wrapper below; PHP gzdecode($s, $max), inflate_add loop) |
| Decoder memory | zstd WithDecoderMaxWindow, WithDecoderMaxMemory, CLI --memory; RFC 8878: "a decoder is allowed to reject a compressed frame that requests a memory size beyond the decoder's authorized range" |
| Archives | Limit entry count, per-entry and total uncompressed size, reject .. paths (zip slip) |
| Time | Request timeout, job timeout |
// Command safedecompress accepts gzip- or zstd-encoded request bodies and
// refuses decompression bombs: it caps the bytes read from the wire AND the
// bytes produced by the decoder, and bounds zstd's window memory.
package main
import (
"compress/gzip"
"errors"
"fmt"
"io"
"log"
"net/http"
"github.com/klauspost/compress/zstd"
)
const (
maxWire = 1 << 20 // 1 MiB compressed
maxDecoded = 10 << 20 // 10 MiB after decompression
)
var errTooLarge = errors.New("decoded body exceeds limit")
// limitedReader fails loudly instead of silently truncating like io.LimitReader.
type limitedReader struct {
r io.Reader
remaining int64
}
func (l *limitedReader) Read(p []byte) (int, error) {
if l.remaining <= 0 {
// Probe one byte: exactly-at-limit bodies are fine.
var one [1]byte
if n, _ := l.r.Read(one[:]); n > 0 {
return 0, errTooLarge
}
return 0, io.EOF
}
if int64(len(p)) > l.remaining {
p = p[:l.remaining]
}
n, err := l.r.Read(p)
l.remaining -= int64(n)
return n, err
}
func decodedBody(w http.ResponseWriter, r *http.Request) (io.Reader, func(), error) {
wire := http.MaxBytesReader(w, r.Body, maxWire)
switch r.Header.Get("Content-Encoding") {
case "", "identity":
return wire, func() {}, nil
case "gzip":
zr, err := gzip.NewReader(wire)
if err != nil {
return nil, nil, err
}
return &limitedReader{r: zr, remaining: maxDecoded}, func() { zr.Close() }, nil
case "zstd":
zr, err := zstd.NewReader(wire,
zstd.WithDecoderMaxWindow(8<<20), // RFC 8878 recommends supporting 8 MB
zstd.WithDecoderMaxMemory(maxDecoded), // cap on declared/decoded size
zstd.WithDecoderConcurrency(1))
if err != nil {
return nil, nil, err
}
return &limitedReader{r: zr, remaining: maxDecoded}, zr.Close, nil
default:
return nil, nil, fmt.Errorf("unsupported Content-Encoding %q", r.Header.Get("Content-Encoding"))
}
}
func ingest(w http.ResponseWriter, r *http.Request) {
body, done, err := decodedBody(w, r)
if err != nil {
// RFC 9110: 415 plus Accept-Encoding tells the client what we take.
w.Header().Set("Accept-Encoding", "gzip, zstd")
http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
return
}
defer done()
n, err := io.Copy(io.Discard, body)
var mbe *http.MaxBytesError
switch {
case errors.As(err, &mbe):
http.Error(w, "compressed body too large", http.StatusRequestEntityTooLarge)
case errors.Is(err, errTooLarge):
http.Error(w, "decompressed body too large", http.StatusRequestEntityTooLarge)
case err != nil:
http.Error(w, "bad body: "+err.Error(), http.StatusBadRequest)
default:
fmt.Fprintf(w, "accepted %d decoded bytes\n", n)
}
}
func main() {
http.HandleFunc("POST /ingest", ingest)
log.Println("listening on :8081")
log.Fatal(http.ListenAndServe(":8081", nil))
}<?php
namespace App\Support;
use RuntimeException;
/**
* Decompress an untrusted gzip/zlib/raw-deflate body in chunks and stop as
* soon as the output passes a limit, instead of allocating it all first.
*/
final class SafeInflate
{
/**
* @param int $encoding ZLIB_ENCODING_GZIP, ZLIB_ENCODING_DEFLATE (zlib) or ZLIB_ENCODING_RAW
*/
public static function decode(string $compressed, int $maxBytes = 10_000_000, int $encoding = ZLIB_ENCODING_GZIP): string
{
$ctx = inflate_init($encoding);
if ($ctx === false) {
throw new RuntimeException('inflate_init failed');
}
$out = '';
// One 8 KiB input chunk can expand ~1000x, so the overshoot is bounded (~8 MiB).
foreach (str_split($compressed, 8192) as $chunk) {
$piece = inflate_add($ctx, $chunk, ZLIB_SYNC_FLUSH);
if ($piece === false) {
throw new RuntimeException('corrupt compressed data');
}
$out .= $piece;
if (strlen($out) > $maxBytes) {
throw new RuntimeException("decompressed size exceeds {$maxBytes} bytes");
}
}
if (inflate_get_status($ctx) !== ZLIB_STREAM_END) {
throw new RuntimeException('truncated compressed data');
}
return $out;
}
}Small payloads: zstd dictionaries
Per-message compression of 200-byte JSON events saved 17% with plain zstd and 54-66% with a trained dictionary (real numbers in Dictionary compression). The Go program trains with dict.BuildZstdDict, compresses with WithEncoderDict, decodes with WithDecoderDicts, and the saved dictionary works with the zstd CLI (zstd -D events.dict), which proves it is a standard zstd dictionary:
// Command dictionary trains a zstd dictionary on small JSON events and
// compares per-event compression with and without it. Small payloads give
// the compressor no history to learn from; the dictionary is that history.
package main
import (
"encoding/json"
"fmt"
"log"
"math/rand/v2"
"os"
"github.com/klauspost/compress/dict"
"github.com/klauspost/compress/zstd"
)
type event struct {
Type string `json:"type"`
OrderID int `json:"order_id"`
UserID int `json:"user_id"`
Status string `json:"status"`
Amount float64 `json:"amount"`
Currency string `json:"currency"`
Country string `json:"country"`
CreatedAt string `json:"created_at"`
TraceID string `json:"trace_id"`
}
func makeEvents(r *rand.Rand, n int) [][]byte {
types := []string{"order.created", "order.paid", "order.shipped", "order.cancelled"}
statuses := []string{"pending", "paid", "shipped", "cancelled"}
countries := []string{"IR", "DE", "NL", "TR", "AE"}
out := make([][]byte, n)
for i := range out {
k := r.IntN(len(types))
e := event{
Type: types[k], OrderID: 1_000_000 + r.IntN(9_000_000), UserID: r.IntN(500_000),
Status: statuses[k], Amount: float64(r.IntN(10_000_000)) / 100, Currency: "EUR",
Country: countries[r.IntN(len(countries))],
CreatedAt: fmt.Sprintf("2026-11-25T%02d:%02d:%02dZ", r.IntN(24), r.IntN(60), r.IntN(60)),
TraceID: fmt.Sprintf("%016x%016x", r.Uint64(), r.Uint64()),
}
b, err := json.Marshal(e)
if err != nil {
log.Fatal(err)
}
out[i] = b
}
return out
}
func main() {
r := rand.New(rand.NewPCG(1, 2))
train := makeEvents(r, 5000)
test := makeEvents(r, 1000)
d, err := dict.BuildZstdDict(train, dict.Options{MaxDictSize: 16 << 10, HashBytes: 6, ZstdDictID: 1001})
if err != nil {
log.Fatal(err)
}
if len(os.Args) > 1 {
// Optional: save it so `zstd -D <file>` can use the same dictionary.
if err := os.WriteFile(os.Args[1], d, 0o644); err != nil {
log.Fatal(err)
}
}
plain, _ := zstd.NewWriter(nil, zstd.WithEncoderLevel(zstd.SpeedDefault))
withDict, _ := zstd.NewWriter(nil, zstd.WithEncoderLevel(zstd.SpeedDefault), zstd.WithEncoderDict(d))
dec, _ := zstd.NewReader(nil, zstd.WithDecoderDicts(d))
defer dec.Close()
var raw, sizePlain, sizeDict int
for _, ev := range test {
a := plain.EncodeAll(ev, nil)
b := withDict.EncodeAll(ev, nil)
back, err := dec.DecodeAll(b, nil)
if err != nil || string(back) != string(ev) {
log.Fatalf("round trip failed: %v", err)
}
raw += len(ev)
sizePlain += len(a)
sizeDict += len(b)
}
n := float64(len(test))
fmt.Printf("dictionary: %d bytes, id %d\n", len(d), 1001)
fmt.Printf("sample event: %s\n", test[0])
fmt.Printf("avg raw event: %6.1f bytes\n", float64(raw)/n)
fmt.Printf("avg zstd, no dict: %6.1f bytes (ratio %.2f)\n", float64(sizePlain)/n, float64(raw)/float64(sizePlain))
fmt.Printf("avg zstd, with dict: %6.1f bytes (ratio %.2f)\n", float64(sizeDict)/n, float64(raw)/float64(sizeDict))
}For PHP, the official image has no zstd; the PECL ext-zstd adds zstd_compress() / zstd_uncompress() and dictionary variants (zstd_compress_dict()), and zlib preset dictionaries work out of the box via deflate_init(ZLIB_ENCODING_DEFLATE, ['dictionary' => $dict]). If you cannot share a dictionary, batch: 50 events in one frame compress almost as well as a file of them.
The zlib preset dictionary in plain PHP (real output in php:8.5-cli-alpine: raw 211 B, zlib 166 B, zlib + preset dictionary 92 B, round trip ok; gzuncompress() without the dictionary returns false):
<?php
// zlib preset dictionary with plain ext-zlib (no PECL): both sides load the
// same bytes before the first message, so small JSON events compress well.
$dict = '{"type":"order.created","order_id":,"user_id":,"status":"pending","amount":,'
.'"currency":"EUR","country":"DE","created_at":"2026-11-25T","trace_id":"'
.'"type":"order.paid","status":"paid""type":"order.shipped","status":"shipped"';
$event = '{"type":"order.shipped","order_id":3424907,"user_id":259293,"status":"shipped",'
.'"amount":55204.91,"currency":"EUR","country":"DE",'
.'"created_at":"2026-11-25T13:33:07Z","trace_id":"f782bf187bf152ecc66593619a39a5c4"}';
$plain = gzcompress($event, 9);
$ctx = deflate_init(ZLIB_ENCODING_DEFLATE, ['level' => 9, 'dictionary' => $dict]);
$withDict = deflate_add($ctx, $event, ZLIB_FINISH);
$inflate = inflate_init(ZLIB_ENCODING_DEFLATE, ['dictionary' => $dict]);
$back = inflate_add($inflate, $withDict, ZLIB_FINISH);
printf("raw %d B, zlib %d B, zlib + preset dictionary %d B, round trip %s\n",
strlen($event), strlen($plain), strlen($withDict), $back === $event ? 'ok' : 'FAILED');
// Without the dictionary the stream cannot be read (FDICT bit is set).
var_dump(@gzuncompress($withDict));Databases and storage
PostgreSQL compresses individual column values through TOAST once a row is wider than about 2 kB; you choose the codec per column. Real session on PostgreSQL 18.6 (postgres:18-alpine):
SHOW default_toast_compression; -- pglz (PostgreSQL 18 default; 19 defaults to lz4 when built with it)
CREATE TABLE docs (
id int PRIMARY KEY,
body_pglz text COMPRESSION pglz,
body_lz4 text COMPRESSION lz4
);
-- 2,000 rows, each about 9 KB of NDJSON
INSERT INTO docs
SELECT g, r, r
FROM generate_series(1, 2000) g,
LATERAL (SELECT string_agg(format('{"ts":%s,"level":"info","service":"orders-api","path":"/api/orders/%s","status":200}',
g*1000+i, (g*i)%977), E'\n') AS r
FROM generate_series(1, 100) i) s;
SELECT octet_length(body_pglz) AS raw,
pg_column_size(body_pglz) AS pglz, pg_column_compression(body_pglz) AS m1,
pg_column_size(body_lz4) AS lz4, pg_column_compression(body_lz4) AS m2
FROM docs WHERE id = 1;
-- raw | pglz | m1 | lz4 | m2
-- 8691 | 939 | pglz | 1087 | lz4
SELECT sum(pg_column_size(body_pglz)) AS pglz_total,
sum(pg_column_size(body_lz4)) AS lz4_total,
sum(octet_length(body_lz4)) AS raw_total FROM docs;
-- pglz_total | lz4_total | raw_total
-- 1944146 | 2255918 | 18064541
-- 6,400 bytes of md5 hex: 4 bits of entropy per byte but no repeats
INSERT INTO docs VALUES (9001, (SELECT string_agg(md5(i::text), '') FROM generate_series(1,200) i), NULL);
SELECT pg_column_size(body_pglz), pg_column_compression(body_pglz) FROM docs WHERE id = 9001;
-- 6400 | (null) -> stored uncompressed: pglz has no entropy stage to exploit the 16-symbol alphabet
-- SET COMPRESSION: old values keep pglz; a copied value keeps its old compression; a new value uses lz4
ALTER TABLE docs ALTER COLUMN body_pglz SET COMPRESSION lz4;
INSERT INTO docs SELECT 9002, body_pglz, NULL FROM docs WHERE id = 1;
INSERT INTO docs SELECT 9003, body_pglz || ' ', NULL FROM docs WHERE id = 1;
SELECT id, pg_column_compression(body_pglz) FROM docs WHERE id IN (1, 9002, 9003) ORDER BY id;
-- 1 | pglz
-- 9002 | pglz <- INSERT ... SELECT copied the already-compressed datum
-- 9003 | lz4 <- a new value
-- STORAGE EXTERNAL: new values are stored out of line without compression
ALTER TABLE docs ALTER COLUMN body_lz4 SET STORAGE EXTERNAL;
INSERT INTO docs SELECT 9004, NULL, body_lz4 || ' ' FROM docs WHERE id = 2;
SELECT id, octet_length(body_lz4), pg_column_size(body_lz4), pg_column_compression(body_lz4)
FROM docs WHERE id IN (2, 9004) ORDER BY id;
-- 2 | 8746 | 1030 | lz4
-- 9004 | 8747 | 8747 | (null)
SET wal_compression = zstd; -- superuser or SET privilege; compresses full-page images in WAL
SHOW wal_compression; -- zstdWhat this shows: lz4 was 16% larger than pglz on this data (lz4 is chosen for CPU, not ratio; measure both on your data); SET COMPRESSION "does not cause the table to be rewritten", and the manual's warning that values copied by INSERT ... SELECT "may retain its existing compression method" is exactly what row 9002 shows; incompressible values are kept raw. STORAGE EXTERNAL is the right setting for already-compressed blobs (or for bytea you want to read by substring fast). The same script is in docs/snippets/foundations/compression/sql/toast.sql.
| Engine | What to do |
|---|---|
| PostgreSQL | lz4 for large JSON/text columns when CPU matters more than ratio, STORAGE EXTERNAL for already-compressed blobs, wal_compression = lz4 or zstd on write-heavy primaries, pg_dump -Fc --compress=zstd for dumps |
| MongoDB | Keep snappy for hot collections; zstd (storage.wiredTiger.collectionConfig.blockCompressor: zstd, or per collection at creation) for cold or large collections; put zstd first in net.compression.compressors across regions |
| Cassandra / ScyllaDB | Keep LZ4Compressor; lower chunk_length_in_kb (e.g. 4) for point-read-heavy tables, raise it for scans; ZstdCompressor for archive tables; watch SSTable Compression Ratio in nodetool tablestats |
| Redis | Values are stored as you send them: compress large values client-side (zstd/lz4 with a dictionary for small JSON); rdbcompression yes only affects snapshot files |
| Columnar (Parquet, ClickHouse, warehouse) | Sort by low-cardinality columns first; let encodings (dictionary, RLE, delta) do most of the work, then ZSTD on pages |
Kafka and message brokers: compress the batch
Producer -> broker -> consumer with compression.type=zstd (producer side)
1 app send(record) -> accumulator for partition P
2 wait until batch.size (16384) or linger.ms (5) -> one RecordBatch of N records
3 compress the whole batch -> zstd frame (level compression.zstd.level=3)
4 broker stores the batch as-is if topic compression.type=producer (default) -> no broker CPU
5 consumer fetches the batch -> decompresses once -> N records
If the topic sets compression.type=gzip while producers send zstd:
6 broker decompresses and recompresses every batch -> broker CPU, and per-batch checksKafka's docs: "Compression is of full batches of data, so the efficacy of batching will also impact the compression ratio (more batching means better compression)." Ten 200-byte events in one batch compress like a 2 KB document; one event per batch compresses like our 200-byte example (barely). linger.ms (default 5 since Kafka 4.0) and batch.size therefore change your compression ratio. zstd and lz4 are the usual choices; gzip costs the most CPU. For RabbitMQ and Redis Streams this page assumes application-level compression: compress the body yourself and set a header or field (content-encoding: zstd) so consumers know. Details: Kafka in Depth.
Logs and backups
| Data | Recommendation | Why |
|---|---|---|
| Rotated logs (logrotate) | compress + compresscmd /usr/bin/zstd, compressext .zst, or gzip delaycompress | zstd -3 is ~6x faster than gzip -6 at similar ratio on logs |
| Log shipping (Vector, Fluent Bit, OTel Collector) | zstd or gzip on the HTTP/gRPC exporter | Network is the bottleneck between regions |
| Log storage (Loki, Elasticsearch, ClickHouse) | Engine-native (chunks/stored fields) | Already compressed; do not double-compress |
pg_dump, mysqldump | pg_dump -Fc --compress=zstd:level=10 / mysqldump | zstd -T0 -10 | Pipe-friendly, multi-core, fast restore |
| Large backups to object storage | zstd -T0 --long=27 -10 then encrypt (age, KMS) | Compress before encrypting |
| VM / disk images | zstd --long, or sparse-aware tools | Long-range repeats |
Observability pipelines are covered in Observability; backup strategy in Backup, PITR & DR.
Archives and analytics file formats: zip vs tar.gz, Parquet
| Format | Compression unit | Random access | Typical codec | Use |
|---|---|---|---|---|
| zip | Each file | Yes (central directory) | DEFLATE (zstd and others in newer APPNOTE methods) | Downloads users open, jars, office documents |
| tar.gz / tar.zst / tar.xz | Whole archive | No | gzip / zstd / xz | Source releases, backups, Docker layer tarballs |
| Parquet | Column chunk pages | Yes, by row group and column | SNAPPY, ZSTD, GZIP, LZ4_RAW, BROTLI | Analytics; read only the columns you need |
| ORC / Arrow IPC | Stripes / buffers | Yes | zstd, lz4 | Analytics, IPC |
| zstd seekable | Frames + seek table | Yes | zstd | Large logs queried by offset |
Parquet's spec defines the codecs (UNCOMPRESSED, SNAPPY, GZIP, LZ4_RAW, ZSTD, BROTLI, deprecated LZ4) and notes GZIP is “based on the GZIP format (not the closely-related “zlib” or “deflate” formats)”. Column encodings (dictionary, RLE, delta) run before the codec and are covered in OLTP vs OLAP & Columnar Storage.
When NOT to compress
| Situation | Why not | Instead |
|---|---|---|
| Already-compressed media and archives (JPEG, PNG, WebP, AVIF, MP4, zip, gz, pdf with images) | Ratio ~1.00; CPU wasted | Exclude by content type / magic bytes |
| Encrypted data | Ratio ≤ 1.00 | Compress before encryption, or not at all |
| Tiny payloads (< ~1 KB) | Header and trailer outweigh savings; latency of a flush | Minimum length; batching; dictionaries |
| CPU-bound service at its limit | Compression steals the CPU you are short of | Offload to proxy/CDN, use lz4/zstd -1, or skip |
| Same datacenter, fast network, small messages | Bytes are cheap, CPU and latency are not | Measure; often lz4 or nothing |
| Responses mixing secrets and reflected input | BREACH | Mask secrets or disable per route |
| Data needing random writes in place | Compressed blocks must be rewritten | Block compression with small blocks, or none |
| Already compressed by another layer | Double work, e.g. app-level zstd payloads inside zstd Kafka batches | Compress once, at the layer with the biggest batch |
Troubleshooting
| Symptom | Likely cause | Check | Fix |
|---|---|---|---|
Browser shows garbage or ERR_CONTENT_DECODING_FAILED | Body compressed twice (app + proxy, or zlib.output_compression + middleware), or header says gzip but body is not | curl -s -H 'Accept-Encoding: gzip' URL | xxd | head -1 should start 1f8b exactly once | Compress in one layer only; nginx proxy_set_header Accept-Encoding "" makes the app send identity |
| Responses are not compressed at all | Content type not listed (nginx default only text/html, Caddy default list lacks application/x-ndjson), body under min length, proxied request with gzip_proxied off | curl -sD - -o /dev/null -H 'Accept-Encoding: gzip' URL | Add gzip_types, gzip_proxied any, or a Caddy match |
| Some clients get gzip they cannot read via a CDN/cache | Missing Vary: Accept-Encoding | Response headers | gzip_vary on; set Vary in middleware |
gzip: invalid header / zlib: invalid header | Wrong wrapper, or an HTML error page instead of compressed data | xxd -l 4 | Match reader to magic bytes; zlib_decode() / inflate_init with the right encoding |
unexpected EOF at the end | Truncated download, writer not Close()d | Size vs gzip -l; did your code call Close()? | Always defer w.Close() and check its error |
| CPU spike after enabling compression | High level on the fly (brotli 11, gzip 9, zstd 19) | Profile; gzip_comp_level | Level 4-6 for gzip/br on the fly, zstd 1-3; pre-compress statics |
| SSE / streaming response arrives all at once | Compressor buffers until it has enough bytes; proxy buffering | Watch with curl -N | Flush() the compressor (Go), ZLIB_SYNC_FLUSH (PHP), X-Accel-Buffering: no, or exclude text/event-stream |
| OOM when receiving uploads | Decompression bomb, io.ReadAll on a decoder | Memory graph per request | Cap decoded bytes, zstd WithDecoderMaxMemory |
Dictionary mismatch | Consumer lacks the dictionary ID the frame names | zstd -lv file shows DictID | Ship dictionaries with versions, keep old ones |
| Kafka ratio poor | Batches tiny (linger.ms 0, low traffic per partition) | Producer metrics for compression rate and average batch size | Raise linger.ms / batch.size, fewer partitions per producer |
Postgres table still large after SET COMPRESSION lz4 | Only new values use it | pg_column_compression(col) | Rewrite (UPDATE ... SET col = col || '', VACUUM FULL, or dump/restore) |
.tar.gz slow to extract one file | Whole-stream compression | - | zip or seekable zstd for random access |
Same input, different .gz hash across builds | MTIME / filename in the gzip header; different zlib versions | xxd -l 10 | gzip -n, pin the tool, or hash the uncompressed content |
Choosing a codec and a level
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Dynamic API JSON / HTML to browsers | gzip level 4-6 at the proxy; zstd or br 4-5 if the proxy supports it | Vary, min length 1 KB, exclude secrets + reflected input | Universal support; cheap enough per request |
| Static JS/CSS/SVG/fonts | brotli -q 11 + zstd -19 + gzip -9 pre-compressed | gzip_static, brotli_static, Caddy precompressed | Pay once at build |
| Service-to-service RPC in one region | none or lz4/snappy; gRPC gzip only for big messages | Measure p99 | Network is cheap, latency is not |
| Cross-region or mobile traffic | zstd -3 or gzip -6 | Dictionaries for small messages | Bytes are expensive |
| Kafka | zstd (ratio) or lz4 (CPU) at the producer | linger.ms 5-50, batch.size 64-256 KiB, topic compression.type=producer | Batch compression; broker passes through |
| OLTP database storage | Engine default (lz4/snappy) | Small chunks for point reads | Decompress on every read |
| Analytics / Parquet | ZSTD (or SNAPPY for speed) | Sort and partition first | Encodings + codec |
| Logs on disk | zstd -3 (rotation), zstd -19 for archive | One file per stream | 5-6x faster than gzip at same ratio |
| Backups | zstd -T0 -10..19 --long | Compress, then encrypt | Fast restore matters |
| Software releases | xz -6/-9 or zstd -19 --long | Reproducible flags (-n, fixed mtime) | Written once, downloaded many times |
| Many tiny records (< 1 KB) | zstd with a trained dictionary, or batching | Dictionary IDs and versions | No history otherwise |
| Already-compressed / encrypted | Nothing | Detect by content type | Cannot shrink |
In architecture: from a single process to a distributed system
Compression is a local decision with global consequences: whoever compresses pays CPU, whoever decompresses must speak the format and guard memory, and every cache or proxy in between must know the response depends on Accept-Encoding.
Monolith: one process, one database
Everyday example: a Laravel shop behind nginx. nginx compresses HTML, JSON, CSS and JS (gzip on; gzip_comp_level 5; gzip_types ...; gzip_vary on;) and serves pre-built app.js.br/.gz; Laravel sends identity; the CSV export streams with deflate_init only if it bypasses nginx. Postgres TOAST compresses large jsonb order snapshots; pg_dump -Fc --compress=zstd runs nightly. Rule: one compression layer per hop, at the edge.
Production example (illustrative): a Go monolith serving 20k req/s on 8 cores: on-the-fly gzip -6 for 20 KB average responses cost measurable CPU, so static assets moved to build-time Brotli, API responses stayed at gzip -4 via gzhttp with MinSize(1024), and the account page with CSRF token and a reflected ?q= was excluded (BREACH).
Modular monolith and multiple databases
Modules share one process, so compression belongs in shared infrastructure, not in each module: one HTTP middleware or proxy config; one helper for compressed cache values (e.g. CompressedCache::put($key, $value) using zstd/gzip with a format prefix byte so you can change codec later); each module's database chooses its own storage compression (reporting module on columnar ZSTD, orders on Postgres lz4). Write the format into the data (content-encoding column, magic bytes, or a version prefix), never assume it.
Microservices: what crosses service boundaries
Order service -> Kafka -> Invoice service -> S3, with compression at each hop
1 mobile app -> API gateway Accept-Encoding: gzip, br (gateway compresses responses, once)
2 gateway -> order-service HTTP/2, identity (same region: no compression)
3 order-svc -> Kafka topic orders compression.type=zstd, linger.ms=20 (batches of many events; ratio depends on batch size)
4 invoice-svc <- Kafka decompresses batch, reads events
5 invoice-svc -> S3 invoices/2026/11/25.ndjson.zst zstd -19 frames per hour (cold storage)
6 analytics <- S3 reads frames by hour (seekable)What survives a boundary is only what is declared: an HTTP Content-Encoding, a Kafka batch codec (in the batch header), a message header like content-encoding: zstd + dict-id: 1001 on RabbitMQ or Redis Streams, an object's Content-Encoding metadata in S3. Contracts to agree on: which codings each service accepts (Accept-Encoding on requests too, and 415 when unsupported), maximum decompressed size, dictionary distribution and versioning, and who compresses (never twice). gRPC has per-call compression (grpc-encoding: gzip) negotiated by grpc-accept-encoding. Service communication patterns are in Service Communication.
Distributed data: replicas, caches, CDNs, multi-region
- CDN and shared caches: objects are stored per encoding;
Vary: Accept-Encodingand normalised keys avoid both cache fragmentation and wrong-encoding hits. CDNs can compress at the edge from an identity origin, or pass through pre-compressed variants. - Database replication: PostgreSQL
wal_compressionshrinks full-page images in WAL, which reduces replication and archive traffic; MongoDB compresses intra-cluster traffic withnet.compression.compressors; Cassandra can compress internode traffic (internode_compression). - Caches: Redis stores what you give it; compressing large values client-side saves memory and network but makes values opaque to
GETRANGE/APPENDand Lua scripts. Keep a format prefix so readers can detect old uncompressed values during migration. - Multi-region object storage: zstd for anything crossing regions (egress is billed per byte); keep the codec in object metadata.
- Where it breaks: a dictionary rolled out to producers before consumers (
Dictionary mismatch), a cache that stored gzip under a URL withoutVary, a replica fed by a decoder with a smaller memory limit than the writer's window.
Scaling path: 1x, 10x, 100x
| Load | What changes |
|---|---|
| 1x | gzip at the proxy, defaults everywhere, pre-compressed assets. Measure response sizes and CPU. |
| 10x | Move on-the-fly compression to the CDN or a dedicated proxy tier; switch internal bulk paths (Kafka, logs, backups) to zstd; batch small messages; per-column lz4 in Postgres for large JSON. |
| 100x | Dictionaries for small hot payloads (shared via a registry with IDs); compression-aware capacity planning (CPU per GB compressed is a line item); seekable/columnar formats for data lakes; faster DEFLATE libraries (zlib-ng, libdeflate) where gzip is mandated; per-route BREACH review as part of security. |
Lab
Tools: gzip, brotli, zstd, lz4, xz, bzip2 (Homebrew or apt), Go 1.24+, Docker (for PostgreSQL, PHP, nginx and Caddy). All expected outputs below are the real ones from the machine this page was written on; yours will differ in speed, not in shape.
1. Build the corpus. (exactly the generator used for this page; same seed, same 146,573,164 bytes)
mkdir -p lab/corpus && cd lab && export CORPUS=$PWD/corpus
cat > genlogs.py <<'PY'
import json, random, sys
random.seed(42)
paths = ["/api/orders", "/api/orders/{id}", "/api/users/{id}", "/api/cart", "/api/payments", "/health", "/api/products", "/api/search"]
methods = ["GET", "GET", "GET", "POST", "PUT", "DELETE"]
levels = ["info"] * 8 + ["warn", "error"]
uas = ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36", "okhttp/4.12.0", "Go-http-client/1.1", "GuzzleHttp/7"]
out = open(sys.argv[1], "w")
t = 1764000000.0
for i in range(int(sys.argv[2])):
t += random.expovariate(50)
p = random.choice(paths).replace("{id}", str(random.randint(1, 99999)))
rec = {"ts": round(t, 3), "level": random.choice(levels), "service": "orders-api", "method": random.choice(methods), "path": p,
"status": random.choice([200, 200, 200, 201, 204, 400, 404, 500]), "duration_ms": round(random.lognormvariate(3, 0.8), 2),
"user_id": random.randint(1, 500000), "request_id": "%032x" % random.getrandbits(128), "ua": random.choice(uas),
"bytes": random.randint(80, 40000)}
out.write(json.dumps(rec, separators=(",", ":")) + "\n")
PY
python3 genlogs.py corpus/logs.jsonl 600000
head -c 4000000 /dev/urandom > corpus/random.bin
cp /System/Library/CoreServices/IconsetResources.bundle/Contents/Resources/Folder_512x512@2x.png corpus/image.png # macOS; any PNG works
for t in اصفهان ایران تاریخ_ایران تهران حافظ خلیج_فارس زبان_فارسی سعدی شاهنامه شیراز فردوسی مولوی; do # the 12 fa.wikipedia.org articles
curl -sG 'https://fa.wikipedia.org/w/api.php' --data-urlencode action=query --data-urlencode prop=extracts \
--data-urlencode explaintext=1 --data-urlencode format=json --data-urlencode formatversion=2 --data-urlencode "titles=$t" \
| python3 -c 'import json,sys; print(json.load(sys.stdin)["query"]["pages"][0]["extract"])' >> corpus/persian.txt
done
wc -c corpus/logs.jsonl # 146573164 corpus/logs.jsonl2. Measure entropy, then ratio and speed.
cd "$REPO/docs/snippets/foundations/compression/go" # REPO = your checkout of this site
go run ./entropy $CORPUS/logs.jsonl
# 146573164 bytes, 63 distinct byte values / order-0 entropy: 5.101 bits/byte / best order-0 ratio: 1.57:1
for c in "gzip -6" "zstd -T1 -3" "lz4 -1" "brotli -q 5"; do
/usr/bin/time -p sh -c "$c -c $CORPUS/logs.jsonl > /tmp/out" 2>&1 | grep real; ls -l /tmp/out
done
zstd -b1 -e5 -T1 $CORPUS/logs.jsonl # in-process benchmark; shows the level 2-4 dip
go run ./bench $CORPUS/logs.jsonl # the Go table in "Measured"3. Look at the bytes.
printf 'hello hello hello hello\n' > /tmp/hello.txt
gzip -n -c /tmp/hello.txt | xxd # 1f8b 0800 0000 0000 0003 cb48 cdc9 ... 0088 590b 1800 0000
zstd -q -f /tmp/hello.txt -o /tmp/hello.zst && xxd /tmp/hello.zst # 28b5 2ffd 2418 6d00 0038 ...
zstd -lv /tmp/hello.zst # Window Size: 24 B ... Check: XXH64 a82e7ca8
go run ./containers # raw / zlib / gzip from Go, and the "invalid header" errors
go run ./huffman abracadabra # 23 bits vs 22.44 entropy vs 88 ASCII
go run ./lz77 'abracadabra abracadabra'4. HTTP with and without Content-Encoding (Go and PHP).
go run ./httpgzip & # :8080 (ADDR=127.0.0.1:18080 to change)
until curl -s -o /dev/null 'localhost:8080/plain/export?n=1'; do sleep 0.5; done # wait for the server
curl -s -o /dev/null -w '%{size_download}\n' 'localhost:8080/mw/export?n=20000' # 1766580
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' 'localhost:8080/mw/export?n=20000' | grep -i encoding # Content-Encoding: gzip, Vary
curl -s -o /dev/null -H 'Accept-Encoding: gzip' -w '%{size_download}\n' 'localhost:8080/mw/export?n=20000' # 109079
go run ./httpclient # transparent decoding vs explicit header vs DisableCompression
# PHP: the same zlib that Laravel's middleware calls, served by php -S
mkdir -p phpapp && cat > phpapp/index.php <<'PHP'
<?php
header('Content-Type: application/json');
$rows = [];
for ($i = 0; $i < 5000; $i++) { $rows[] = ['id' => $i, 'status' => 'paid', 'currency' => 'EUR', 'total' => $i * 3 % 1000]; }
echo json_encode($rows);
PHP
docker run -d --rm --name php -p 8090:8000 -v "$PWD/phpapp:/app:ro" php:8.5-cli-alpine \
php -d zlib.output_compression=On -S 0.0.0.0:8000 -t /app
curl -s -o /dev/null -w '%{size_download}\n' localhost:8090/ # identity
curl -s -o /dev/null -H 'Accept-Encoding: gzip' -w '%{size_download}\n' localhost:8090/ # gzip, ~14x smaller5. Proxy compression (nginx and Caddy in front of the Go server).
docker run -d --rm --name ngx --add-host host.docker.internal:host-gateway -p 8091:80 -v "$PWD/../config/nginx.conf:/etc/nginx/nginx.conf:ro" nginx:alpine
docker run -d --rm --name cdy --add-host host.docker.internal:host-gateway -p 8092:80 -v "$PWD/../config/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2-alpine
for ae in gzip zstd; do
curl -s -D - -o /dev/null -H "Accept-Encoding: $ae" -w "%{size_download}\n" 'localhost:8092/plain/export?n=20000' | grep -iE 'content-encoding|^[0-9]'
done
# gzip -> 107533, zstd -> 55662 (Caddy). nginx without ngx_brotli/zstd modules: zstd request -> identity6. Dictionaries, bombs, PostgreSQL.
go run ./dictionary /tmp/events.dict # 174.0 B -> 96.3 B per event
go run ./safedecompress & # :8081
until curl -s -o /dev/null 'localhost:8081/'; do sleep 0.5; done
head -c 100000000 /dev/zero | gzip -9 > bomb.gz
curl -s -H 'Content-Encoding: gzip' --data-binary @bomb.gz localhost:8081/ingest # decompressed body too large (413)
docker run -d --rm --name pg -e POSTGRES_PASSWORD=pw postgres:18-alpine && sleep 5
docker exec -i pg psql -U postgres -X < ../sql/toast.sql # the script from "Databases and storage"Expected learning: logs shrink 4-8x and the level/codec choice moves you along a curve, not to a better point for free; PNG and random bytes do not shrink; headers explain why tiny inputs grow; HTTP compression needs Vary and a minimum size; a dictionary turns 200-byte messages from 1.2x into 2-3x; limits on decoded size are what stop bombs.
Common misconceptions
| Belief | Reality |
|---|---|
| "gzip, zlib and deflate are the same." | One DEFLATE stream, three wrappers: raw (none), zlib (2 B + Adler-32), gzip (10 B + CRC-32 + ISIZE). Readers reject each other's headers. |
"HTTP deflate is raw DEFLATE." | RFC 9110 says zlib-wrapped; some servers send raw. Use gzip. |
| "Higher level = always smaller." | zstd -1 beat zstd -3 on our logs; levels are search presets. Measure. |
| "Higher zstd level = slower decompression." | Decompression was 2,047-2,697 MB/s at -1/-3/-19. Only window size (memory) grows. |
| "Compression always helps." | PNG, JPEG, zip, encrypted and random data do not shrink; tiny payloads grow. |
| "Encrypt then compress is fine." | Ciphertext is incompressible. Compress first, and mind length leaks. |
| "TLS stops BREACH." | TLS hides content, not length. Separate or mask secrets, or disable compression on those routes. |
"client_max_body_size stops zip bombs." | It caps compressed bytes; cap decoded bytes and decoder memory too. |
| "Transfer-Encoding: gzip is how HTTP compresses." | Browsers use Content-Encoding; Transfer-Encoding is in practice only chunked, and RFC 9113 forbids it in HTTP/2. |
| "Brotli beats gzip everywhere." | At q11 it is ~1 MB/s to compress; at on-the-fly levels it is close to gzip; zstd decompresses faster. |
| "lz4/snappy are bad compressors." | They trade ratio for GB/s; that is the right trade inside databases and RPC. |
| "Entropy is a fixed property of a file." | It depends on the model; order-0 H promised 1.57x on logs, LZ77 delivered 5.5x. |
| "One zstd dictionary for all data." | Dictionaries are data-type specific; train one per message type and version them. |
| "Laravel compresses responses." | It does not; nginx/Caddy/CDN or your own middleware does. |
| "Setting a column to lz4 recompresses the table." | SET COMPRESSION affects future values only. |
Cheat sheet
| Topic | What to remember |
|---|---|
| Two families | Entropy coders (Huffman, arithmetic, ANS/FSE) + dictionary coders (LZ77, LZ78/LZW); real codecs chain both |
| Limit | Shannon entropy of your model; random/encrypted = 8 bits/byte = no gain |
| DEFLATE | LZ77 (32 KiB window, matches 3-258) + Huffman; blocks stored/fixed/dynamic |
| Wrappers | raw: none; zlib 78 9c + Adler-32; gzip 1f 8b 08 + CRC-32 + ISIZE; zip PK\3\4 per entry |
| Magic bytes | zstd 28 b5 2f fd, lz4 04 22 4d 18, xz fd 37 7a 58 5a 00, bzip2 BZh, Brotli none |
| Measured on logs | lz4 3.25x @3.6 GB/s; zstd -1 5.66x @1.1 GB/s; gzip -6 5.54x @134 MB/s; brotli 11 7.28x @1 MB/s; bzip2 7.66x @19 MB/s |
| zstd | Default 3; --fast, 1-19, --ultra 22; --long 128 MiB; frames, skippable frames, seekable format; dictionaries by ID |
| HTTP | Accept-Encoding / Content-Encoding / Vary: Accept-Encoding; compress at the proxy; pre-compress statics; min ~1 KB |
| nginx | gzip on; gzip_comp_level 5; gzip_min_length 1024; gzip_types ...; gzip_proxied any; gzip_vary on; + gzip_static |
| Caddy | encode zstd gzip (default), minimum_length 512, default match list; file_server precompressed |
| Go | compress/gzip, compress/flate, compress/zlib; klauspost zstd, gzhttp, s2, dict; andybalholm brotli; client decodes gzip itself |
| PHP / Laravel | gzencode/gzcompress/gzdeflate, zlib_encode, deflate_init+deflate_add, gzdecode($s, $max); Guzzle decode_content true; no built-in br/zstd |
| BREACH | Secret + reflected input + compression + observable length = leak |
| Bombs | ~1000:1 for gzip, far more for zstd/brotli/bzip2; cap decoded bytes and decoder memory |
| Databases | Postgres TOAST pglz/lz4 + wal_compression; Mongo snappy default; Cassandra LZ4 16 KiB chunks; Redis none for values |
| Kafka | Producer compresses batches; topic compression.type=producer; linger.ms/batch.size drive ratio |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Order-0 entropy of our JSON logs is 5.1 bits/byte, which bounds an order-0 coder at 1.57x. How did gzip reach 5.5x? Good to know
Answer
Answer: The bound is for a model that ignores context. LZ77 replaces repeated strings (keys, paths, service names) with back-references, a far stronger model; Huffman then codes the remaining tokens. See Entropy and LZ77.
2 — Why does a 4 MB file from /dev/urandom get larger under every codec? Must-know
Answer
Answer: By the pigeonhole principle no lossless code shrinks every input; random data has no redundancy, so codecs fall back to stored/raw blocks and still add headers, block markers and checksums. See Why random and encrypted data do not compress.
3 — Build the Huffman code for abracadabra. How many bits, and why is that above the entropy? Good to know
Answer
Answer: a=0, c=100, d=101, b=110, r=111: 23 bits. Entropy is 22.44 bits; Huffman must use whole bits per symbol, so it rounds up. Arithmetic coding or ANS can get closer. See Huffman coding.
4 — A client sends Content-Encoding: deflate and your zlib reader fails. What happened? Important
Answer
Answer: RFC 9110 defines deflate as zlib-wrapped, but some implementations send raw DEFLATE. Check the first bytes (78 xx = zlib); fall back to raw inflate or ask for gzip. See Containers.
5 — Name the three headers involved in HTTP compression and what each does. Must-know
Answer
Answer: Accept-Encoding (client: what I can decode), Content-Encoding (server: what I applied to this representation), Vary: Accept-Encoding (caches: key on that request header). See HTTP and Vary.
6 — Your page shows a CSRF token and echoes ?q=. Why is enabling gzip on it dangerous, and name two fixes. Important
Answer
Answer: BREACH: an attacker who drives the victim's requests and sees encrypted lengths can guess the token byte by byte, because a correct guess compresses better. Fix: mask the token per request, separate secrets from reflected input, or disable compression on that route. See BREACH.
7 — Your ingestion endpoint limits bodies to 1 MiB. Is it safe against bombs? Must-know
Answer
Answer: No. 1 MiB of gzip can hold ~1 GB; zstd and Brotli far more. Cap the decoded bytes (count while reading), cap decoder memory (zstd WithDecoderMaxMemory/window), and use timeouts. See Bombs.
8 — You compress each 200-byte Kafka event with zstd in the application and get 1.2x. What two changes help most? Important
Answer
Answer: Let the producer compress batches (compression.type=zstd with a non-trivial linger.ms / batch.size), or, if each message must stand alone, use a trained zstd dictionary (2.2-2.9x in our test). See Kafka and Dictionaries.
9 — Why do Cassandra and MongoDB default to lz4/snappy rather than gzip or zstd -19? Important
Answer
Answer: Storage engines decompress blocks on every read; lz4/snappy decompress at GB/s with low CPU, and block-level compression needs per-block speed more than ratio. See lz4 and snappy.
10 — You ran ALTER TABLE ... SET COMPRESSION lz4 but the table did not shrink. Why? Important
Answer
Answer: It applies to values written afterwards; existing TOAST values keep their method until rewritten. pg_column_compression() shows the method per value. See Databases.
11 — When is tar.gz the wrong choice compared to zip or seekable zstd? Good to know
Answer
Answer: When readers need one file or one range without decompressing everything before it; tar.gz is one stream. See Streaming vs block and Archives.
12 — Your Go client sets Accept-Encoding: gzip itself and now json.Decoder fails. Why? Must-know
Answer
Answer: Go's Transport only decodes transparently when it added the header. If you set it, you receive raw gzip and must wrap the body in gzip.NewReader. See the client snippet.
Glossary
| Term | Meaning |
|---|---|
| Compression ratio | Original size / compressed size (5.5 = 5.5x smaller) |
| Lossless | Decoder reproduces the exact input bytes |
| Lossy | Decoder reproduces an approximation (JPEG, MP3, lossy WebP/AVIF) |
| Shannon entropy | H = -Σ p log2 p: average information per symbol under a model; the lossless limit |
| Order-0 entropy | Entropy counting symbols without context |
| Redundancy | The predictable part of the data; what compression removes |
| Pigeonhole principle | Why no lossless method shrinks every input |
| Entropy coder | Assigns shorter codes to more probable symbols (Huffman, arithmetic, ANS) |
| Prefix code | No code is a prefix of another, so no separators are needed |
| Huffman coding | Optimal whole-bit prefix code from symbol frequencies (1952) |
| Canonical Huffman | Codes rebuilt from code lengths only, as DEFLATE transmits them |
| Arithmetic / range coding | Encodes a message as one number in an interval; fractional bits per symbol |
| ANS | Asymmetric numeral systems: arithmetic-coding precision with one integer state (Duda 2009) |
| FSE / tANS | Finite State Entropy, zstd's table-based ANS coder |
| Run-length encoding (RLE) | (count, symbol) for runs of equal symbols |
| Dictionary coder | Replaces repeats with references to earlier data |
| LZ77 | Sliding-window back-references (distance, length) + literals (1977) |
| LZ78 | Explicit phrase dictionary (index, next symbol) (1978) |
| LZW | LZ78 variant sending only indices; Unix compress, GIF |
| Sliding window | The recent output an LZ77 match may refer to (32 KiB in DEFLATE) |
| Literal | A byte emitted as itself |
| Match / back-reference | Copy length bytes from distance bytes back |
| Lazy matching | Encoder checks whether a match starting one byte later is longer |
| DEFLATE | LZ77 + Huffman format of RFC 1951 |
| BFINAL / BTYPE | DEFLATE block header bits: last block flag; stored / fixed / dynamic |
| zlib format | RFC 1950 wrapper: 2-byte header + DEFLATE + Adler-32 |
| gzip format | RFC 1952 wrapper: 10-byte header (+ optional name, comment, extra) + DEFLATE + CRC-32 + ISIZE |
| Adler-32 | zlib's fast checksum (see Checksums & Hashing) |
| CRC-32 | gzip's and zip's checksum |
| ISIZE | gzip trailer: uncompressed length mod 2^32 |
| Multi-member gzip | Several gzip members concatenated; readers treat them as one stream |
| zip | Archive with per-file compression and a central directory |
| tar.gz | A tar archive compressed as one gzip stream |
| Brotli | RFC 7932 codec: LZ77 + Huffman + context modelling + static dictionary |
| Static dictionary | Built-in shared data (Brotli's 122,784 bytes) both sides know |
| Zstandard (zstd) | RFC 8878 codec: LZ77 + Huffman + FSE, levels from --fast to 22 |
| Frame | zstd's self-contained unit: magic, header, blocks, optional checksum |
| Skippable frame | zstd frame with magic 0x184D2A5? that decoders ignore (metadata, padding) |
| Seekable format | zstd frames + seek table for random access |
| Long-distance matching | zstd --long: window up to 128 MiB+ |
| Trained dictionary | zstd dictionary built from samples (--train), referenced by ID |
| Preset dictionary | zlib FDICT / Go NewWriterDict / PHP dictionary option |
| Compression Dictionary Transport | RFC 9842: HTTP dcb/dcz codings using a previous response as dictionary |
| lz4 | Byte-aligned LZ77, no entropy stage; very fast |
| LZ4HC | lz4's high-compression match finder (higher levels), same decoder |
| snappy | Google's byte-oriented LZ77 codec, no entropy stage |
| S2 | klauspost's snappy extension; faster, can read snappy |
| xz / LZMA2 | Large-window LZ77 with a range coder; high ratio, slow |
| bzip2 | Burrows-Wheeler transform + MTF + RLE + Huffman |
| Burrows-Wheeler transform | Reversible sort that groups similar contexts |
| pglz | PostgreSQL's built-in LZ-family TOAST compressor |
| TOAST | PostgreSQL's storage of large column values (compressed and/or out of line) |
| Compression level | Encoder search-effort preset |
| Streaming compression | Stateful compression over an unbounded input |
| Block compression | Independent chunks; random access, lower ratio |
| Flush (sync flush) | Emit all buffered compressed data now without ending the stream |
| Content-Encoding | HTTP header: coding applied to the representation |
| Accept-Encoding | HTTP request header: codings the client accepts, with q-values |
| Transfer-Encoding | HTTP/1.1 message framing (chunked); not used for compression in practice |
| identity | The "no encoding" content coding |
| q-value | Preference weight 0-1 in Accept-Encoding; q=0 means not acceptable |
| Vary | Response header listing request headers that change the response |
| Weak ETag | W/"...": semantically equal, not byte-identical |
| BREACH | Length side channel on compressed HTTP responses (2013) |
| CRIME | Same idea against TLS/SPDY header compression (2012) |
| HPACK / QPACK | HTTP/2 / HTTP/3 header compression designed to resist CRIME |
| Decompression bomb | Small input that expands enormously |
http.MaxBytesReader | Go helper capping request body bytes |
gzhttp | klauspost's Go gzip/zstd HTTP handler and transport |
gzencode / gzcompress / gzdeflate | PHP functions for gzip / zlib / raw DEFLATE |
deflate_init / deflate_add | PHP incremental compression API |
zlib.output_compression | PHP ini: compress all output when the client accepts gzip |
decode_content | Guzzle option (default true) to decode compressed responses |
compression.type | Kafka producer/topic codec setting |
linger.ms / batch.size | Kafka producer batching knobs that drive compression ratio |
default_toast_compression | PostgreSQL default TOAST codec |
wal_compression | PostgreSQL WAL full-page image compression |
blockCompressor | MongoDB WiredTiger collection codec (snappy default) |
chunk_length_in_kb | Cassandra compression chunk size (16 KiB default) |
rdbcompression | Redis: LZF-compress strings in RDB snapshots |
list-compress-depth | Redis: compress inner quicklist nodes |
| Parquet codec | Page compression in Parquet: SNAPPY, GZIP, ZSTD, LZ4_RAW, BROTLI |
| pigz | Parallel gzip implementation |
| zlib-ng / libdeflate | Faster DEFLATE implementations |
| Magic number | Fixed leading bytes that identify a format |
References
- Shannon, C. E., "A Mathematical Theory of Communication", Bell System Technical Journal, 1948. PDF (Harvard mirror)
- Huffman, D. A., "A Method for the Construction of Minimum-Redundancy Codes", Proceedings of the IRE, 1952. PDF scan
- Ziv, J. and Lempel, A., "A Universal Algorithm for Sequential Data Compression", IEEE Trans. Information Theory, 1977. PDF; "Compression of Individual Sequences via Variable-Rate Coding", 1978. PDF; Welch, T., "A Technique for High-Performance Data Compression", 1984. PDF
- Duda, J., "Asymmetric numeral systems", arXiv:0902.0271 (2009). PDF; arXiv:1311.2540 abstract
- RFCs: 1950 zlib, 1951 DEFLATE, 1952 gzip, 7932 Brotli, 8878 Zstandard, 9110 HTTP Semantics, 9112 HTTP/1.1, 9842 Compression Dictionary Transport, 7541 HPACK, 8446 TLS 1.3
- Tools: pigz, zlib-ng, libdeflate, logrotate(8), xz(1), RFC 9113 HTTP/2
- Format docs: Zstandard README, zstd man page, zstd compression format, zstd seekable format, lz4 block format, lz4 frame format, snappy format, snappy framing, snappy README, Brotli README, .xz file format, bzip2 manual, PKWARE APPNOTE 6.3.9, PNG 3rd edition, Parquet compression
- BREACH: Gluck, Harris, Prado, "BREACH: Reviving the CRIME Attack" (2013). site, PDF
- Media formats: MDN image file type and format guide
- Browser support: MDN browser-compat-data, Content-Encoding, MDN Content-Encoding, MDN Accept-Encoding
- Servers: nginx ngx_http_gzip_module, gzip_static, gunzip, ngx_brotli, Caddy encode, Caddy file_server, gRPC compression
- Databases and brokers: PostgreSQL TOAST, client defaults (19), client defaults (18), WAL settings, ALTER TABLE, pg_dump; MongoDB WiredTiger, configuration options; Cassandra compression, cassandra.yaml; ScyllaDB CQL DDL; redis.conf; Kafka producer configs, topic configs; Elasticsearch index modules
- Go:
compress/gzip,compress/flate,compress/zlib,net/httpTransport, klauspost/compress README, zstd README, gzhttp README, zstd package, dict package, andybalholm/brotli, pierrec/lz4 (APIs checked withgo docagainst klauspost v1.18.0, brotli v1.3.0, lz4 v4.1.33) - PHP and Laravel: zlib book, gzencode, zlib_encode, gzdecode, deflate_init, inflate_init, zlib constants, zlib runtime configuration, php-ext-zstd, php-ext-brotli; Laravel 13 HTTP Client, Responses, Middleware; Guzzle request options