5. DEFLATE

The engine behind gzip, zip, and PNG

DEFLATE is probably the most important compression algorithm you've never heard of by name. It powers gzip, zip, zlib, PNG images, and HTTP content encoding. Every time you load a web page, DEFLATE is almost certainly involved.

Created by Phil Katz for PKZIP in 1993 and documented as RFC 1951, DEFLATE's brilliance is in combining two techniques we've already covered: LZ77 for finding repeated sequences and Huffman coding for encoding the result compactly.

The Two-Stage Pipeline

                    DEFLATE
    ┌──────────────────────────────────────┐    
    │                                      │    
    │   Input bytes                        │    
    │       │                              │    
    │       ▼                              │    
    │   ┌────────┐                         │    
    │   │  LZ77  │  Find repeated          │    
    │   │        │  sequences              │    
    │   └───┬────┘                         │    
    │       │                              │    
    │       ▼                              │    
    │   Stream of literals                 │    
    │   and (distance, length) matches     │    
    │       │                              │    
    │       ▼                              │    
    │   ┌─────────┐                        │    
    │   │ Huffman │  Encode with           │    
    │   │ Coding  │  variable-lengt h      │    
    │   │         │  bit codes             │    
    │   └───┬─────┘                        │    
    │       │                              │    
    │       ▼                              │    
    │   Compressed bitstream               │    
    │                                      │    
    └──────────────────────────────────────┘    

Each stage tackles a different kind of redundancy. LZ77 eliminates repeated sequences (structural redundancy). Huffman coding eliminates statistical redundancy in the LZ77 output. Together, they compress better than either could alone.

Stage 1: LZ77 in DEFLATE

DEFLATE's LZ77 stage works just like we described in the LZ77 chapter, with specific parameters:

Parameter Value
Window size 32,768 bytes (32 KB)
Minimum match length 3 bytes
Maximum match length 258 bytes
Maximum distance 32,768 bytes

The minimum match length is 3 because shorter matches aren't worth the overhead — a (distance, length) pair for a 1-byte or 2-byte match would often be larger than just including the literal bytes.

The LZ77 stage produces a stream of three kinds of elements:

  • Literal bytes (0–255) — raw bytes that had no match
  • Length values (3–258) — how many bytes to copy
  • Distance values (1–32768) — how far back to look

Length and distance codes with extra bits

Lengths and distances can have large values, so DEFLATE encodes them cleverly: a base code plus extra bits. Small values use no extra bits. Larger values use the base code to identify a range and extra bits to specify the exact value within that range.

Length code examples

CodeLengthExtra bits
25730
25840
26511–121
26919–222
281131–1625
2852580

For example, code 269 with extra bits "10" means length 19 + 2 = 21. This is efficient: common short lengths use few bits, while rare long lengths use more.

Stage 2: Huffman Coding in DEFLATE

DEFLATE uses two separate Huffman trees:

  • Tree 1: Literals/lengths — encodes literal bytes (0–255), end-of-block (256), and length codes (257–285). All in one combined alphabet of 286 symbols.
  • Tree 2: Distances — encodes distance codes (0–29), each potentially followed by extra bits.

When the encoder outputs a match, the stream looks like:

[Huffman-coded length] [extra length bits] [Huffman-coded distance] [extra distance bits]

Three block types

DEFLATE splits data into blocks. Each block starts with a 3-bit header: 1 bit for "is this the last block?" and 2 bits for the block type:

Type Name Description
0 Stored No compression — raw bytes. Used when the data is incompressible (already compressed, random, etc.)
1 Fixed Huffman Predefined Huffman trees built into the spec. No need to transmit the trees — fast but not optimal for every input.
2 Dynamic Huffman Custom Huffman trees optimized for this specific block. The trees are transmitted before the data. Better compression but more overhead.

Trees describing trees

In type 2 blocks, the custom Huffman trees need to be transmitted. But transmitting a full tree would be expensive! DEFLATE solves this with a clever trick: it sends only the code lengths (how many bits each symbol uses), and those code lengths are themselves compressed using a third small Huffman tree (the "code length code"). It's turtles all the way down — but it keeps the overhead tiny.

A Worked Example

Input: ABCABCABCABC (12 bytes = 96 bits)

Stage 1 — LZ77

The LZ77 stage finds:

literal A
literal B
literal C
match (distance=3, length=9)    ← copies "ABCABCABC"

