Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why we compress, and what it costsWhy compression exists
Shannon, Huffman, Ziv-Lempel, DEFLATE, Brotli, zstd: who and whenWhere it comes from
Entropy, redundancy, why random and encrypted data do not shrinkInformation theory you actually need
Lossless vs lossy (JPEG, MP3, WebP, AVIF)Lossless vs lossy
RLE, Huffman, arithmetic/ANS, LZ77, LZ78/LZW, one block eachThe concept catalogue
DEFLATE, raw vs zlib vs gzip, zip, Brotli, zstd, lz4, snappy, xz, bzip2Formats and codecs
Measured ratio and speed on JSON logs, Persian text, a PNG, random bytesMeasured: the speed / ratio / memory triangle
Magic numbers, hex dumps, DEFLATE token trace, every knob and error messageMechanics
HTTP compression, BREACH, bombs, small payloads, databases, Kafka, logs, archivesSolving the classic problems
Symptoms and fixesTroubleshooting
Which codec whereChoosing a codec and a level
Monolith to distributed systemIn architecture
Reproduce every number on your laptopLab
Wrong beliefs, a cheat sheet, every term definedMisconceptions, 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)FamilyRatioCompress MB/sDecompress MB/sWhere you meet it
lz4 -1LZ77, byte-aligned, no entropy stage3.2536263232Cassandra/ScyllaDB default, Kafka, PostgreSQL TOAST, RPC
snappy (Go, 9.8 MB)LZ77, byte-aligned3.377553376MongoDB WiredTiger default, Parquet default, Kafka
zstd -1LZ77 + Huffman + FSE (ANS)5.6611022121Kafka, backups, Parquet, HTTP zstd
zstd -3 (default)same5.337482047the general-purpose default today
gzip -6 (default)DEFLATE = LZ77 + Huffman5.541341619HTTP gzip, .gz, .tar.gz, PNG (zlib), zip
brotli -q 5LZ77 + Huffman + context modelling + static dictionary5.751291124HTTP br on the fly
brotli -q 11same7.281893pre-compressed web assets
zstd -19same as zstd -36.9942697archives, release artifacts, cold storage
xz -6LZMA2 (LZ77 + range coder)6.655176.tar.xz source releases, Linux packages
bzip2 -9Burrows-Wheeler + Huffman7.661987legacy archives; slow to decompress

HTTP rules.

HeaderMeaningRule
Accept-Encoding: gzip, br, zstdClient lists codings it can decode (with optional ;q=)Absent = anything goes; identity;q=0 = must encode
Content-Encoding: zstdThe representation was encoded; decode before using the media typeOne coding per response in practice; never twice
Vary: Accept-EncodingThe response depends on that request headerAlways send it when you negotiate, or caches serve gzip to clients that cannot read it
Transfer-Encoding: chunkedMessage 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.

SituationDo this
API JSON, HTML, JS, CSS, SVG over HTTPCompress at the proxy (nginx gzip, Caddy encode zstd gzip), level 4-6, min length ~1 KB, Vary: Accept-Encoding
Static assetsPre-compress at build time with brotli -q 11 and zstd -19, serve with gzip_static / brotli_static / Caddy precompressed
Logs, backups, Kafka, Parquetzstd (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 inputCap 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 compressionWith compression
Zero CPU per byteCPU on both ends: cheap decode, expensive encode at high levels
Bytes on the wire = bytes in memory3x-10x fewer bytes for text, JSON, logs; nothing saved for media
Random access to any offsetNeed block or frame boundaries (or a seek table) to read the middle
Easy debugging with tcpdump, cat, lessNeed zcat, zstdcat, curl --compressed
No new security surfaceLength 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 ​

  1. "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.
  2. "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).
  3. "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.

text
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:1

Real 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).

DataTypical order-0 HWhat a good codec reachesWhy
JSON / NDJSON logs5-5.5 bits/byte5-8xKeys, values and paths repeat: LZ77 wins far beyond order-0
English textnot measured heredepends on lengthShannon estimated "roughly 50%" redundancy from letter statistics alone; phrases repeat on top
Persian (UTF-8) text~4.1 bits/byte3.8-5.5xTwo bytes per letter, first byte nearly constant (0xD8-0xDB)
Hex / UUID strings~4 bits/byte~1.5-2x with Huffman; ~1x with lz4/pglzOnly 16 symbols, but no repeats
PNG, JPEG, MP4, zip, gz~7.95-8 bits/byte~1xAlready compressed
Encrypted / random8 bits/byte≤ 1xNo model predicts it

Fix / how to use it: measure before choosing. The Go snippet counts bytes and prints H0 and the order-0 bound:

go
// 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).

text
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 coder

Real 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.

text
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 happensWhat to do
Compressed (PNG, JPEG, WebP, MP4, zip, gz, docx, xlsx)Ratio ~1.00, CPU wastedExclude by content type or magic bytes
Encrypted (TLS payload, AES-GCM blob, age/gpg file)Ratio ≤ 1.00Compress before encrypting, or not at all
Random IDs, hashes, tokensSmall gain at bestDo 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).

text
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
FormatLossless?InsideNotes
PNGYesFilters + zlib (DEFLATE)Never gzip it again over HTTP
GIFYes (8-bit indexed colour)LZW ("GIF uses the Lempel-Ziv-Welch (LZW) algorithm")Same LZW family as RFC 9110's compress coding
JPEGNoDiscrete cosine transform"the most widely used lossy compression format for still images"
MP3, AAC, Opus (audio)NoPerceptual audio codingSame rule: lossy for media, never for data
WebPBothLossy and lossless modesWidely supported replacement for JPEG/PNG
AVIFBothAV1 bitstreams in a HEIF containerMDN: 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.

