17. Zstandard Deep Dive

Inside the frame format, FSE tables, and dictionary training

We introduced Zstandard in the ANS article — a modern compressor that combines LZ77 matching with FSE (Finite State Entropy, a tANS implementation) to achieve arithmetic-coding-level compression at Huffman-coding speed. That article covered the why. This one covers the how: the frame format, the sequence encoding, how FSE tables are built and transmitted, and the dictionary training system that makes zstd uniquely effective on small data.

The Zstandard Frame Format

A Zstandard compressed stream consists of one or more frames. Each frame is independently decompressible — you don't need data from previous frames. This is important for streaming, seeking, and error recovery.

Zstandard frame layout

┌──────────────────────────────────────────────────┐
│  Magic Number (4 bytes): 0xFD2FB528              │
├──────────────────────────────────────────────────┤
│  Frame Header                                    │
│    ├─ Frame Header Descriptor (1 byte)           │
│    ├─ Window Descriptor (0–1 bytes)              │
│    ├─ Dictionary ID (0–4 bytes)                  │
│    └─ Frame Content Size (0–8 bytes)             │
├──────────────────────────────────────────────────┤
│  Block 1                                         │
│    ├─ Block Header (3 bytes)                     │
│    └─ Block Data                                 │
├──────────────────────────────────────────────────┤
│  Block 2                                         │
│    ├─ Block Header (3 bytes)                     │
│    └─ Block Data                                 │
├──────────────────────────────────────────────────┤
│  ...                                             │
├──────────────────────────────────────────────────┤
│  Last Block (marked in header)                   │
├──────────────────────────────────────────────────┤
│  Content Checksum (0 or 4 bytes, xxHash-64)      │
└──────────────────────────────────────────────────┘

Block types

Each block has a 3-byte header with a "last block" flag, block type, and block size:

Block type Meaning
Raw Uncompressed data (stored as-is)
RLE Entire block is a single repeated byte
Compressed LZ77 + entropy coded data
Reserved Not used

Maximum block size is 128 KB. The encoder splits input into blocks and chooses the best type for each — incompressible data gets stored raw rather than expanded by failed compression.

Inside a Compressed Block

A compressed block contains three interleaved bitstreams:

     Compressed Block Structure
