Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Dictionaries

A dictionary primes the encoder with content that responses are likely to share, so short responses compress much better. It helps most with short responses that resemble it, such as small JSON documents; on long ones the gain is small.

Only clients that already have the dictionary can decode these responses. They are sent with Content-Encoding: zstd, as with tokers/zstd-nginx-module, and nothing in the response tells a client which dictionary it needs; browsers do not have it and fail to decode them. Use it only for clients you control. Compression dictionary transport (RFC 9842, Content-Encoding: dcz) is not supported.

Train and configure

Train a dictionary on samples of your responses with the zstd tool, then point zstd_dict_file at it:

zstd --train samples/*.json -o /etc/nginx/api.dict
location /internal-api/ {
    proxy_pass http://127.0.0.1:8080;
    zstd on;
    zstd_types application/json;
    zstd_dict_file api.dict;   # relative to the directory of nginx.conf
}

Clients decode with the same file:

curl -s -H 'Accept-Encoding: zstd' http://localhost/internal-api/items \
    | zstd -d -D /etc/nginx/api.dict

Which files are accepted

Both kinds of dictionary that zstd reads are accepted:

  • one in the Zstandard format, such as zstd --train produces, whose ID each frame names;
  • raw content, any file without the dictionary magic number, which the frames do not name.

How it is loaded

  • The file is read once, when the configuration is loaded, and a malformed Zstandard dictionary is rejected there.
  • It is prepared once for each zstd_comp_level and zstd_window that locations with zstd on use it with, and the prepared copies are shared by all such locations.
  • With zstd_dict_file off, a location inherits no dictionary.
  • Responses compressed with a dictionary are compressed in the event loop even with zstd_thread_pool: the parallel compressor does not take dictionaries.

In tokers/zstd-nginx-module the directive is only allowed in http and has no off.