text
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 times

Real 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.

WhereHow runs are encoded
Parquet / ORCRLE + bit-packing hybrid for levels and dictionary indices
DEFLATE, zstd, lz4, snappyOverlapping match (distance 1 = repeat the last byte)
bzip2RLE before and after the Burrows-Wheeler transform
PNGFilters 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.

11624a: 5c: 1d: 1b: 2r: 2code 010010111011101010101merge order1. c(1) + d(1) = 22. b(2) + r(2) = 43. cd(2) + br(4) = 64. a(5) + 6 = 11cost5x1 + 2x3 + 1x3+ 1x3 + 2x3 = 23 bitsASCII: 88 bitsentropy: 22.44 bitsabracadabra11 symbols
text
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 bits

The 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.

ProductHuffman variant
DEFLATE (gzip, zlib, zip, PNG)Canonical, max 15-bit codes; fixed tables (BTYPE 01) or per-block dynamic tables (BTYPE 10)
BrotliCanonical prefix codes per block type and context
zstdHuffman for literals (max 11 bits); FSE for literal lengths, match lengths, offsets
HTTP/2 HPACK, HTTP/3 QPACKOne static Huffman table from the RFC, no per-message tables
JPEG baselineHuffman 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:

go
// 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."

text
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..n

Real 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.

CoderUsed bySpeedPrecision
HuffmanDEFLATE, Brotli, zstd literals, JPEG, HPACKVery fastWhole bits per symbol
Adaptive binary range coderxz / LZMA / LZMA2, 7zSlow (decompress ~176 MB/s here)Fractional bits, adaptive
tANS / FSEzstd sequences (and literal-length, match-length, offset codes)FastFractional 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.

search buffer (window): bytes already emittedlook-ahead bufferabracadabra␣abracadabra012345678910111213141516171819202122source: 11 bytes starting 12 backcursor at 12: 11 bytes to encodeemit match (distance 12, length 11) instead of 11 literalstoken stream the decoder replaysabracad(7, 4)␣(12, 11)literal: copy this bytematch (distance, length): copy length bytes from distance backDEFLATE: window 32 KiB, match length 3 to 258. zstd: window 8 MB recommended, more with --long.A match may overlap the cursor (distance 1, length 19 = a run of one byte repeated).
text
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 matches

Real 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).

CodecWindow (max distance)Min matchToken encoding
DEFLATE (gzip, zlib, zip)32 KiB3Huffman codes for literal/length and distance
Brotli1 KiB - 16 B to 16 MiB - 16 B2 (RFC 7932: minimum copy length two)Huffman, plus references into the 122,784-byte static dictionary
zstd1 KB to 3.75 TB in the format; 8 MB recommended; --long = 128 MiB3Literals (Huffman) + sequences (FSE)
lz465,535 bytes (max offset)4Byte-aligned tokens, no entropy stage
snappy~32 KiB in practice (the compressor works in 32 kB blocks)4Byte-aligned tags, no entropy stage
LZMA / xzdictionary up to 1.5 GiB (preset -6 = 8 MiB)not covered by the .xz container specRange-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.

go
// 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.

text
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") -> end

Real scenarios: reading legacy .Z archives and GIF images; understanding why GIF's LZW "was covered by patents until the early 2000s" (MDN); interview questions.

FormatAlgorithm
Unix compress, .Z, HTTP compress codingLZW
GIF, TIFF (LZW option), PDF LZWDecodeLZW
gzip, zip, PNG, zlibLZ77 (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.

input byteshello hellohello hello\n24 bytes1. LZ77 match finderhash chains, lazy matching32 KiB sliding windowlevel = how hard it searches(gzip -1 ... -9)2. tokensliteral 0-255length 3-258 (codes 257-285)distance 1-32768 (codes 0-29)end of block = 2563. Huffman + block framingtwo prefix codes: lit/len, distanceBTYPE 00 stored, 01 fixed,10 dynamic (tables in block)raw DEFLATE: 11 bytes cb 48 cd ...the same DEFLATE stream, three wrappersraw DEFLATE (RFC 1951)no header, no checksum11 bytesinside .zip entries (zip addsits own headers + CRC-32),PHP gzdeflate(), Go flate,WebSocket permessage-deflatezlib (RFC 1950)78 9c | DEFLATE | Adler-32 (BE)2 + 11 + 4 = 17 bytesPNG IDAT, PDF FlateDecode,HTTP Content-Encoding: deflate,PHP gzcompress(), Go compress/zlib,Java Deflater, Node zlib.deflate()gzip (RFC 1952)1f 8b 08 flags mtime xfl os |DEFLATE | CRC-32 (LE) | ISIZE10 + 11 + 8 = 29 bytes.gz files, tar.gz, HTTP gzip,PHP gzencode(), Go compress/gzip,Kafka gzip codec, Parquet GZIPHeader and trailer bytes carry no compressed data: on a 200-byte JSON event, gzip's 18 fixed bytes are 9% of the input.Readers are not interchangeable: a zlib reader rejects gzip bytes ("invalid header") and vice versa.Brotli (RFC 7932) and zstd (RFC 8878) are different formats end to end, not new wrappers around DEFLATE.
text
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-block

Real 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).

ImplementationNotes
zlib (C)Reference implementation; levels 0-9, memLevel 1-9, windowBits 8-15 (+16 gzip, +32 auto-detect on inflate)
zlib-ngzlib-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/flatePure Go; BestSpeed=1 ... BestCompression=9, HuffmanOnly=-2, DefaultCompression=-1
klauspost/compress/flateDrop-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:

