8. ANS & Zstandard

Modern compression: fast and optimal

We've reached a tension in entropy coding:

  • Huffman coding is fast (table lookups) but suboptimal (integer bits per symbol)
  • Arithmetic coding is optimal (fractional bits) but slow (multiply + shift per symbol, strictly sequential output)

What if we could have both — the optimality of arithmetic coding at the speed of a table lookup? That's ANS (Asymmetric Numeral Systems), developed by Jarosław Duda starting around 2007–2009. It's the entropy coding method behind Zstandard, the modern compression standard that's rapidly replacing gzip.

The Intuition Behind ANS

Think of encoding as building a single large integer, one symbol at a time. You start with a state number. Each symbol you encode transforms the state into a larger number. The clever part is how much the number grows:

Growth rate encodes information

A common symbol (high probability) makes the state number grow by a small factor. A rare symbol makes it grow by a large factor. The final state number IS the compressed data. Since common symbols contribute less to its size, the total size naturally approaches the Shannon entropy — optimal compression!

This is similar to arithmetic coding's narrowing interval, but expressed as integer growth rather than interval subdivision. This difference has profound implications for speed.

uABS: The Simplest ANS

To build intuition, consider the simplest case: two symbols, 0 and 1, with probabilities p and (1−p). The idea is to interleave the natural numbers between the two symbols in proportion to their probabilities.

Example: p(a) = 2/3, p(b) = 1/3

Distribute natural numbers so that symbol 'a' gets 2/3 of the slots and 'b' gets 1/3:

State:   1  2  3  4  5  6  7  8  9  10  11  12 ...
Symbol:  a  b  a  a  b  a  a  b  a   a   b   a ...

Every 3rd slot goes to 'b', the rest go to 'a'. This pattern ensures the encoding naturally uses ≈ −log₂(2/3) ≈ 0.58 bits for 'a' and −log₂(1/3) ≈ 1.58 bits for 'b' — exactly the ideal costs.

Encoding symbol 's' from state x means: find the next slot for symbol 's' at or after position x. The new state is that slot's index. Decoding is the reverse: given a state, determine which symbol it corresponds to and compute the previous state.

tANS: Table-Based ANS

The practical breakthrough is tANS (tabled ANS). Instead of computing the interleaving mathematically, precompute everything into lookup tables:

  1. Choose a table size L (a power of 2, e.g., 2048)

    The state will be kept in the range [L, 2L). Larger L = more precise probability modeling but bigger tables.

  2. Distribute symbols across L slots proportional to their probabilities

    If symbol 'a' has probability 0.4 and L = 2048, then 'a' gets about 819 slots. The exact distribution determines the compression quality.

  3. Build the encoding table

    Maps (current_state, symbol) → (new_state, bits_to_output). When the new state would exceed 2L, output some bits first (renormalization) to bring it back into range.

  4. Build the decoding table

    Maps state → (symbol, previous_state, bits_to_read). One table lookup per symbol — that's it.

Why tANS is so fast

Encoding one symbol = one table lookup + possible bit output.
Decoding one symbol = one table lookup + possible bit read.
No multiplication. No division. Just array indexing. This is as fast as Huffman decoding — but with arithmetic-coding-level compression.

ANS vs Arithmetic Coding