┌─────────────────────────────────────────┐
│                                         │
│  Literals Section                       │
│  (raw bytes that didn't match)          │
│    ├─ Literals header (1–5 bytes)       │
│    ├─ Huffman tree description           │
│    └─ Huffman-compressed literals       │
│                                         │
├─────────────────────────────────────────┤
│                                         │
│  Sequences Section                      │
│  (match descriptions)                   │
│    ├─ Number of sequences               │
│    ├─ FSE table for literal lengths     │
│    ├─ FSE table for offsets             │
│    ├─ FSE table for match lengths       │
│    └─ Interleaved FSE-coded sequences   │
│                                         │
└─────────────────────────────────────────┘

The LZ77 stage produces a stream of sequences, each containing:

(literal_length, offset, match_length)
  • literal_length — how many raw bytes precede this match (the literals are stored separately in the literals section)
  • offset — how far back to look (with special codes for repeated offsets)
  • match_length — how many bytes to copy

This separation — literals in one section, sequence metadata in another — is key to zstd's efficiency. Literals and match metadata have very different statistical properties and benefit from different entropy coders.

FSE: Finite State Entropy

FSE is Yann Collet's production-quality implementation of tANS. Let's trace how an FSE table is built and used.

Building the table

  1. Count symbol frequencies

    Scan the data and count how often each symbol appears. For match lengths: how often is the match length 4? 5? 6? 10? 50?

  2. Normalize to table size

    Choose a table size L (power of 2, typically 32–2048). Scale each frequency so the total equals L. A symbol with 30% frequency gets about 0.3 × L slots.

    Rounding is tricky — every symbol must get at least 1 slot (even very rare symbols), and the total must equal exactly L. Zstd uses a careful rounding algorithm that minimizes the impact on compression.

  3. Distribute symbols across the table

    Assign each symbol its slots in a specific interleaving pattern. The distribution must be deterministic (encoder and decoder must agree) and spread each symbol's slots as evenly as possible across the table for good compression.

  4. Build encoding and decoding tables

    Decoding table: for each state s in [0, L), store the symbol, the number of bits to read, and the base value for computing the next state.
    Encoding table: for each (symbol, sub-state) pair, store the bits to output and the next state.

Transmitting the table

The decoder needs to know the frequency distribution to rebuild the table. Zstd transmits normalized frequencies using a compact encoding:

For each symbol (in order):
  If frequency < threshold:  encode with few bits
  If frequency >= threshold: encode with more bits
  If frequency == 0:         skip (run-length encode sequences of zero-frequency symbols)

A typical FSE table description fits in 10–40 bytes — tiny compared to the data it helps compress.

Predefined tables

For very small blocks where transmitting a custom FSE table would cost more than it saves, zstd provides predefined default tables for literal lengths, offsets, and match lengths. These are hardcoded in the specification and optimized for "typical" data distributions. The block header signals whether the block uses default, custom, or "repeat previous" tables.

Repeated Offsets

Like LZMA, Zstandard maintains a cache of the three most recent match offsets. When a match reuses a recent offset, the encoder signals this with special offset codes (1, 2, or 3) instead of the full offset value.

Why repeated offsets matter so much

In structured data, the same distances appear over and over. Consider a CSV with fixed-width columns, a binary format with fixed-size records, or source code with consistent indentation. The same offset might account for 30–50% of all matches. Encoding it as a single small code (1–2 bits via FSE) instead of a full offset (potentially 20+ bits) saves enormous amounts of space.

The repeated offset stack works like this:

Initial state: rep = [1, 4, 8]  (most recent first)

Match with offset 1000:   rep = [1000, 1, 4]     (push, shift)
Match with rep offset 1:  rep = [1000, 1, 4]     (reuse most recent, no change)
Match with rep offset 2:  rep = [1, 1000, 4]     (swap positions 1 and 2)
Match with rep offset 3:  rep = [4, 1000, 1]     (rotate position 3 to front)

Huffman for Literals

Literals (raw bytes that didn't match) are compressed with Huffman coding, not FSE. Why use Huffman here when FSE is available?

  • Literals have a large alphabet (256 possible byte values) — Huffman works well at this scale
  • Huffman decoding is slightly faster than FSE for large alphabets (fewer table lookups per symbol)
  • The compression difference between Huffman and FSE is minimal for 256-symbol alphabets

Zstd's Huffman implementation uses a 4-stream parallel decoder: the compressed literals are split into 4 streams that can be decoded simultaneously on modern CPUs. This is a key contributor to zstd's decompression speed — the literals section often dominates decoding time, and 4-way parallelism nearly quadruples throughput.

Compression Levels

Zstandard's 23 compression levels (-1 through 22) control several parameters:

Parameter Low levels (1–3) Mid levels (6–12) High levels (16–22)
Match finder Hash chain (4-byte hash) Hash chain + binary tree Binary tree, longer chains
Search depth 1–4 16–64 256–4096
Lazy matching None 1 attempt Multiple attempts
Optimal parsing No No Yes (levels 17+)
Window size 256 KB – 4 MB 4–16 MB 32–128 MB

The key speedup at low levels: greedy matching with short hash chains. The encoder takes the first good-enough match rather than searching for the best one. At level 1, this means compression is CPU-limited by memory bandwidth rather than by search — that's why zstd level 1 can compress at 500+ MB/s.

At high levels (17+), zstd switches to optimal parsing — the same technique LZMA uses. The encoder considers multiple ways to parse each region and picks the cheapest total encoding, factoring in repeated offsets and FSE symbol costs. This approaches LZMA compression ratios but with much faster decompression (since the output format still uses FSE, not range coding).

Asymmetric speed is the design goal

Zstd decompression speed is roughly constant (~1500 MB/s) regardless of compression level. This is because the format doesn't change — only how hard the encoder searches. The decoder always does the same work: read FSE states, look up tables, copy bytes. This makes zstd ideal for scenarios where data is compressed once and decompressed many times.

Dictionary Compression

Dictionary compression is Zstandard's killer feature for small data. The problem: LZ77 needs data in the sliding window to find matches. For a 1 KB JSON record, the window contains only the record itself — not much to match against. Compression ratios for small data are typically poor.

The solution: train a dictionary on a collection of similar samples, then use it as a pre-populated sliding window.

How dictionary training works

  1. Collect training samples

    Gather 100–10,000 representative samples of the data you want to compress. For a REST API, these might be typical JSON responses. For a log system, typical log lines.

  2. Find common substrings

    The training algorithm (COVER or fastCOVER) identifies substrings that appear across many samples. These are the patterns that will be useful for matching during compression.

  3. Build the dictionary

    The dictionary contains:
    - The content (up to 110 KB of common substrings, most useful last)
    - Pre-computed Huffman and FSE tables optimized for the training data
    - A dictionary ID so the decoder knows which dictionary to use

Dictionary compression in practice

Dataset: 10,000 JSON API responses, average size 800 bytes

Without dictionary: Average compressed size: 620 bytes (22% reduction)

With trained dictionary (32 KB): Average compressed size: 180 bytes (77% reduction)

The dictionary "knows" the JSON structure, field names, common values, and typical patterns. Each individual record only needs to encode what's DIFFERENT from the expected pattern.

Why the dictionary goes at the end

The dictionary content is ordered so that the most useful substrings are at the end — closest to the beginning of the actual data in the virtual sliding window. This means the most common patterns have the smallest offsets, which encode in the fewest bits.

Virtual sliding window during compression:

[...dictionary content (oldest)...][...most useful patterns...][actual data...]
                                    ▲                          ▲
                                    │                          │
                               small offsets              current position
                               = few bits

Zstd in the Ecosystem

Command-line usage

# Compress
zstd file.txt                    # default level 3
zstd -19 file.txt                # high compression
zstd --ultra -22 file.txt        # maximum compression

# Decompress
zstd -d file.txt.zst

# Train a dictionary
zstd --train samples/* -o dict

# Compress with dictionary
zstd --dict dict file.txt

# Benchmark
zstd -b1 -e22 file.txt          # bench all levels

As a library

Zstd's C library provides streaming and one-shot APIs. The library is ~100 KB compiled — small enough for embedded systems. Bindings exist for every major language.

Key API features:

  • Streaming compression/decompression — process data in chunks without buffering the entire input
  • Multi-threaded compression — split input into sections compressed in parallel (decompression is always single-threaded since it's already fast)
  • Dictionary preloading — compile a dictionary once, reuse for many compression operations
  • Pledged source size — tell the compressor how much data is coming so it can optimize frame parameters

Adoption

Zstandard's adoption has been rapid since its standardization (RFC 8478, 2018):

Domain Examples
Operating systems Linux kernel (initramfs, Btrfs, SquashFS), FreeBSD
Databases RocksDB, ClickHouse, MySQL 8.0, CockroachDB, ScyllaDB
Package managers Arch Linux (pacman), Fedora RPMs, FreeBSD packages, Debian (.deb)
Web HTTP Content-Encoding: zstd (RFC 8878), supported in all major browsers
Big data Apache Parquet, ORC, Kafka, Hadoop
Logging Facebook's LogDevice, various log pipeline compression
Gaming Unreal Engine, Unity asset compression

Zstd vs Everything Else

How does Zstandard compare to other compressors across the speed/ratio spectrum?

Compressor Ratio (silesia corpus) Compress speed Decompress speed Sweet spot
LZ4 (default) 2.1:1 780 MB/s 4200 MB/s Maximum speed (caches, IPC)
zstd -1 2.8:1 510 MB/s 1500 MB/s Fast general purpose
zstd -3 (default) 2.9:1 350 MB/s 1400 MB/s Default general purpose
gzip -6 3.1:1 30 MB/s 350 MB/s Universal compatibility
zstd -9 3.2:1 50 MB/s 1400 MB/s Better than gzip, 4× faster decompress
bzip2 -9 3.4:1 10 MB/s 40 MB/s Legacy text compression
zstd -19 3.5:1 5 MB/s 1400 MB/s Near-LZMA ratio, fast decompress
xz -9 (LZMA2) 3.6:1 2 MB/s 100 MB/s Maximum compression

Zstd's unique position

No other compressor covers this range. At level 1, zstd matches gzip's ratio at 15× the speed. At level 19, it nearly matches LZMA's ratio while decompressing 14× faster. And decompression speed is nearly constant across all levels — the decoder doesn't care how hard the encoder worked.

The Technology Behind the Speed

Why is zstd decompression so fast? Several architectural decisions:

Table-based entropy decoding. FSE decoding is a single table lookup per symbol — no multiplication, no division. Huffman decoding uses a single table lookup with a fixed bit read. This is fundamentally faster than arithmetic/range coding's multiply-per-symbol.

Branchless critical paths. The inner decompression loops are written to minimize branch mispredictions. The decoder reads bits, indexes into tables, and copies bytes in a tight loop with very few conditional branches.

4-stream Huffman. Literals are decoded in 4 parallel streams, using instruction-level parallelism (ILP) within a single core. While one stream waits for a table lookup result, others make progress.

Memory-copy-dominated. For many inputs, decompression is dominated by memcpy — copying literal bytes and match data. Modern CPUs execute memcpy at near-memory-bandwidth speeds, making decompression essentially I/O bound.

Try It Yourself — Zstandard Compression

Enter text and see how Zstandard encodes it. The output shows the sequence decomposition (literals + matches), repeated offset usage, and compression statistics. Compare different inputs to see how structured vs random data affects the ratio.

Sequence Decomposition

Repeated Offsets

Compression Statistics

Key Takeaways

  • Zstandard frames contain blocks, each with a literals section (Huffman) and a sequences section (FSE)
  • FSE tables are transmitted compactly in each block header, or default/repeated tables are used for small blocks
  • Three repeated offsets dramatically reduce the cost of encoding structured data with recurring match distances
  • 4-stream parallel Huffman decoding and branchless FSE decoding drive decompression speeds above 1 GB/s
  • Compression levels 1–22 control search depth and parsing strategy; decompression speed is constant
  • Dictionary compression pre-populates the sliding window with trained patterns, enabling 3–4× better compression on small records
  • Zstd uniquely spans the entire speed/ratio spectrum, from faster-than-gzip to near-LZMA compression

End of the road — for now

From RLE's simplest possible idea (count the runs) to Zstandard's FSE tables and optimal parsing, we've traced the entire arc of compression. The fundamental principles have been the same throughout: find redundancy (runs, repeated sequences, statistical skew, temporal correlation, perceptual irrelevance) and encode what remains as efficiently as possible (Huffman, arithmetic coding, ANS/FSE, range coding).

Every compressed file you encounter — every .gz, .7z, .zst, .jpg, .mp4 — uses some combination of these building blocks. The art is in how you combine them.