ContainerHeaderTrailerChecksumSpecMagic bytes
raw DEFLATEnonenonenoneRFC 1951none
zlib2 bytes: CMF (method 8, window), FLG (check bits, FDICT, level hint)Adler-32, big-endianAdler-32 of uncompressed dataRFC 195078 01 / 78 5e / 78 9c / 78 da
gzip10 bytes: ID1 ID2 CM FLG MTIME(4) XFL OS, plus optional FEXTRA / FNAME / FCOMMENT / FHCRCCRC-32 then ISIZE (length mod 2^32), little-endianCRC-32 of uncompressed dataRFC 19521f 8b 08 ("ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213)")
zipPer-entry local header + central directory at the endData descriptorCRC-32 per entryPKWARE APPNOTE50 4b 03 04 ("PK")
text
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 header

Real 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).

NeedChooseWhy
HTTP bodygzip (or br, zstd)Unambiguous; every client decodes it
File on disk, log rotation.gz or .zstChecksum + length, streamable, zcat/zstdcat
Many files, users pick onezipCentral directory, per-file random access
Many files, one-shot transfer, best ratiotar + zstd/xz/gzipCross-file matches; tar --zstd, tar -J, tar -z
Embedding in your own framed protocolraw DEFLATE or zstd frameYour 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.

go
// 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
<?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.

text
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 bytes

Real 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.

ProductBrotli support
BrowsersChrome 50, Firefox 44, Safari 11, Edge 15 (MDN browser-compat-data)
nginxNot built in; ngx_brotli module: brotli, brotli_static, brotli_comp_level (default 6), brotli_window (default 512k), brotli_min_length (default 20)
CaddyServes pre-compressed .br via file_server precompressed; encode compresses on the fly with zstd and gzip
Gogithub.com/andybalholm/brotli (pure Go): NewWriterLevel, NewReader, HTTPCompressor
PHPNot in the official image (function_exists('brotli_compress') is false); PECL ext-brotli
LaravelNo 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).

text
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.

KnobCLIGo (klauspost)Effect
Level-1 ... -19, --ultra -22, --fast=NWithEncoderLevel(SpeedFastest / SpeedDefault / SpeedBetterCompression / SpeedBestCompression)Search effort
Window--long[=27], --memory= on decodeWithWindowSize, WithDecoderMaxWindowRepeat distance vs memory
Threads-T0 / -T#WithEncoderConcurrency, WithDecoderConcurrencyThroughput on big inputs
Checksum--check / --no-checkWithEncoderCRCXXH64-based frame checksum (lower 32 bits)
Dictionary--train, -D dictWithEncoderDict, WithDecoderDicts, dict.BuildZstdDictSmall-payload ratio
Decoder memory limit-M / --memoryWithDecoderMaxMemoryDefence 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).

text
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.