Arithmetic Coding ANS (tANS)
Compression Optimal Near-optimal (approaches optimal as L increases)
Encode speed Multiply + branch per symbol Table lookup per symbol
Decode speed Multiply + branch per symbol Table lookup per symbol
Output order FIFO (first in, first out) LIFO (last in, first out) — encodes in reverse
Parallelism Hard — strictly sequential Easy — multiple independent streams
Patents Were patented (IBM), now expired Patent-free by design (Duda's explicit choice)

The LIFO property means ANS encodes symbols in reverse order — the last symbol encoded is the first one decoded. Practical compressors handle this by encoding backwards through each block, so the decoder reads forwards naturally.

Zstandard (zstd) — The Modern Compressor

Zstandard was created by Yann Collet at Facebook in 2015–2016 and standardized as RFC 8478. It combines LZ77-style matching with ANS-based entropy coding (via Collet's FSE — Finite State Entropy, a tANS implementation).

                Zstandard
┌──────────────────────────────────────┐
│                                      │
│   Input                              │
│     │                                │
│     ▼                                │
│   ┌──────────────┐                   │
│   │  LZ77-style  │  Match finding    │
│   │  parsing     │                   │
│   └──────┬───────┘                   │
│          │                           │
│          ▼                           │
│   Sequences of:                      │
│   (literals, match_offset,           │
│    match_length)                     │
│          │                           │
│     ┌────┴────┐                      │
│     │         │                      │
│     ▼         ▼                      │
│   Huffman    FSE (tANS)              │
│   for        for offsets             │
│   literals   and lengths             │
│     │         │                      │
│     └────┬────┘                      │
│          │                           │
│          ▼                           │
│   Compressed frame                   │
│                                      │
└──────────────────────────────────────┘

Zstandard encodes data as a sequence of "sequences", each containing:

  • Literals — raw bytes that didn't match. Encoded with Huffman.
  • Match offset — how far back to look. Encoded with FSE (tANS).
  • Match length — how many bytes to copy. Encoded with FSE (tANS).

Why Huffman for literals and FSE for offsets/lengths? Literals have a large alphabet (256 values) where Huffman works well. Offsets and lengths have more skewed distributions where FSE's fractional-bit advantage matters more.

Why Zstandard Is Revolutionary

Speed-ratio tradeoff

Zstandard offers 22 compression levels (-1 to 22), spanning an enormous range:

Level Comparison Speed
-1 to 3 Similar ratio to gzip, 3–5× faster 500–1000 MB/s compress
6–9 Better than gzip -9 50–100 MB/s compress
19–22 Better than bzip2 2–5 MB/s compress

Decompression is always fast: 1000+ MB/s regardless of compression level. This asymmetry (slow encode, fast decode) is ideal for scenarios where data is compressed once and decompressed many times.

Dictionary mode

Zstandard has a unique feature: trained dictionaries. You can train a dictionary on a collection of similar small files (JSON records, log lines, protocol messages), and then use it to compress each individual file.

This is a game-changer for databases and network protocols: small records (1–10 KB) that are individually hard to compress become highly compressible when the compressor knows the common patterns in advance. Without a dictionary, there's not enough data for the LZ77 stage to find matches.

Where Zstandard is used

System Use case
Linux kernel Kernel image compression, initramfs, Btrfs filesystem
Facebook/Meta Warehouse data, cache compression, network transfer
Databases RocksDB, ClickHouse, MySQL 8.0, PostgreSQL extensions
Package managers Arch Linux packages, Fedora RPMs, FreeBSD packages
Filesystems Btrfs, OpenZFS
HTTP Supported in browsers (Content-Encoding: zstd)

The Modern Compression Landscape

Zstandard didn't appear in isolation. Here's how the modern tools relate to the algorithms we've covered:

Tool LZ stage Entropy coder Niche
gzip/zlib LZ77 Huffman Universal compatibility
bzip2 BWT Huffman Best text compression (legacy)
LZMA/7-Zip LZ77 Range coding Maximum compression
LZ4 LZ77 None (raw) Maximum speed
Zstandard LZ77 FSE (tANS) + Huffman Best all-round
Brotli LZ77 Huffman + ANS ideas Web content

The Full Picture — How It All Connects

We've covered eight algorithms. Here's how they all fit together:

  THE BUILDING BLOCKS OF COMPRESSION

┌─────────────────────────────────────────────────┐ │ Finding Redundancy │ │ │ │ RLE (1967) Simple runs │ │ │ │ │ ▼ │ │ LZ77 (1977) Repeated sequences │ │ │ (sliding window) │ │ ├──► LZ78 (1978) → LZW (1984) → GIF │ │ │ │ │ ▼ │ │ BWT (1994) Context clustering │ │ │ (sort rotations) │ │ ▼ │ │ bzip2 = BWT + MTF + RLE + Huffman │ └─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐ │ Entropy Coding │ │ (turning probabilities into bits) │ │ │ │ Huffman (1952) Integer bits per symbol │ │ │ │ │ ▼ │ │ Arithmetic (1976) Fractional bits — optimal │ │ │ │ │ ▼ │ │ ANS (2009) Optimal at lookup speed │ └─────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────┐ │ Combined Systems │ │ │ │ DEFLATE (1993) = LZ77 + Huffman → gzip │ │ LZMA (1998) = LZ77 + Range coding→ 7-Zip │ │ Zstandard (2015)= LZ77 + FSE/Huffman → zstd │ └─────────────────────────────────────────────────┘

The pattern is always the same: find redundancy (LZ77, BWT, or similar), then encode efficiently (Huffman, arithmetic, or ANS). The history of compression is the history of doing both of these things better.

Try It Yourself — tANS Encoder & Decoder

Type a message (at least 2 distinct symbols) and watch tANS in action. The table size L controls precision — larger tables model probabilities more accurately. The colored slot grid shows how symbols are distributed across states. Switch to Decode mode to see the decoder recover the message from just the final state and bit output using table lookups.

Symbol Distribution

State Table (slots L to 2L−1)

Encoding Steps

Compressed Output

Statistics

Key Takeaways

  • ANS achieves arithmetic-coding-level compression at Huffman-coding speed
  • tANS uses precomputed tables — encoding and decoding are single table lookups
  • ANS is patent-free by design, enabling widespread adoption
  • Zstandard combines LZ77 matching with FSE (tANS) entropy coding
  • zstd offers a huge range of speed/ratio tradeoffs (levels -1 to 22) with consistently fast decompression
  • Dictionary mode enables effective compression of small records
  • The fundamental ideas — redundancy elimination and entropy coding — are what all these algorithms share

You made it!

You've now seen the complete picture of lossless compression: from counting repeated characters (RLE) to building optimal lookup tables (ANS). Every compressed file you encounter — every .gz, .zip, .png, .mp4, every web page served with Content-Encoding — uses some combination of these ideas.

The key insight that ties everything together: compression is about finding and exploiting patterns. Different algorithms find different kinds of patterns. The art is in combining them.