Zstandard compression with compression.zstd
suggest changeZstandard (zstd) is a compression format from Meta. At its default level it compresses about as well as gzip, but it compresses several times faster and decompresses faster too. At high levels it gets close to xz/lzma. It is used by Linux kernels and package managers, databases, HTTP (Content-Encoding: zstd), and many file formats.
Python 3.14 added zstd to the standard library as compression.zstd (PEP 784). The same PEP added a new compression package that collects all the compression modules in one place.
| Version | Change |
|---|---|
| 3.14 | compression.zstd module, the compression package (compression.gzip, .bz2, .lzma, .zlib) |
| 3.14 | zstd support in tarfile ("w:zst"), zipfile (ZIP_ZSTANDARD) and shutil ("zstdtar") |
| older | pip install backports.zstd, which has the same API |
All examples were run with Python 3.14.4 (bundled libzstd 1.5.7) on Linux. The zstd module is optional: it is only built when libzstd is available, which is the case for the official installers and the usual Linux packages.
Compressing and decompressing bytes
compress() and decompress() work like the functions in gzip, bz2 and lzma:
from compression import zstd
data = b"Hello, Zstandard! " * 1000
packed = zstd.compress(data)
print(len(data), "->", len(packed))
print(packed[:4])
restored = zstd.decompress(packed)
print(restored == data)
18000 -> 36
b'(\xb5/\xfd'
True
Every zstd frame starts with the magic number 28 b5 2f fd. compress() returns one complete frame. Files with the .zst extension, created by the zstd command line tool, have the same format, so data written by Python can be read by zstd -d and the other way round.
Compression levels
The level argument goes from 1 (fastest) to 22 (smallest). The default is 3. Negative levels down to -131072 are even faster and compress less:
from compression import zstd
print(zstd.COMPRESSION_LEVEL_DEFAULT)
print(zstd.CompressionParameter.compression_level.bounds())
packed = zstd.compress(b"abc" * 1000, level=19)
3
(-131072, 22)
To see how the levels compare to the older formats, here is a benchmark that compresses about 4.7 MB of Python source code (the top-level .py files of the standard library):
import bz2, lzma, os, pathlib, sysconfig, time, zlib
from compression import zstd
# about 5 MB of real-world text: the standard library's own source files
stdlib = pathlib.Path(sysconfig.get_path("stdlib"))
data = b"".join(p.read_bytes() for p in sorted(stdlib.glob("*.py")))
print("cpu_count:", os.cpu_count(), " input:", len(data), "bytes")
def bench(name, comp, decomp):
t0 = time.perf_counter(); packed = comp(data); t1 = time.perf_counter()
assert decomp(packed) == data; t2 = time.perf_counter()
print(f"{name:8} {len(packed):8} bytes {len(data)/len(packed):4.1f}x"
f" compress {1000*(t1-t0):6.0f} ms decompress {1000*(t2-t1):4.0f} ms")
bench("zlib 6", lambda d: zlib.compress(d, 6), zlib.decompress)
bench("bz2 9", lambda d: bz2.compress(d, 9), bz2.decompress)
bench("lzma 6", lambda d: lzma.compress(d, preset=6), lzma.decompress)
for lvl in (-5, 1, 3, 9, 19):
bench(f"zstd {lvl}", lambda d: zstd.compress(d, level=lvl), zstd.decompress)
cpu_count: 24 input: 4767935 bytes
zlib 6 1172445 bytes 4.1x compress 227 ms decompress 30 ms
bz2 9 976064 bytes 4.9x compress 362 ms decompress 149 ms
lzma 6 911804 bytes 5.2x compress 3065 ms decompress 76 ms
zstd -5 1944564 bytes 2.5x compress 16 ms decompress 9 ms
zstd 1 1321798 bytes 3.6x compress 23 ms decompress 6 ms
zstd 3 1204660 bytes 4.0x compress 31 ms decompress 13 ms
zstd 9 1046929 bytes 4.6x compress 231 ms decompress 12 ms
zstd 19 926721 bytes 5.1x compress 3449 ms decompress 6 ms
Timings differ between runs and machines, but the pattern holds:
- zstd level 3 compresses as well as zlib level 6 and does it about 7 times faster.
- zstd level 19 is about as small as lzma and as slow to compress, but decompression is much faster. This is a good choice for data you compress once and read many times, like release artifacts.
- Decompression speed hardly depends on the level.
Reading and writing .zst files
zstd.open() works like gzip.open(). In text mode ("rt", "wt") it also encodes and decodes the text:
import os
from compression import zstd
# text mode: encode/decode and compress/decompress in one step
with zstd.open("events.log.zst", "wt", encoding="utf-8", level=10) as f:
for i in range(1000):
f.write(f"2026-10-18T12:{i // 60 % 60:02}:{i % 60:02} INFO request {i} handled in {i % 17} ms\n")
print(os.path.getsize("events.log.zst"), "bytes on disk")
with zstd.open("events.log.zst", "rt", encoding="utf-8") as f:
for line in f:
if "request 500 " in line:
print(line, end="")
# binary mode
with zstd.open("events.log.zst") as f: # default mode is "rb"
print(f.read(19))
print(type(f).__name__)
4045 bytes on disk
2026-10-18T12:08:20 INFO request 500 handled in 7 ms
b'2026-10-18T12:00:00'
ZstdFile
In binary mode open() returns a ZstdFile, a regular file object with read(), readline(), iteration, seek() and write(). You can also pass an already open file object instead of a file name, for example a socket file or an io.BytesIO.
Because a ZstdFile is a file object, shutil.copyfileobj() compresses or decompresses a file of any size in chunks, without loading it all into memory:
import os, shutil
from compression import zstd
with open("big.bin", "wb") as f:
for i in range(200_000):
f.write(f"row {i}: {'x' * (i % 50)}\n".encode())
with open("big.bin", "rb") as src, zstd.open("big.bin.zst", "wb", level=6) as dst:
shutil.copyfileobj(src, dst)
with zstd.open("big.bin.zst") as src, open("big.out", "wb") as dst:
shutil.copyfileobj(src, dst)
print(open("big.bin", "rb").read() == open("big.out", "rb").read())
print(os.path.getsize("big.bin"), os.path.getsize("big.bin.zst"))
True
7388890 221169
Multiple frames
A zstd file can contain several frames one after another, and they decompress to the concatenation of their contents. Opening a file in "a" mode adds a new frame at the end, which is handy for log files:
from compression import zstd
with zstd.open("multi.zst", "wb") as f:
f.write(b"first frame\n")
with zstd.open("multi.zst", "ab") as f:
f.write(b"second frame\n")
with zstd.open("multi.zst") as f:
print(f.read())
raw = open("multi.zst", "rb").read()
print(zstd.decompress(raw)) # decompress() also reads all frames
size = zstd.get_frame_size(raw)
print(size, len(raw))
print(zstd.decompress(raw[:size]))
b'first frame\nsecond frame\n'
b'first frame\nsecond frame\n'
21 43
b'first frame\n'
get_frame_size() returns the size of the first frame, so you can split a buffer into frames without decompressing it.
Advanced options
Instead of level you can pass options, a dict that maps CompressionParameter members to integers. You can pass level or options, not both. To use a level together with other options, put the level in the dict as compression_level:
from compression.zstd import CompressionParameter as CP, compress, decompress, get_frame_info
data = b"some data to compress " * 500
options = {
CP.compression_level: 10,
CP.checksum_flag: 1, # store a 32-bit checksum of the content
CP.content_size_flag: 1, # store the original size in the header (default)
}
packed = compress(data, options=options)
print(len(packed))
print(get_frame_info(packed))
print(CP.window_log.bounds())
print(CP.nb_workers.bounds())
try:
compress(data, options={CP.window_log: 40})
except Exception as e:
print(type(e).__name__, e)
try:
compress(data, level=3, options={CP.checksum_flag: 1})
except Exception as e:
print(type(e).__name__, e)
bad = bytearray(packed); bad[20] ^= 0xFF
try:
decompress(bytes(bad))
except Exception as e:
print(type(e).__name__, e)
44
FrameInfo(decompressed_size=11000, dictionary_id=0)
(10, 31)
(0, 256)
ValueError compression parameter 'window_log' received an illegal value 40; the valid range is [10, 31]
TypeError Only one of level or options should be used.
ZstdError Unable to decompress Zstandard data: Restored data doesn't match checksum
Without checksum_flag (it is off by default) zstd doesn't check the content, so some kinds of corruption go unnoticed. Turn it on for data that is stored or sent over the network. get_frame_info() reads the frame header without decompressing anything. decompressed_size is None when the size isn't stored, for example in streams written by ZstdCompressor.
The most useful parameters:
| Parameter | Meaning |
|---|---|
compression_level |
same as level |
checksum_flag |
add a checksum that decompress() verifies |
nb_workers |
number of threads for compression, 0 means single-threaded |
job_size |
size of the piece each worker compresses |
window_log |
log2 of how far back zstd looks for matches |
enable_long_distance_matching |
find repeats far apart, use with a big window_log |
strategy |
match finding algorithm, a zstd.Strategy member (fast ... btultra2) |
Each parameter has a bounds() method that returns the allowed (min, max) range for the libzstd version Python uses.
Multi-threaded compression
With nb_workers greater than 0, compression runs in background threads inside libzstd. Each worker compresses one job. The default job size is several times the window size, so for inputs of a few megabytes there is just one job and no speedup. A smaller job_size fixes that:
import os, pathlib, sysconfig, time
from compression.zstd import CompressionParameter as CP, compress
stdlib = pathlib.Path(sysconfig.get_path("stdlib"))
data = b"".join(p.read_bytes() for p in sorted(stdlib.rglob("*.py")))
print("cpu_count:", os.cpu_count(), " input:", len(data), "bytes")
for workers in (0, 2, 4, 8):
t0 = time.perf_counter()
packed = compress(data, options={CP.compression_level: 15, CP.nb_workers: workers, CP.job_size: 1 << 20})
print(f"nb_workers={workers}: {len(packed)} bytes in {time.perf_counter() - t0:.2f} s")
cpu_count: 24 input: 11151424 bytes
nb_workers=0: 2084040 bytes in 3.41 s
nb_workers=2: 2128948 bytes in 2.26 s
nb_workers=4: 2128948 bytes in 1.32 s
nb_workers=8: 2128948 bytes in 0.92 s
The output is about 2% bigger with small jobs, because matches can't cross job boundaries. Decompression is always single-threaded.
Long distance matching and the window size
zstd only finds repeated data inside its window, which is 8 MB or less for levels up to 19. Data that repeats further apart (for example backups, VM images or similar files in one archive) needs long distance matching and a bigger window:
import os
from compression.zstd import CompressionParameter as CP, DecompressionParameter as DP
from compression.zstd import ZstdCompressor, ZstdError, compress, decompress
chunk = os.urandom(32 * 1024 * 1024) # 32 MB of random bytes ...
data = chunk + chunk # ... repeated once, 32 MB apart
print(len(compress(data, level=3)))
opts = {CP.compression_level: 3, CP.enable_long_distance_matching: 1, CP.window_log: 28}
comp = ZstdCompressor(options=opts) # streaming: total size isn't known up front
packed = comp.compress(data) + comp.flush()
print(len(packed))
try:
decompress(packed)
except ZstdError as e:
print(e)
print(decompress(packed, options={DP.window_log_max: 28}) == data)
67110410
33562108
Unable to decompress Zstandard data: Frame requires too much memory for decoding
True
Without long distance matching the output is a bit larger than the input: random data doesn't compress and zstd never sees the repeat. With it, the second copy costs almost nothing.
The decoder needs memory equal to the window size. By default it refuses windows bigger than 128 MB (window_log 27), which protects you from files that ask for gigabytes of memory. If you trust the data, raise the limit with DecompressionParameter.window_log_max. (compress() knows the input size, so it shrinks the window to fit the data. That's why this example uses a ZstdCompressor.)
Streaming with ZstdCompressor and ZstdDecompressor
When data arrives in pieces, for example from a socket or a generator, use the incremental classes. ZstdCompressor.compress() returns whatever compressed output is ready, which is often nothing, and flush() returns the rest and ends the frame:
from compression.zstd import ZstdCompressor, ZstdDecompressor
comp = ZstdCompressor(level=5)
out = []
for i in range(3):
piece = comp.compress(f"message {i}\n".encode() * 100)
print("compress() returned", len(piece), "bytes")
out.append(piece)
out.append(comp.flush()) # FLUSH_FRAME by default: ends the frame
print("flush() returned", len(out[-1]), "bytes")
stream = b"".join(out)
decomp = ZstdDecompressor()
result = b""
for i in range(0, len(stream), 16): # feed 16 bytes at a time
result += decomp.decompress(stream[i:i + 16])
print(len(result), decomp.eof, decomp.needs_input)
print(result[:22])
compress() returned 0 bytes
compress() returned 0 bytes
compress() returned 0 bytes
flush() returned 33 bytes
3000 True False
b'message 0\nmessage 0\nme'
The decompressor accepts input of any size, even cut in the middle of a block. eof becomes True at the end of the frame.
For a message protocol, where the other side must be able to decode each message right away, compress each message with ZstdCompressor.FLUSH_BLOCK. It pushes out everything written so far but keeps the frame open, so later messages can still use earlier ones as context:
from compression.zstd import ZstdCompressor, ZstdDecompressor
comp = ZstdCompressor()
decomp = ZstdDecompressor()
for msg in [b"hello", b"how are you?", b"bye"]:
packet = comp.compress(msg, ZstdCompressor.FLUSH_BLOCK)
print(len(packet), decomp.decompress(packet))
packet = comp.flush() # end the frame
print(len(packet), decomp.decompress(packet), decomp.eof)
14 b'hello'
15 b'how are you?'
6 b'bye'
3 b'' True
The modes are ZstdCompressor.CONTINUE (the default for compress()), FLUSH_BLOCK and FLUSH_FRAME (the default for flush()).
A ZstdDecompressor decodes exactly one frame. Anything after the frame ends up in unused_data, and feeding more data raises EOFError. To read a stream of several frames, create a new decompressor for the rest, or use ZstdFile, which does that for you:
from compression import zstd
frame = zstd.compress(b"payload")
d = zstd.ZstdDecompressor()
print(d.decompress(frame + b"trailing junk"))
print(d.eof, d.unused_data)
try:
d.decompress(b"more")
except EOFError as e:
print("EOFError:", e)
b'payload'
True b'trailing junk'
EOFError: Already at the end of a Zstandard frame.
ZstdDecompressor.decompress() also takes max_length, which limits how many bytes one call returns. That protects you from "zip bombs" that expand a small input into gigabytes.
Dictionaries for small records
Compressors learn the data as they go, so tiny inputs like a single JSON record compress badly: there is nothing to learn from yet. A zstd dictionary solves this. You train it once on sample records, and then each record is compressed using what the dictionary already knows:
import json, random
from compression import zstd
random.seed(1)
cities = ["Berlin", "Paris", "Warsaw", "Lisbon", "Oslo", "Madrid", "Rome", "Vienna"]
def make_record(i):
return json.dumps({
"id": i,
"username": f"user_{random.randint(1000, 99999)}",
"email": f"user{i}@example.com",
"city": random.choice(cities),
"active": random.random() < 0.8,
"roles": random.sample(["admin", "editor", "viewer", "billing"], k=2),
"last_login": f"2026-10-{random.randint(1, 28):02}T{random.randint(0, 23):02}:00:00Z",
}).encode()
samples = [make_record(i) for i in range(2000)]
print("one record:", len(samples[0]), "bytes")
zdict = zstd.train_dict(samples, 4096)
print(zdict.dict_id, len(zdict.dict_content))
records = [make_record(i) for i in range(2000, 2100)] # new data, not in training set
raw = sum(len(r) for r in records)
plain = sum(len(zstd.compress(r)) for r in records)
with_dict = sum(len(zstd.compress(r, zstd_dict=zdict)) for r in records)
print(f"raw {raw}, compressed {plain}, compressed with dictionary {with_dict}")
packed = zstd.compress(records[0], zstd_dict=zdict)
print(zstd.get_frame_info(packed))
print(zstd.decompress(packed, zstd_dict=zdict) == records[0])
try:
zstd.decompress(packed)
except zstd.ZstdError as e:
print(e)
# save and load the dictionary
open("users.dict", "wb").write(zdict.dict_content)
loaded = zstd.ZstdDict(open("users.dict", "rb").read())
print(loaded.dict_id == zdict.dict_id, zstd.decompress(packed, zstd_dict=loaded) == records[0])
one record: 168 bytes
1190077169 4096
raw 17339, compressed 15014, compressed with dictionary 4316
FrameInfo(decompressed_size=173, dictionary_id=1190077169)
True
Unable to decompress Zstandard data: Dictionary mismatch
True True
Without a dictionary the 100 records shrink by only 13%. With a 4 KB dictionary they shrink to a quarter of their size.
Things to know about dictionaries:
train_dict(samples, dict_size)needs many samples (hundreds or thousands);dict_sizeis the maximum size in bytes. A few KB to about 100 KB is typical.- The same dictionary is needed to decompress. Store
dict_contentwith your data or ship it with your application. The frame header recordsdict_idso you can tell which dictionary a frame needs. finalize_dict(zstd_dict, samples, dict_size, level)turns your own raw content (aZstdDict(data, is_raw=True)) into a proper dictionary tuned on samples.- When you compress many records with the same dictionary, pass
zdict.as_digested_dict. It's slower to load once but faster for each later call. - Retrain when your data's shape changes. A dictionary trained on old records helps less with new fields.
Using a previous version as a prefix
as_prefix uses raw data as one-time context. If you already have the previous version of a file, only the differences need to be stored:
from compression import zstd
old = b"".join(f"line {i}: status=ok value={i * 3}\n".encode() for i in range(2000))
new = old.replace(b"line 1500: status=ok", b"line 1500: status=FAILED")
prefix = zstd.ZstdDict(old, is_raw=True)
delta = zstd.compress(new, zstd_dict=prefix.as_prefix)
print(len(new), len(zstd.compress(new)), len(delta))
print(zstd.decompress(delta, zstd_dict=prefix.as_prefix) == new)
62522 4460 204
True
The compression package
Python 3.14 also added the compression package, so all the compression modules can be imported from one place. compression.gzip, compression.bz2, compression.lzma and compression.zlib re-export the existing top-level modules:
import gzip
from compression import gzip as cgzip, bz2, lzma, zlib, zstd
print(cgzip.GzipFile is gzip.GzipFile) # a re-export of the old module
data = b"same API everywhere " * 100
for mod in (cgzip, bz2, lzma, zlib, zstd):
packed = mod.compress(data)
print(f"{mod.__name__:18} {len(packed):4} bytes", mod.decompress(packed) == data)
True
compression.gzip 57 bytes True
compression.bz2 83 bytes True
compression.lzma 104 bytes True
compression.zlib 45 bytes True
compression.zstd 38 bytes True
The old names (import gzip) keep working and aren't deprecated. PEP 784 says there are no plans to deprecate them, and that any deprecation would come no sooner than 5 years after the PEP was accepted. New code that targets 3.14+ can use either name. zstd only exists inside the package; there is no top-level zstd module in the standard library.
zstd in tar and zip archives
tarfile, zipfile and shutil understand zstd in 3.14:
import os, pathlib, tarfile, zipfile, shutil
src = pathlib.Path("project")
src.mkdir(exist_ok=True)
for i in range(5):
(src / f"module{i}.py").write_text(f"def f{i}():\n return {i}\n" * 200)
with tarfile.open("project.tar.zst", "w:zst") as tar:
tar.add(src)
with tarfile.open("project.tar.zst") as tar: # "r:*" detects zstd
print(tar.getnames())
with zipfile.ZipFile("project.zip", "w", compression=zipfile.ZIP_ZSTANDARD, compresslevel=10) as zf:
for p in sorted(src.iterdir()):
zf.write(p)
with zipfile.ZipFile("project.zip") as zf:
info = zf.infolist()[0]
print(info.filename, info.compress_type, info.file_size, info.compress_size)
print(zf.read(info).decode().splitlines()[0])
print([name for name, _ in shutil.get_archive_formats()])
archive = shutil.make_archive("backup", "zstdtar", root_dir=src)
print(os.path.basename(archive))
shutil.unpack_archive(archive, "restored")
print(sorted(os.listdir("restored")))
['project', 'project/module0.py', 'project/module1.py', 'project/module2.py', 'project/module3.py', 'project/module4.py']
project/module0.py 93 4600 40
def f0():
['bztar', 'gztar', 'tar', 'xztar', 'zip', 'zstdtar']
backup.tar.zst
['module0.py', 'module1.py', 'module2.py', 'module3.py', 'module4.py']
tarfile.open() with "w:zst" also accepts level=, options= and zstd_dict=. A .tar.zst file can be unpacked with tar --zstd -xf on the command line.
Zstandard in ZIP files is method 93 of the ZIP specification. It is much less widely supported than the classic deflate method: many tools, including older versions of Windows Explorer and Info-ZIP unzip, can't open such files. Use it for archives that your own programs read, and stick with ZIP_DEFLATED for files you hand to other people (see Working with ZIP files).
Supporting older Python versions
The backports.zstd package has the same API for Python 3.10 to 3.13:
try:
from compression import zstd # Python 3.14+
except ImportError:
from backports import zstd # pip install backports.zstd
print(zstd.decompress(zstd.compress(b"ok")))
b'ok'
The older third-party packages zstandard and pyzstd have different APIs. compression.zstd is based on pyzstd, so code using pyzstd is the easiest to port.
Summary
from compression import zstd(Python 3.14+).zstd.compress(data, level=...)andzstd.decompress(data)handle bytes.- Levels go from 1 to 22, the default is 3, and negative levels are even faster. Level 3 is about as small as gzip and several times faster; level 19 is close to lzma and decompresses much faster.
zstd.open()reads and writes.zstfiles in binary or text mode and supportsshutil.copyfileobj()streaming.options={CompressionParameter...: value}enables checksums, multi-threading (nb_workers,job_size), long distance matching and bigger windows. Useleveloroptions, not both.ZstdCompressorandZstdDecompressorwork incrementally.FLUSH_BLOCKsends each message right away and keeps the frame open.train_dict()builds a dictionary that makes small records compress several times better. You need the same dictionary to decompress.tarfile("w:zst"),zipfile(ZIP_ZSTANDARD) andshutil("zstdtar") support zstd. On older Pythons usebackports.zstd.