The first "ABC" is output as literals (nothing to match against yet). The remaining 9 characters are all a repetition of that same 3-character pattern, captured as a single back-reference.

Stage 2 — Huffman coding

Using fixed Huffman codes (type 1 block) for simplicity:

A (0x41) → 8-bit fixed code: 00110001    (8 bits)
B (0x42) → 8-bit fixed code: 00110010    (8 bits)
C (0x43) → 8-bit fixed code: 00110011    (8 bits)
Length 9 → code 265 + 1 extra bit        (8 bits)
Distance 3 → code 3, 0 extra bits        (5 bits)
End of block (256) → fixed code          (7 bits)
Block header                             (3 bits)

Approximate total: ~47 bits

Original

96 bits (12 bytes)

DEFLATE (approximate)

~47 bits — ~50% smaller

On a 12-byte input, the savings are modest. On real files (kilobytes to megabytes), DEFLATE typically achieves 60–80% compression on text.

Compression Levels — What gzip -1 through -9 Really Means

When you run gzip -1 (fast) or gzip -9 (best), you're not changing the compressed format. All levels produce valid DEFLATE. The difference is entirely in how hard the encoder searches for matches:

Level Strategy Speed Compression
0 Stored (no compression) Instant None
1 Greedy matching, short hash chains Very fast Decent
6 Lazy matching, moderate chain length (default) Moderate Good
9 Lazy matching, long chains, maximum effort Slow Best

A general principle in compression

The compressed format specifies how to decode, not how to encode. Any valid DEFLATE stream can be decoded by any DEFLATE decoder. But the encoder is free to be as smart (or as lazy) as it wants in choosing matches. Better encoders produce smaller output — the format is the same, only the intelligence differs.

This is why tools like Zopfli (Google) can produce DEFLATE streams that are 3–8% smaller than gzip -9 — same format, smarter encoder.

gzip, zip, zlib — The Wrappers Around DEFLATE

DEFLATE is just the raw compressed bitstream. Real formats wrap it with metadata and checksums:

Format Wraps Adds
gzip (RFC 1952) Single file Magic bytes, timestamp, OS, optional filename, CRC-32 checksum
zlib (RFC 1950) Single stream Minimal header (2 bytes), Adler-32 checksum (faster than CRC-32)
zip Multiple files File metadata, directory structure, per-file compression, optional encryption
PNG Image data zlib-wrapped DEFLATE for pixel data (after PNG filtering)

So gzip and zip are not compression algorithms — they're container formats that use DEFLATE for the actual compression.

Why DEFLATE Won

Phil Katz deliberately placed DEFLATE in the public domain with no patents. This was a direct response to the legal troubles around LZW. The timing was perfect:

  • LZW was patent-encumbered — DEFLATE was free
  • Simple enough for efficient implementation, good enough compression for most uses
  • zlib by Jean-loup Gailly and Mark Adler became the canonical implementation — clean, well-tested, available everywhere
  • HTTP adopted gzip/deflate content encoding, making it essential for the web
  • PNG adopted DEFLATE, ensuring its role in image compression

More than 30 years later, DEFLATE remains the most widely-deployed compression algorithm in the world. Newer algorithms (Zstandard, Brotli) compress better and faster, but DEFLATE's universal support makes it hard to displace.

Try It Yourself — DEFLATE Pipeline

Type a string and watch DEFLATE's two-stage pipeline in action. Stage 1 (LZ77) finds repeated sequences. Stage 2 encodes the result using fixed Huffman codes (type 1 block) into a bitstream. Try strings with lots of repetition to see matches dominate, or random text to see mostly literals.

Stage 1: LZ77 Decomposition

Stage 2: Fixed Huffman Encoding

Output Bitstream

Compression Statistics

Key Takeaways

  • DEFLATE = LZ77 + Huffman coding — the combination that conquered the world
  • LZ77 eliminates repeated sequences; Huffman coding compresses what's left
  • Two Huffman trees: one for literals/lengths, one for distances
  • Three block types: stored, fixed Huffman, dynamic Huffman
  • Compression levels only affect encoding strategy, not the format — any decoder can decompress any level
  • gzip, zip, zlib, and PNG are containers/wrappers around DEFLATE
  • Patent-free by design — this is why it won

DEFLATE combines dictionary matching and entropy coding in a straightforward pipeline. But there's a completely different approach to making data compressible: what if you could rearrange the data so that identical characters end up next to each other? That's the Burrows-Wheeler Transform — and it's magical.