ToolTrainUse
zstd CLIzstd --train samples/* -o dict --maxdict=16384zstd -D dict, zstd -D dict -d
Go klauspostdict.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
HTTPServer sends Use-As-Dictionary on a resourceAvailable-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).

text
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/s

Real 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).

Productlz4 / snappy role
CassandraLZ4Compressor default; chunk_length_in_kb default 16 KiB; also Snappy, Deflate, Zstd
ScyllaDBLZ4Compressor default; SnappyCompressor, DeflateCompressor, ZstdCompressor
MongoDB WiredTigersnappy for collections and the journal by default; zlib, zstd optional
PostgreSQL TOASTpglz or lz4 per column
Kafkalz4 (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.

text
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/s

Real 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.

UsePrefer
Archive written once, rarely readxz -6/-9 or zstd -19 --long
Archive read often (CI caches, container layers)zstd
Legacy compatibilitybzip2 / 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."

text
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 only

Real 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).

ModeRatioRandom accessParallelExamples
One streamBestNoEncode only with tricks (pigz).gz, .zst, HTTP bodies
Independent blocksLower (no cross-block matches)YesYesParquet, Cassandra, zip entries
Seekable streamClose to streamYes, via seek tableYeszstd 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.

text
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 times

Real 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).

CodecLevel rangeDefaultMemory to note
gzip / zlib1-9 (0 = store)6 (nginx gzip_comp_level default 1)32 KiB window; trivial
Brotli0-1111 in the CLI (--best is the default); ngx_brotli 6window up to 16 MiB
zstd--fast=N, 1-19, 20-22 with --ultra3RFC 8878 recommends windows up to 8 MB; --long = 128 MiB on both sides; decoder limit -M default 128 MiB
lz41 (fast) to 12 (--best), higher levels use the HC match finder; --fast=N164 KB window
xz0-9, -e extreme694 MiB to compress, 9 MiB to decompress at -6
bzip21-9 = 100k-900k block9-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.

1101001,00010,000compression speed, MB/s (log scale, single thread)345678compression ratio (higher is smaller)gzip -9 (5.81)brotli 5 (5.75)gzip -6 (5.54)zstd -1 (5.66)zstd -3 (5.33)brotli 1 (5.26)gzip -1 (4.45)lz4 -9 HC (4.25)lz4 -1 (3.25)brotli 11 (7.28)zstd -19 (6.99)xz -6 (6.65)bzip2 -9 (7.66)gzipbrotlizstdlz4xz, bzip2146.6 MB JSON logs, Apple M5, best of 3, CLI

JSON logs, 146,573,164 bytes (the chart's data):

Tool and levelCompressed bytesRatioCompress MB/sDecompress MB/s
gzip -132,947,1864.453211,666
gzip -626,475,8725.541341,619
gzip -925,239,8945.81561,654
brotli -q 127,865,8495.26688953
brotli -q 525,503,9105.751291,124
brotli -q 1120,141,9277.281893
zstd -125,895,1905.661,1022,121
zstd -327,482,5315.337482,047
zstd -1920,960,9276.9942,697
lz4 -145,093,1803.253,6263,232
lz4 -9 (HC)34,509,1734.254733,309
xz -622,029,3246.655176
bzip2 -919,145,8517.661987

Ratios on the other inputs (same tools):

Tool and levelPersian text 1.47 MBPNG 700 KBRandom 4 MB
gzip -1 / -6 / -92.79 / 3.81 / 3.941.01 / 1.01 / 1.011.00 (grew 1,238-1,243 B)
brotli -q 1 / 5 / 113.35 / 3.96 / 5.071.01 / 1.00 / 1.011.00
zstd -1 / -3 / -193.50 / 3.76 / 5.041.01 / 1.01 / 1.011.00 (grew 103 B)
lz4 -1 / -92.21 / 3.421.00 / 1.011.00
xz -65.111.011.00
bzip2 -95.541.011.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)BytesRatioCompress MB/sDecompress MB/s
stdlib compress/gzip -1 / -6 / -91,922,502 / 1,732,479 / 1,593,7365.08 / 5.64 / 6.13592 / 298 / 66533-614
klauspost gzip -1 / -6 / -91,922,517 / 1,732,533 / 1,593,7555.08 / 5.64 / 6.13622 / 342 / 66534-609
klauspost zstd fastest / default / better / best1,776,305 / 1,812,899 / 1,693,177 / 1,692,7045.50 / 5.39 / 5.77 / 5.77656 / 528 / 311 / 781,383-1,536
andybalholm brotli 1 / 5 / 111,857,437 / 1,657,697 / 1,356,0855.26 / 5.89 / 7.20444 / 83 / 1439-576
pierrec lz4 block2,914,8083.359687,344
klauspost snappy / s2 block2,893,851 / 3,015,1363.37 / 3.24755 / 1,5843,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.

go
// 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/DEFLATEBrotlizstdlz4snappyxzbzip2
SpecRFC 1951/1950/1952RFC 7932RFC 8878lz4 block + frame docsformat_description.txt.xz file formatnone formal
Entropy stageHuffmanHuffman + contextHuffman + FSEnonenonerange coderHuffman
Max window32 KiB16 MiB8 MB typical, --long 128 MiB+64 KB~32 KiB in practice1.5 GiB900k block
Built-in dictionaryno (preset dict supported)yes, 122,784 bytestrained, by IDraw dict APInonono
ChecksumCRC-32 (gzip), Adler-32 (zlib)noneoptional XXH64 (low 32 bits)optional xxHash32 (frame)masked CRC-32C (framing format)CRC-32/64, SHA-256CRC-32 per block
Magic1f 8b / 78 xxnone28 b5 2f fd04 22 4d 18ff 06 00 00 73 4e 61 50 70 59 (framing)fd 37 7a 58 5a 0042 5a 68
HTTP codinggzip, deflatebrzstdnononono

Where each product compresses ​

ProductWhat is compressedCodec / knobDefault
PostgreSQL TOASTColumn values wider than ~2 kB (TOAST_TUPLE_THRESHOLD)default_toast_compression, column COMPRESSION pglz / lz4pglz in 18; docs for 19: "lz4 (if available); otherwise, pglz"
PostgreSQL WALFull-page imageswal_compression = off / on / pglz / lz4 / zstdoff
PostgreSQL backupspg_dump archivespg_dump --compress=gzip / lz4 / zstd[:level] (zstd also long)custom and directory formats: gzip "at a moderate level"; plain text: none
MongoDB WiredTigerCollection blocks, journal, networkblockCompressor snappy / zlib / zstd; journalCompressor; net.compression.compressorssnappy (time-series: zstd); network snappy,zstd,zlib; indexes: prefix compression
CassandraSSTable chunkscompression = {'class': 'LZ4Compressor', 'chunk_length_in_kb': 16}LZ4Compressor, 16 KiB
ScyllaDBSSTable chunks{'sstable_compression': 'LZ4Compressor'} (also Snappy, Deflate, Zstd)LZ4Compressor
RedisRDB snapshots (LZF on strings), quicklist nodesrdbcompression yes, list-compress-depthRDB yes; list compression 0 (off); values in memory: none
KafkaWhole record batchesproducer compression.type none/gzip/snappy/lz4/zstd; topic compression.type=producerproducer none; topic producer
ParquetColumn chunk pagesUNCOMPRESSED, SNAPPY, GZIP, LZ4_RAW, ZSTD, BROTLIwriter-specific
ElasticsearchStored fieldsindex.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 / servergzipbrzstdNotes
Chrome / Edgeyes50 / 15123dcb/dcz dictionary transport from Chrome 130
Firefoxyes44126
Safariyes1126.3
curl--compressedif built with brotliif built with zstdwithout --compressed curl sends no Accept-Encoding
Go net/http clienttransparentnonoAdds Accept-Encoding: gzip itself and decodes, unless you set the header or DisableCompression
Guzzle / Laravel Httpdecode_content true by defaultcurl-dependentcurl-dependentwithOptions(['decode_content' => false]) keeps raw bytes
nginxgzip, gzip_static, gunzipngx_brotli modulethird-party modulegzip_proxied default off
Caddyencode gzipprecompressed br onlyencode zstd (preferred)default minimum_length 512
Go servercompress/gzip, gzhttpandybalholm/brotliklauspost zstdnothing automatic
PHPzlib.output_compression, ob_gzhandler, gzencodePECL ext-brotliPECL ext-zstdnone 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).

FormatFirst bytesTotal size for the 24-byte inputReal hex (start)
raw DEFLATE (zlib, level 6)none11cb48 cdc9 c957 c840 27b9 00
zlib78 9c (default level)17789c cb48 ... 70be 08bb
gzip1f 8b 08291f8b 0800 0000 0000 0003 cb48 ...
zstd28 b5 2f fd2628b5 2ffd 2418 6d00 0038 6865 6c6c 6f20
lz4 frame04 22 4d 18340422 4d18 6440 a70f 0000 0069 6865 6c6c
Brotlinone (no magic)24a1b8 00c0 6fa4 74f3 26aa 32b4 5600 617b
xzfd 37 7a 58 5a 0080fd37 7a58 5a00 0004 e6d6 b446 04c0 1418
bzip242 5a 68 39 ("BZh9")47425a 6839 3141 5926 5359 ...
zip50 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 ​

text
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-endian

ISIZE 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 ​

text
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 = 211

The 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 ​

WhereKnobValues / defaultEffect
zlib / Go flate / PHPlevel-1 default (= 6), 0 store, 1-9; Go HuffmanOnly = -2Search effort
zlib / PHP deflate_initwindow (windowBits)8-15, default 15 (32 KiB)Window; lower saves memory
zlib / PHP deflate_initmemory (memLevel)1-9, default 8Hash table size
zlib / PHP deflate_initstrategyZLIB_DEFAULT_STRATEGY, ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXEDSpecialised match strategies
PHP inizlib.output_compression0 default; On or a buffer sizeTransparent page compression when the client sends Accept-Encoding: gzip
PHP inizlib.output_compression_level-1Level for the above
nginxgzip, gzip_comp_level, gzip_min_length, gzip_types, gzip_proxied, gzip_vary, gzip_buffers, gzip_http_version, gzip_disableoff, 1, 20, text/html, off, off, 32 4k|16 8k, 1.1, noneSee HTTP
nginxgzip_staticon / off / alwaysServe file.gz sidecars
ngx_brotlibrotli, brotli_static, brotli_comp_level, brotli_window, brotli_min_length, brotli_typesoff, -, 6, 512k, 20, text/htmlSame idea for br
Caddyencode [gzip [level]] [zstd [level]] { minimum_length; match }zstd + gzip, 512 B, a list of text typesOn-the-fly encoding
Caddyfile_server { precompressed br zstd gzip }br zstd gzip orderSidecar files
zstd CLI-#, --ultra, --fast, --long, -T, -M, -D, --train, --rsyncable, --patch-from, --adapt3, -, -, 27, 1-4 threads, 128 MiBSee zstd
Kafka producercompression.type, compression.gzip.level, compression.lz4.level, compression.zstd.level, batch.size, linger.msnone, -1, 9, 3, 16384, 5Batch codec and batch size
Kafka topic/brokercompression.typeproducerRe-compress on the broker if different
PostgreSQLdefault_toast_compression, column COMPRESSION, wal_compressionpglz (18) / lz4 if available (19), offTOAST and WAL full-page images
MongoDBstorage.wiredTiger.collectionConfig.blockCompressor, ...engineConfig.journalCompressor, ...indexConfig.prefixCompression, net.compression.compressorssnappy, snappy, true, snappy,zstd,zlibStorage and wire
Cassandratable compression = {'class', 'chunk_length_in_kb', 'lz4_compressor_type', 'lz4_high_compressor_level', 'compression_level'}LZ4Compressor, 16 KiB, fast, 9, 3 (zstd)SSTable chunks
Redisrdbcompression, list-compress-depthyes, 0LZF for RDB strings; quicklist node compression
Go net/httpTransport.DisableCompressionfalseClient auto gzip
Guzzle / Laraveldecode_contenttrueClient auto decode

Error messages you will see ​

Message (verbatim)WhereMeaning
gzip: invalid headerGo gzip.NewReaderInput is not gzip (zlib, raw, brotli, plain text, an HTML error page)
zlib: invalid headerGo zlib.NewReaderNot zlib (often gzip or raw deflate)
flate: corrupt input before offset NGo compress/flate (CorruptInputError)Bad DEFLATE stream, or wrong wrapper stripped
unexpected EOFGo readersTruncated stream: missing trailer or final block
gzip: invalid checksumGo gzip.ReaderCRC-32 or ISIZE mismatch: corruption
gzdecode(): data errorPHPNot gzip, or corrupt
gzdecode(): insufficient memoryPHP with $max_lengthOutput would exceed $max_length (your bomb guard working)
Decoding error (36) : Dictionary mismatchzstd CLIFrame 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 > 8388608zstd CLI with --memory=8MBFrame's window exceeds the decoder limit (made with --long); real output
gzip: stdin: not in gzip formatgzip CLISame as invalid header
ERR_CONTENT_DECODING_FAILEDChromeServer said Content-Encoding: gzip but sent something else (double compression or none)
http: request body too largeGo http.MaxBytesReaderCompressed body exceeded the cap
415 Unsupported Media Type + Accept-EncodingHTTP serverRFC 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).

text
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
SolutionHowAdvantageCost / limitation
Compress at the reverse proxynginx gzip on, Caddy encode, CDNOne place, every upstream, C-speed, app stays simpleProxy CPU; must set gzip_proxied any (nginx default off) and types
Pre-compress static filesgzip -9 -k, brotli -q 11, zstd -19 at buildBest ratio, zero CPU per requestOnly for files known at build time
Compress in the app (Go middleware, Laravel middleware)Wrap the response writerPer-route control, works without a proxyEvery app must get Vary, ETag, flush, HEAD, 204/304 right
Compress at the CDN edgeCDN compression settingsOffloads origin, br/zstd for browsersOrigin to CDN may still be uncompressed
Do not compress-No CPUBandwidth, 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
# 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 "";
        }
    }
}
txt
# 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:

go
// 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))
}
go
// 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.

text
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: identity

Laravel: 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
<?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
<?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
<?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 ​

text
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 identity

Rules: 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."

text
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 total

Real 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 inputSolves 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 limitingRemoves 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):

go
// 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
<?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.

text
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, zstd

Real 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.

LayerGuard
Wirenginx client_max_body_size, Go http.MaxBytesReader
Decoder outputCount bytes produced; fail above a cap (Go wrapper below; PHP gzdecode($s, $max), inflate_add loop)
Decoder memoryzstd 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"
ArchivesLimit entry count, per-entry and total uncompressed size, reject .. paths (zip slip)
TimeRequest timeout, job timeout
go
// 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
<?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:

go
// 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
<?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):

sql
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;         -- zstd

What 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.

EngineWhat to do
PostgreSQLlz4 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
MongoDBKeep 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 / ScyllaDBKeep 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
RedisValues 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 ​

text
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 checks

Kafka'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 ​

DataRecommendationWhy
Rotated logs (logrotate)compress + compresscmd /usr/bin/zstd, compressext .zst, or gzip delaycompresszstd -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 exporterNetwork is the bottleneck between regions
Log storage (Loki, Elasticsearch, ClickHouse)Engine-native (chunks/stored fields)Already compressed; do not double-compress
pg_dump, mysqldumppg_dump -Fc --compress=zstd:level=10 / mysqldump | zstd -T0 -10Pipe-friendly, multi-core, fast restore
Large backups to object storagezstd -T0 --long=27 -10 then encrypt (age, KMS)Compress before encrypting
VM / disk imageszstd --long, or sparse-aware toolsLong-range repeats

Observability pipelines are covered in Observability; backup strategy in Backup, PITR & DR.

Archives and analytics file formats: zip vs tar.gz, Parquet ​

FormatCompression unitRandom accessTypical codecUse
zipEach fileYes (central directory)DEFLATE (zstd and others in newer APPNOTE methods)Downloads users open, jars, office documents
tar.gz / tar.zst / tar.xzWhole archiveNogzip / zstd / xzSource releases, backups, Docker layer tarballs
ParquetColumn chunk pagesYes, by row group and columnSNAPPY, ZSTD, GZIP, LZ4_RAW, BROTLIAnalytics; read only the columns you need
ORC / Arrow IPCStripes / buffersYeszstd, lz4Analytics, IPC
zstd seekableFrames + seek tableYeszstdLarge 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 ​

SituationWhy notInstead
Already-compressed media and archives (JPEG, PNG, WebP, AVIF, MP4, zip, gz, pdf with images)Ratio ~1.00; CPU wastedExclude by content type / magic bytes
Encrypted dataRatio ≤ 1.00Compress before encryption, or not at all
Tiny payloads (< ~1 KB)Header and trailer outweigh savings; latency of a flushMinimum length; batching; dictionaries
CPU-bound service at its limitCompression steals the CPU you are short ofOffload to proxy/CDN, use lz4/zstd -1, or skip
Same datacenter, fast network, small messagesBytes are cheap, CPU and latency are notMeasure; often lz4 or nothing
Responses mixing secrets and reflected inputBREACHMask secrets or disable per route
Data needing random writes in placeCompressed blocks must be rewrittenBlock compression with small blocks, or none
Already compressed by another layerDouble work, e.g. app-level zstd payloads inside zstd Kafka batchesCompress once, at the layer with the biggest batch

Troubleshooting ​

SymptomLikely causeCheckFix
Browser shows garbage or ERR_CONTENT_DECODING_FAILEDBody compressed twice (app + proxy, or zlib.output_compression + middleware), or header says gzip but body is notcurl -s -H 'Accept-Encoding: gzip' URL | xxd | head -1 should start 1f8b exactly onceCompress in one layer only; nginx proxy_set_header Accept-Encoding "" makes the app send identity
Responses are not compressed at allContent type not listed (nginx default only text/html, Caddy default list lacks application/x-ndjson), body under min length, proxied request with gzip_proxied offcurl -sD - -o /dev/null -H 'Accept-Encoding: gzip' URLAdd gzip_types, gzip_proxied any, or a Caddy match
Some clients get gzip they cannot read via a CDN/cacheMissing Vary: Accept-EncodingResponse headersgzip_vary on; set Vary in middleware
gzip: invalid header / zlib: invalid headerWrong wrapper, or an HTML error page instead of compressed dataxxd -l 4Match reader to magic bytes; zlib_decode() / inflate_init with the right encoding
unexpected EOF at the endTruncated download, writer not Close()dSize vs gzip -l; did your code call Close()?Always defer w.Close() and check its error
CPU spike after enabling compressionHigh level on the fly (brotli 11, gzip 9, zstd 19)Profile; gzip_comp_levelLevel 4-6 for gzip/br on the fly, zstd 1-3; pre-compress statics
SSE / streaming response arrives all at onceCompressor buffers until it has enough bytes; proxy bufferingWatch with curl -NFlush() the compressor (Go), ZLIB_SYNC_FLUSH (PHP), X-Accel-Buffering: no, or exclude text/event-stream
OOM when receiving uploadsDecompression bomb, io.ReadAll on a decoderMemory graph per requestCap decoded bytes, zstd WithDecoderMaxMemory
Dictionary mismatchConsumer lacks the dictionary ID the frame nameszstd -lv file shows DictIDShip dictionaries with versions, keep old ones
Kafka ratio poorBatches tiny (linger.ms 0, low traffic per partition)Producer metrics for compression rate and average batch sizeRaise linger.ms / batch.size, fewer partitions per producer
Postgres table still large after SET COMPRESSION lz4Only new values use itpg_column_compression(col)Rewrite (UPDATE ... SET col = col || '', VACUUM FULL, or dump/restore)
.tar.gz slow to extract one fileWhole-stream compression-zip or seekable zstd for random access
Same input, different .gz hash across buildsMTIME / filename in the gzip header; different zlib versionsxxd -l 10gzip -n, pin the tool, or hash the uncompressed content

Choosing a codec and a level ​

SituationRecommendedExtra techniqueReason
Dynamic API JSON / HTML to browsersgzip level 4-6 at the proxy; zstd or br 4-5 if the proxy supports itVary, min length 1 KB, exclude secrets + reflected inputUniversal support; cheap enough per request
Static JS/CSS/SVG/fontsbrotli -q 11 + zstd -19 + gzip -9 pre-compressedgzip_static, brotli_static, Caddy precompressedPay once at build
Service-to-service RPC in one regionnone or lz4/snappy; gRPC gzip only for big messagesMeasure p99Network is cheap, latency is not
Cross-region or mobile trafficzstd -3 or gzip -6Dictionaries for small messagesBytes are expensive
Kafkazstd (ratio) or lz4 (CPU) at the producerlinger.ms 5-50, batch.size 64-256 KiB, topic compression.type=producerBatch compression; broker passes through
OLTP database storageEngine default (lz4/snappy)Small chunks for point readsDecompress on every read
Analytics / ParquetZSTD (or SNAPPY for speed)Sort and partition firstEncodings + codec
Logs on diskzstd -3 (rotation), zstd -19 for archiveOne file per stream5-6x faster than gzip at same ratio
Backupszstd -T0 -10..19 --longCompress, then encryptFast restore matters
Software releasesxz -6/-9 or zstd -19 --longReproducible flags (-n, fixed mtime)Written once, downloaded many times
Many tiny records (< 1 KB)zstd with a trained dictionary, or batchingDictionary IDs and versionsNo history otherwise
Already-compressed / encryptedNothingDetect by content typeCannot 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 ​

text
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-Encoding and 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_compression shrinks full-page images in WAL, which reduces replication and archive traffic; MongoDB compresses intra-cluster traffic with net.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/APPEND and 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 without Vary, a replica fed by a decoder with a smaller memory limit than the writer's window.

Scaling path: 1x, 10x, 100x ​

LoadWhat changes
1xgzip at the proxy, defaults everywhere, pre-compressed assets. Measure response sizes and CPU.
10xMove 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.
100xDictionaries 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)

bash
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.jsonl

2. Measure entropy, then ratio and speed.

bash
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.

bash
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).

bash
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 smaller

5. Proxy compression (nginx and Caddy in front of the Go server).

bash
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 -> identity

6. Dictionaries, bombs, PostgreSQL.

bash
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 ​

BeliefReality
"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 ​

TopicWhat to remember
Two familiesEntropy coders (Huffman, arithmetic, ANS/FSE) + dictionary coders (LZ77, LZ78/LZW); real codecs chain both
LimitShannon entropy of your model; random/encrypted = 8 bits/byte = no gain
DEFLATELZ77 (32 KiB window, matches 3-258) + Huffman; blocks stored/fixed/dynamic
Wrappersraw: none; zlib 78 9c + Adler-32; gzip 1f 8b 08 + CRC-32 + ISIZE; zip PK\3\4 per entry
Magic byteszstd 28 b5 2f fd, lz4 04 22 4d 18, xz fd 37 7a 58 5a 00, bzip2 BZh, Brotli none
Measured on logslz4 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
zstdDefault 3; --fast, 1-19, --ultra 22; --long 128 MiB; frames, skippable frames, seekable format; dictionaries by ID
HTTPAccept-Encoding / Content-Encoding / Vary: Accept-Encoding; compress at the proxy; pre-compress statics; min ~1 KB
nginxgzip on; gzip_comp_level 5; gzip_min_length 1024; gzip_types ...; gzip_proxied any; gzip_vary on; + gzip_static
Caddyencode zstd gzip (default), minimum_length 512, default match list; file_server precompressed
Gocompress/gzip, compress/flate, compress/zlib; klauspost zstd, gzhttp, s2, dict; andybalholm brotli; client decodes gzip itself
PHP / Laravelgzencode/gzcompress/gzdeflate, zlib_encode, deflate_init+deflate_add, gzdecode($s, $max); Guzzle decode_content true; no built-in br/zstd
BREACHSecret + reflected input + compression + observable length = leak
Bombs~1000:1 for gzip, far more for zstd/brotli/bzip2; cap decoded bytes and decoder memory
DatabasesPostgres TOAST pglz/lz4 + wal_compression; Mongo snappy default; Cassandra LZ4 16 KiB chunks; Redis none for values
KafkaProducer compresses batches; topic compression.type=producer; linger.ms/batch.size drive ratio

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Compression ratioOriginal size / compressed size (5.5 = 5.5x smaller)
LosslessDecoder reproduces the exact input bytes
LossyDecoder reproduces an approximation (JPEG, MP3, lossy WebP/AVIF)
Shannon entropyH = -Σ p log2 p: average information per symbol under a model; the lossless limit
Order-0 entropyEntropy counting symbols without context
RedundancyThe predictable part of the data; what compression removes
Pigeonhole principleWhy no lossless method shrinks every input
Entropy coderAssigns shorter codes to more probable symbols (Huffman, arithmetic, ANS)
Prefix codeNo code is a prefix of another, so no separators are needed
Huffman codingOptimal whole-bit prefix code from symbol frequencies (1952)
Canonical HuffmanCodes rebuilt from code lengths only, as DEFLATE transmits them
Arithmetic / range codingEncodes a message as one number in an interval; fractional bits per symbol
ANSAsymmetric numeral systems: arithmetic-coding precision with one integer state (Duda 2009)
FSE / tANSFinite State Entropy, zstd's table-based ANS coder
Run-length encoding (RLE)(count, symbol) for runs of equal symbols
Dictionary coderReplaces repeats with references to earlier data
LZ77Sliding-window back-references (distance, length) + literals (1977)
LZ78Explicit phrase dictionary (index, next symbol) (1978)
LZWLZ78 variant sending only indices; Unix compress, GIF
Sliding windowThe recent output an LZ77 match may refer to (32 KiB in DEFLATE)
LiteralA byte emitted as itself
Match / back-referenceCopy length bytes from distance bytes back
Lazy matchingEncoder checks whether a match starting one byte later is longer
DEFLATELZ77 + Huffman format of RFC 1951
BFINAL / BTYPEDEFLATE block header bits: last block flag; stored / fixed / dynamic
zlib formatRFC 1950 wrapper: 2-byte header + DEFLATE + Adler-32
gzip formatRFC 1952 wrapper: 10-byte header (+ optional name, comment, extra) + DEFLATE + CRC-32 + ISIZE
Adler-32zlib's fast checksum (see Checksums & Hashing)
CRC-32gzip's and zip's checksum
ISIZEgzip trailer: uncompressed length mod 2^32
Multi-member gzipSeveral gzip members concatenated; readers treat them as one stream
zipArchive with per-file compression and a central directory
tar.gzA tar archive compressed as one gzip stream
BrotliRFC 7932 codec: LZ77 + Huffman + context modelling + static dictionary
Static dictionaryBuilt-in shared data (Brotli's 122,784 bytes) both sides know
Zstandard (zstd)RFC 8878 codec: LZ77 + Huffman + FSE, levels from --fast to 22
Framezstd's self-contained unit: magic, header, blocks, optional checksum
Skippable framezstd frame with magic 0x184D2A5? that decoders ignore (metadata, padding)
Seekable formatzstd frames + seek table for random access
Long-distance matchingzstd --long: window up to 128 MiB+
Trained dictionaryzstd dictionary built from samples (--train), referenced by ID
Preset dictionaryzlib FDICT / Go NewWriterDict / PHP dictionary option
Compression Dictionary TransportRFC 9842: HTTP dcb/dcz codings using a previous response as dictionary
lz4Byte-aligned LZ77, no entropy stage; very fast
LZ4HClz4's high-compression match finder (higher levels), same decoder
snappyGoogle's byte-oriented LZ77 codec, no entropy stage
S2klauspost's snappy extension; faster, can read snappy
xz / LZMA2Large-window LZ77 with a range coder; high ratio, slow
bzip2Burrows-Wheeler transform + MTF + RLE + Huffman
Burrows-Wheeler transformReversible sort that groups similar contexts
pglzPostgreSQL's built-in LZ-family TOAST compressor
TOASTPostgreSQL's storage of large column values (compressed and/or out of line)
Compression levelEncoder search-effort preset
Streaming compressionStateful compression over an unbounded input
Block compressionIndependent chunks; random access, lower ratio
Flush (sync flush)Emit all buffered compressed data now without ending the stream
Content-EncodingHTTP header: coding applied to the representation
Accept-EncodingHTTP request header: codings the client accepts, with q-values
Transfer-EncodingHTTP/1.1 message framing (chunked); not used for compression in practice
identityThe "no encoding" content coding
q-valuePreference weight 0-1 in Accept-Encoding; q=0 means not acceptable
VaryResponse header listing request headers that change the response
Weak ETagW/"...": semantically equal, not byte-identical
BREACHLength side channel on compressed HTTP responses (2013)
CRIMESame idea against TLS/SPDY header compression (2012)
HPACK / QPACKHTTP/2 / HTTP/3 header compression designed to resist CRIME
Decompression bombSmall input that expands enormously
http.MaxBytesReaderGo helper capping request body bytes
gzhttpklauspost's Go gzip/zstd HTTP handler and transport
gzencode / gzcompress / gzdeflatePHP functions for gzip / zlib / raw DEFLATE
deflate_init / deflate_addPHP incremental compression API
zlib.output_compressionPHP ini: compress all output when the client accepts gzip
decode_contentGuzzle option (default true) to decode compressed responses
compression.typeKafka producer/topic codec setting
linger.ms / batch.sizeKafka producer batching knobs that drive compression ratio
default_toast_compressionPostgreSQL default TOAST codec
wal_compressionPostgreSQL WAL full-page image compression
blockCompressorMongoDB WiredTiger collection codec (snappy default)
chunk_length_in_kbCassandra compression chunk size (16 KiB default)
rdbcompressionRedis: LZF-compress strings in RDB snapshots
list-compress-depthRedis: compress inner quicklist nodes
Parquet codecPage compression in Parquet: SNAPPY, GZIP, ZSTD, LZ4_RAW, BROTLI
pigzParallel gzip implementation
zlib-ng / libdeflateFaster DEFLATE implementations
Magic numberFixed leading bytes that identify a format

References ​

Built by Morteza Negahi