Replace the zstd CLI with node:zlib's built-in zstd #
Scratch-path note:
/tmp/agentpaths in this document are historical. Use~/temp/agentfor current work.
Context #
Two places in the workspace shell out to the external zstd command-line tool:
package/figma/kiwi/src/index.ts, functiondecompressZstd, decompresses the zstd-compressed document section of a Figma.fig/.deck/.jamexport. It first tries an optional native module (@bokuwatch/zstd, never declared as a dependency) and otherwise spawnszstd -dthroughnano-spawn, shuttling data through temp files.package/ssg/aquati.cat/mise.toml, taskbuild:compress, runszstd -z -f --no-check -T0 --exclude-compressed --no-content-size -r --adapt distto write a<file>.zstcompanion next to every compressible asset indist/. The companions are read bypackage/dev-script/page-weight/src/size.ts(wireSize) and exist for precompressed serving.
Both depend on the zstd binary being installed,
which the workspace declares as a mise tool
("github:facebook/zstd" = "latest" in mise.toml and mise.no-env.toml).
Node 22.15+ and Bun 1.3+ ship native Zstandard support directly in node:zlib
(zstdCompressSync,
zstdDecompressSync,
zstdCompress,
zstdDecompress,
and the streaming
createZstd* constructors).
The workspace runs Bun 1.3.14 and Node 26.3.0,
both of which expose
the full API.
Replacing the subprocess and the external tool dependency with the platform built-in
removes a tool from the install set,
removes the temp-file dance and the undeclared optional
dependency in the Figma parser,
and makes the compression step a normal in-process build script.
The decompression swap is mechanically trivial and is treated as an independent change.
The
compression swap raises real choices (compression level,
threading model,
which .zst to keep),
because the CLI flags being replaced (--adapt,
-T0,
--exclude-compressed) have no one-to-one
node:zlib equivalent.
Those choices were settled by benchmarking,
documented in full below.
This document records the decision and the complete evidence behind it. It does not itself land the change; the code edits await go-ahead.
Decision #
-
Figma
decompressZstdbecomes a one-line call tonode:zlib'szstdDecompressSync. The optional@bokuwatch/zstdpath and thezstdCLI fallback are removed, andnano-spawnis dropped from the package's dependencies (it has no other use there). This is correctness-only: one-shot decompression of a single frame, no level or threading concerns. Validated by full interop (every produced frame round-trips byte-identically) and by the package's existing integration test that decodes real.fig/.deck/.jamfiles. -
The ssg
build:compresstask becomes a build script (src/build/compress.ts, alongside the existingpostprocess.ts) that walksdist/, compresses each file withnode:zlib, and writes<file>.zst. The workspace has migrated off Bun, so this script must run under Node; the engine choice is made for Node, with Bun numbers kept only as reference. Specifics, each justified by the benchmark:- **Engine + threading:
** shard the file list across
node:worker_threads(about 8 workers, matching the physical-core count), each worker running synchronouszstdCompressSync. This is the fastest Node approach measured, and at matched ratio (level 19) it is faster than the zstd CLI itself (168 ms versus 217 ms on tmpfs for the realdist/). Three other approaches were measured and rejected: Node's asynczstdCompressviaPromise.allis pathologically slow (about 1 second at level 19, 7.8 seconds at level 22) because Node's async zlib carries a large fixed per-call overhead; the CLI's in-frame-T0multithreading is useless for many small files; the CLI's cross-file process parallelism is catastrophic (process-spawn bound, seconds to tens of seconds). Node sequentialzstdCompressSyncis the simple fallback (243 ms) if the worker_threads machinery is judged not worth it, but it does not scale with file count the way worker_threads does (2,000 files: 787 ms sequential versus 253 ms with 8 workers). Over- subscribing to all 16 logical threads is slightly slower than 8 for CPU-bound zstd. Bun's async parallel path is faster still (72 ms) but Bun is no longer the target runtime. - **Level:
** fixed level 19.
node:zlibhas no equivalent of--adapt, so a fixed level is required, and a fixed level also makes the build's output reproducible (--adaptis not; see caveats). Level 19 is the best practical ratio; under the chosen Node worker_threads engine its full wall time on the realdist/is ~168 ms (tmpfs) / ~177 ms (SSD). Level 15 is the knee of the ratio curve (within 0.1 percentage points of level 19's ratio at ~20% less time: ~141 ms / ~146 ms) and is the better pick only if dev-rebuild latency is ever a felt pain; since precompressed assets are paid for once and served repeatedly, level 19 is preferred. - **Exclusion policy ("keep if smaller" + extension skip):
** write
<file>.zstonly when it is strictly smaller than the original, and skip known-incompressible extensions (images, fonts, video, already-compressed) without reading them. This is stricter and more correct than the CLI's--exclude-compressed(which is extension-only and can leave a.zstlarger than its source); incompressible input always grows under zstd (frame overhead), so keeping the raw bytes is the right behavior forwireSizeand for any precompressed server. The set of produced.zstfiles therefore differs from the CLI's by design.
- **Engine + threading:
** shard the file list across
-
**Remove the external tool. ** Drop
"github:facebook/zstd" = "latest"frommise.tomlandmise.no-env.tomlonce both call sites are migrated. No other workspace code invokes thezstdbinary (the lone remaining textual reference is a tool-name entry in the bash-output-filter allowlist, which is generic and harmless).
The decompression change (1) is unconditionally safe. The compression change (2) is the one the benchmark exists to justify.
Head-to-head: the current task versus the proposal #
The single most decision-relevant measurement,
framed for the Node target (the workspace is
after the Bun-to-Node migration.
Real dist/ text assets (138 files,
1,257,418 bytes raw),
full wall time
including process startup and file writes,
output dir cleared before each run.
Times are mean +/-
stddev.
The key comparison is at matched compression (level 19),
since the current --adapt
command's speed comes entirely from it choosing a weak level.
| Configuration | tmpfs (RAM) mean | SSD (btrfs+LUKS) mean | Output bytes (kept) | Ratio vs raw |
|---|---|---|---|---|
current: zstd -T0 --adapt (CLI) | 13.8 ms ± 0.4 | 33.4 ms ± 34.6 | 404,644 (level-3-equiv, nondeterministic) | 32.18% |
zstd CLI -19 -T0 (matched ratio) | 216.6 ms ± 4.9 | 232.1 ms ± 1.9 | 374,726 | 29.80% |
| proposed: node worker_threads (8), level 19 | 168.1 ms ± 9.4 | 177.3 ms ± 4.2 | 374,726 | 29.80% |
| proposed: node worker_threads (8), level 15 | 141.4 ms ± 10.5 | 146.4 ms ± 4.0 | 375,774 | 29.88% |
| node sequential, level 19 (simple fallback) | 243.4 ms ± 3.4 | 257.4 ms ± 3.6 | 374,726 | 29.80% |
| node async parallel, level 19 (rejected) | 980.9 ms ± 38.2 | 987.3 ms ± 24.7 | 374,726 | 29.80% |
| bun parallel, level 19 (reference only; Bun being removed) | 74.1 ms ± 2.8 | 88.3 ms ± 2.2 | 374,726 | 29.80% |
Reading this table:
- The current
--adapttask looks fastest (14 ms / 33 ms) only because--adaptsettled on a low effort level (its output, 404,644 bytes, equals level 3 exactly) and is nondeterministic (the SSD run has stddev 35 ms because--adapttunes its level to observed I/O speed). It is not a fair comparison: it produces 7.4% larger, irreproducible output. - At matched ratio (level 19) the proposed Node worker_threads engine (168 ms / 177 ms) is faster than the zstd CLI at the same level (217 ms / 232 ms), while removing the external tool and producing reproducible output.
- worker_threads (8 workers) beats Node sequential (243 ms / 257 ms) by ~1.5x here and by ~3x on larger file counts (see the Node parallelism section), and beats Node's async parallel path (~1 s) by ~6x.
- Bun's async parallel path (74 ms) is the fastest of all, but Bun is no longer the target; it is listed only to anchor the Node numbers.
Environment #
All measurements were taken on one machine. Numbers are specific to it; see caveats.
| CPU | AMD Ryzen 7 8700F, 8 cores / 16 threads, base/boost to 5.055 GHz max, 0.413 GHz min |
|---|---|
| CPU scaling at capture | governor reported 83% scaling (not pinned to performance) |
| RAM | 62 GiB total, ~41 GiB available, ~43 GiB in buff/cache during runs |
| OS / kernel | Fedora 44, Linux 7.0.9-ogc3.2.fc44.x86_64 |
| tmpfs backend | /tmp, tmpfs (RAM-backed), 32 GiB |
| SSD backend | /var/home, btrfs on LUKS (/dev/mapper/luks-...), 882 GiB, opts rw,relatime,seclabel,ssd,discard=async,space_cache=v2; no compress= mount option, so btrfs transparent compression does not interfere |
| zstd CLI | Zstandard CLI v1.5.7 (Yann Collet), /usr/bin/zstd |
| Bun | 1.3.14 |
| Node | 26.3.0 |
| hyperfine | 1.20.0 |
The SSD path is encrypted (LUKS) and copy-on-write (btrfs).
Writing many small .zst files there
costs real metadata,
CoW,
and encryption work that tmpfs does not incur.
Running on both backends
isolates compute cost (tmpfs) from realistic build cost (SSD,
where the real dist/ lives).
The node:zlib advanced-parameter constants are identical across Bun and Node:
ZSTD_c_compressionLevel = 100,
ZSTD_c_windowLog = 101,
ZSTD_c_enableLongDistanceMatching = 160,
ZSTD_c_nbWorkers = 400,
ZSTD_c_contentSizeFlag = 200,
ZSTD_c_checksumFlag = 201.
Neither
runtime exposes a ZSTD_VERSION constant,
so the libzstd version was characterized empirically by
comparing output bytes (see correctness).
Methodology #
Datasets #
Four datasets, generated deterministically (seeded PRNG) so the tmpfs and SSD copies are byte-identical. Per-file content verified identical across backends by path-sorted SHA-256.
| Dataset | Files | Raw bytes | Purpose |
|---|---|---|---|
real | 138 | 1,257,418 | the actual ssg dist/ text assets (HTML/CSS/JS/SVG/JSON/XML); the workload the decision is about |
many | 2,000 | 5,791,137 | synthetic small HTML files; stresses cross-file parallelism and filesystem metadata (creating many files) |
large | 1 | 33,554,432 | one 32 MiB compressible file (repeated blog text); exposes in-frame multithreading scaling |
incompressible | 1 | 8,388,608 | 8 MiB seeded random bytes; worst-case compress time and the keep-if-smaller guard |
Engines and the threading vocabulary #
"Threading" means different mechanisms for different engines; the benchmark separates them deliberately because they behave very differently.
- zstd CLI,
in-frame multithreading (
-T<n>, with-T0meaning all cores): splits a single file into jobs across worker threads. When compressing a directory recursively, the CLI processes files one at a time, each with in-frame MT. This is exactly what the currentbuild:compressdoes (-T0 -r). For files smaller than zstd's job size it gives no benefit. - zstd CLI,
cross-file process parallelism (
xargs -P<n>): launches onezstdprocess per file, up tonat a time. This is the only way to parallelize the CLI across many files. - node:
zlib sequential (
zstdCompressSyncin a loop): one thread. - node:
zlib async parallel (
Promise.allover asynczstdCompress, bounded concurrencyn): the async calls run on the runtime's internal thread pool, giving cross-file parallelism in-process. This is the path that turns out pathological under Node. - node:
zlib worker_threads (shard files across
nnode:worker_threads, each running synchronouszstdCompressSync): real OS-thread, cross-file parallelism that bypasses the async zlib path entirely. This is the chosen Node engine. It was added to the matrix as a follow-up once the constraint that the build must run under Node made the async path's pathology disqualifying. - node:
zlib in-frame multithreading (
ZSTD_c_nbWorkers): the direct analogue of the CLI's-T<n>, splitting a single file.
Bun does not honor UV_THREADPOOL_SIZE (verified:
4,
8,
16 are indistinguishable);
it uses its own
pool.
Node does honor it,
and the async-parallel Node runs set it to match the concurrency.
The async/sequential candidate is compress-worker.ts (run under both bun and node);
the chosen
Node engine is compress-node-wt.ts (worker_threads).
Both are reproduced below and use only
node: APIs so the bun-vs-node comparison is fair.
Measurement #
- Ratio (compressed size) is storage-independent and deterministic, so it was measured once, in memory, on the tmpfs copy, under both Bun and Node, and cross-checked against the system CLI.
- Time was measured with hyperfine on both backends.
Each hyperfine benchmark clears its output
directory before every run via
--prepare, mirroring the real pipeline (thebuildtask runsbuild:clean=rm -rf distbefore each build, so.zstfiles are always freshly created, never warm overwrites). Run counts: Exp A (level sweep)--warmup 2 --runs 5; Exp B (threading)--warmup 1 --runs 5(3 for the 2000-processmany+ cli-xargs case); Exp C/D--warmup 1 --runs 4; Exp E--warmup 2 --runs 6; Exp F (head-to-head)--warmup 3 --runs 12.
All compression used --no-check / ZSTD_c_checksumFlag = 0 (zstd's default is already no
checksum) and --no-content-size / ZSTD_c_contentSizeFlag = 0 to match the current task's frame
options.
Ultra levels (20 to 22) require --ultra on the CLI;
node:zlib reaches them directly via
the level parameter.
Correctness and engine equivalence #
Before any timing, the engines were checked for byte-level agreement. These are the load-bearing correctness facts for the swap.
- **Bun and Node produce byte-identical output at every level on every dataset. ** All 110+ rows of the ratio sweep matched exactly between the two runtimes.
- node: zlib matches the system zstd CLI v1.5.7 byte-for-byte at every level 1 to 19 on the real dataset (per-file totals: L1 419,904; L3 404,644; L6 387,591; L9 384,350; L12 381,095; L15 375,774; L19 374,726). The Figma round-trip was also exhaustively verified: every one of the 138 files, compressed by the Bun worker and by the CLI, decompresses to the exact original bytes (0 mismatches across all files and both producers).
- At ultra levels the CLI silently caps at 19 without
--ultra(CLI "level 22" returned 374,726, identical to its level 19), whereasnode:zlibapplies the ultra level directly and reaches 374,698. Sonode:zlibis not merely equivalent; it can produce marginally smaller output than a bare CLI invocation.
The decompression direction is symmetric:
a frame produced by the system CLI decodes correctly under
Bun's zstdDecompressSync,
and a frame produced by node:zlib decodes correctly under the CLI.
Ratio results #
real (1,257,418 bytes raw) #
All 138 files compress smaller at every level, so "kept if smaller" equals the compressed total here.
| Level | Compressed bytes | Ratio | Level | Compressed bytes | Ratio |
|---|---|---|---|---|---|
| -7 | 675,774 | 53.74% | 9 | 384,350 | 30.57% |
| -5 | 623,679 | 49.60% | 10 | 383,982 | 30.54% |
| -3 | 564,301 | 44.88% | 11 | 382,235 | 30.40% |
| -1 | 404,644 | 32.18% | 12 | 381,095 | 30.31% |
| 1 | 419,904 | 33.39% | 13 | 379,868 | 30.21% |
| 2 | 415,136 | 33.01% | 14 | 376,666 | 29.96% |
| 3 | 404,644 | 32.18% | 15 | 375,774 | 29.88% |
| 4 | 398,381 | 31.68% | 16 | 375,050 | 29.83% |
| 5 | 391,757 | 31.16% | 17 | 374,927 | 29.82% |
| 6 | 387,591 | 30.82% | 18 | 374,922 | 29.82% |
| 7 | 386,272 | 30.72% | 19 | 374,726 | 29.80% |
| 8 | 385,192 | 30.63% | 20 | 374,712 | 29.80% |
| 21 | 374,712 | 29.80% | |||
| 22 | 374,698 | 29.80% |
The curve drops steeply through level 6,
flattens after level 12,
and is essentially flat from level
16 onward.
Level 15 (375,774) is within 1,048 bytes (0.08 percentage points) of level 19 (374,726).
Negative ("fast") levels trade a lot of ratio for speed and are not useful for precompressed,
served-many-times assets.
Note that the committed dist/.zst baseline of 404,644 bytes equals level
3,
but that figure came from a prior --adapt run and is environment-specific,
not a fixed property
of --adapt.
many (5,791,137 bytes raw, 2,000 files) #
| Level | Compressed bytes | Ratio |
|---|---|---|
| 1 | 1,835,464 | 31.69% |
| 3 | 1,781,447 | 30.76% |
| 6 | 1,767,604 | 30.52% |
| 9 | 1,760,041 | 30.39% |
| 12 | 1,710,352 | 29.53% |
| 15 | 1,697,316 | 29.31% |
| 16 to 22 | 1,689,927 | 29.18% |
Same shape: a knee around level 12 to 16, flat thereafter.
large (33,554,432 bytes raw, 1 file) and long-distance matching #
The large file is repeated blog text, so it is hugely compressible. This dataset is where long-distance matching (LDM) can matter, because LDM needs a large window over a large input.
| Level | No LDM bytes | No LDM ratio | LDM bytes | LDM ratio |
|---|---|---|---|---|
| -5 | 7,547,185 | 22.49% | 276,636 | 0.82% |
| 1 | 5,016,925 | 14.95% | 190,078 | 0.57% |
| 3 | 175,217 | 0.52% | 174,173 | 0.52% |
| 6 | 160,534 | 0.48% | 164,371 | 0.49% |
| 12 | 156,407 | 0.47% | 160,430 | 0.48% |
| 19 | 147,097 | 0.44% | 147,046 | 0.44% |
| 22 | 146,701 | 0.44% | 146,702 | 0.44% |
LDM dramatically helps low levels on a large redundant file (level 1: 14.95% to 0.57%) but is neutral or slightly worse at high levels (whose windows are already large), and it does nothing for small files. Since the ssg assets are small per-file, LDM is irrelevant to the decision; it is measured here only to rule it out.
incompressible (8,388,608 bytes raw, 1 file) #
At every level the compressed output is 8,388,806 bytes,
which is 198 bytes larger than the raw
input (zstd frame overhead on already-random data).
The keep-if-smaller policy therefore keeps the
raw 8,388,608 bytes and writes no .zst.
This is the concrete justification for keep-if-smaller:
without it,
the build would emit .zst companions that are larger than their sources,
which
wireSize would then report as the (inflated) wire size.
Timing results #
Experiment A: level sweep on real, per engine #
Mean wall time in milliseconds,
real dataset,
output cleared before each run.
This experiment
predates the Bun-removal constraint,
so it sweeps bun-par and node-par (async);
the chosen Node
worker_threads engine is benchmarked separately in the Node parallelism section.
cli-rec-T0 is the
current style,
node-par (async) is shown to be pathological,
and node-seq is the Node sequential
baseline that worker_threads improves on.
Bun numbers are reference only.
tmpfs backend:
| Level | cli-rec-T0 | bun-par-c16 | bun-seq | node-par-c16 | node-seq |
|---|---|---|---|---|---|
| 1 | 12.2 | 37.2 | 34.1 | 71.4 | 65.9 |
| 2 | 12.3 | 38.2 | 34.4 | 66.5 | 64.1 |
| 3 | 13.5 | 35.4 | 34.4 | 71.7 | 62.6 |
| 4 | 16.2 | 36.5 | 35.3 | 78.1 | 65.9 |
| 5 | 17.6 | 35.3 | 37.4 | 80.0 | 66.9 |
| 6 | 20.1 | 36.0 | 40.5 | 82.9 | 71.6 |
| 7 | 20.8 | 36.8 | 41.4 | 97.5 | 70.6 |
| 8 | 22.4 | 35.4 | 41.2 | 98.4 | 70.9 |
| 9 | 26.4 | 36.2 | 46.8 | 134.6 | 76.5 |
| 10 | 27.5 | 37.4 | 51.3 | 210.7 | 76.6 |
| 11 | 42.4 | 41.9 | 64.7 | 216.2 | 94.1 |
| 12 | 51.9 | 40.6 | 69.3 | 580.0 | 102.0 |
| 13 | 66.2 | 42.7 | 84.4 | 484.3 | 117.4 |
| 14 | 80.5 | 44.6 | 99.8 | 654.9 | 129.4 |
| 15 | 94.3 | 47.1 | 110.0 | 819.3 | 142.0 |
| 16 | 134.8 | 55.5 | 145.2 | 521.5 | 181.5 |
| 17 | 150.7 | 57.1 | 159.2 | 662.0 | 195.0 |
| 18 | 171.4 | 67.7 | 178.5 | 669.6 | 208.1 |
| 19 | 216.6 | 72.0 | 215.1 | 1007.4 | 256.9 |
| 20 | 223.9 | 72.2 | 221.0 | 1966.3 | 297.7 |
| 21 | 224.0 | 71.5 | 223.8 | 3654.5 | 256.6 |
| 22 | 233.9 | 75.3 | 230.1 | 7837.6 | 266.6 |
SSD backend:
| Level | cli-rec-T0 | bun-par-c16 | bun-seq | node-par-c16 | node-seq |
|---|---|---|---|---|---|
| 1 | 21.0 | 47.6 | 43.1 | 81.9 | 75.3 |
| 3 | 23.1 | 178.1* | 44.1 | 86.7 | 76.3 |
| 6 | 40.2* | 47.7 | 52.1 | 92.7 | 81.4 |
| 9 | 37.6 | 49.4 | 193.4* | 143.7 | 86.8 |
| 12 | 83.8* | 53.5 | 83.3 | 561.7 | 111.3 |
| 15 | 113.1 | 62.8 | 123.0 | 829.4 | 154.8 |
| 16 | 158.5 | 70.3 | 161.7 | 459.1 | 192.5 |
| 19 | 232.1 | 89.8 | 231.1 | 1012.6 | 263.3 |
| 22 | 254.0 | 92.7 | 250.9 | 7543.9 | 279.7 |
Rows marked * had a large standard deviation (a transient outlier run);
see caveats.
The SSD table
is abridged to representative levels;
the full 22-level SSD data was collected and matches the tmpfs
shape offset by roughly 10 to 20 ms of I/O.
What this shows:
- **
bun-paris nearly flat and far cheaper at the levels that matter. ** It has a higher floor (~35 ms, from Bun startup plus thread-pool spin-up) but barely rises with level: level 19 is 72 ms versuscli-rec-T0217 ms andbun-seq215 ms. From level 16 to 22 it is essentially flat (72 to 75 ms). - The CLI is cheapest only at trivial levels (level 1,
12 ms),
where the work is so small that
process startup dominates and parallelism cannot pay for its floor.
The crossover with
bun-paris around level 11 to 12; above it,bun-parwins decisively. node-paris pathological and gets worse with level, exploding to 7.8 seconds at level 22. This is discussed in its own section; it is the reason Node is not used for the parallel path.
Experiment B: threading scaling at level 19 #
Mean ms, level 19, varying the thread/concurrency count. This isolates how each parallelism mechanism scales.
real dataset, tmpfs:
| Threads | bun-par | cli-rec (in-frame) | cli-xargs (cross-file procs) | node-par |
|---|---|---|---|---|
| 1 | 275.0* | 244.1* | 1722.2* | 4684.5 |
| 8 | 58.4 | 216.2 | 1467.9 | 1185.6 |
| 16 | 60.2 | 215.2 | 1470.8* | 1099.2 |
real dataset, SSD:
| Threads | bun-par | cli-rec (in-frame) | cli-xargs (cross-file procs) | node-par |
|---|---|---|---|---|
| 1 | 252.1 | 239.6 | 1657.3 | 4542.1 |
| 8 | 91.1 | 230.4 | 1705.6* | 1030.5 |
| 16 | 86.0 | 248.2* | 2189.7* | 1019.1 |
many dataset (2,000 files), tmpfs:
| Threads | bun-par | cli-xargs (cross-file procs) | node-par |
|---|---|---|---|
| 1 | 823.4 | 22,541 | 59,515 |
| 8 | 180.6 | 23,357 | 14,019 |
| 16 | 154.8 | 23,978 | 13,158 |
many dataset (2,000 files), SSD:
| Threads | bun-par | cli-xargs (cross-file procs) | node-par |
|---|---|---|---|
| 1 | 973.7 | 23,971 | 61,118 |
| 8 | 477.4* | 28,541* | 14,510 |
| 16 | 573.1* | 28,107* | 13,742 |
What this shows:
bun-parscales well across files (real: 275 ms at T1 to ~60 ms at T8/T16, ~4.5x; many: 823 ms to 155 ms, ~5.3x) and is the fastest everywhere it is measured.- The CLI's in-frame
-T<n>does not scale for small files (real: 244 to 215 ms from T1 to T16), confirming that the current task's-T0buys nothing on this workload. - **The CLI's cross-file process parallelism is catastrophic for many files.
** On the 2,000-file set
it takes ~23 to 28 seconds and does not improve with more processes,
because spawning 2,000
zstdprocesses dominates everything. On the 138-filerealset it is ~1.5 to 2.2 seconds, still ~25x slower thanbun-par. Process-per-file is simply the wrong model. node-paris slow and erratic: onmanyit ranges from 13 seconds (T16) to 60 seconds (T1). Notably its slowest point is concurrency 1, which rules out a "too much concurrency" explanation.
Experiment C: in-frame multithreading on the 32 MiB file #
Does the CLI's -T<n> (and node:zlib's nbWorkers) help when the file is actually large?
Mean ms,
single 32 MiB file.
| Config | T1 | T8 | T16 |
|---|---|---|---|
| CLI level 12 (tmpfs) | 62.9 | 51.5 | 50.1 |
| CLI level 19 (tmpfs) | 200.0 | 193.2 | 194.5 |
| node nbWorkers level 12 (tmpfs) | 119.6 | 115.1 | 114.1 |
| node nbWorkers level 19 (tmpfs) | 278.9 | 252.8 | 247.6 |
Even on a 32 MiB file, in-frame MT gives only a mild speedup at level 12 (1.26x for the CLI) and essentially nothing at level 19 (the window already spans most of the file, so there is little to parallelize). This confirms that in-frame MT is not a useful lever for the ssg workload, whose files are three orders of magnitude smaller. SSD numbers match within noise.
Experiment D: long-distance matching wall time (32 MiB file) #
| Config | tmpfs | SSD |
|---|---|---|
| node level 1, no LDM | 114.2 | 114.6 |
| node level 1, LDM | 83.9 | 83.2 |
| node level 19, no LDM | 233.3 | 225.8 |
| node level 19, LDM | 257.7 | 260.2 |
| CLI level 19, no LDM | 197.6 | 196.1 |
| CLI level 19, LDM | 213.1 | 209.0 |
LDM is both faster and far smaller at level 1 on a large redundant file (it finds the long-range repeats cheaply), but it is pure overhead at level 19 (slower, same size). Irrelevant for small ssg assets; measured to rule out.
Experiment E: incompressible worst case and keep-if-smaller cost #
8 MiB random file, level 19.
| Config | tmpfs | SSD |
|---|---|---|
| node parallel, no keep-if-smaller | 930.5 | 907.8 |
| node parallel, keep-if-smaller | 939.9 | 911.9 |
| CLI | 807.8 | 814.9 |
Incompressible data is the slowest per byte (no early exit;
~0.8 to 0.9 s for 8 MiB).
The
keep-if-smaller check costs ~10 ms (under 1%) and,
more importantly,
prevents writing a .zst that
is larger than its source.
In the real build this branch is only reached for the rare text file that
fails to compress;
the common incompressible assets (images,
fonts) are skipped by extension before
any compression is attempted.
Node parallelism: worker_threads is the best optimized implementation #
Because the workspace has migrated off Bun,
the parallel engine must work well under Node,
and Node's
async zstdCompress does not (see the pathology section).
The fast Node path is to shard files
across node:worker_threads,
each worker running synchronous zstdCompressSync.
This avoids Node's
async zlib per-call overhead entirely and uses real OS threads.
The worker_threads compressor was
validated for correctness (138 files,
all decode to the exact originals,
total 374,726 bytes = level
19).
Node engines compared at level 19 (mean ms):
| Engine | real (138 files) tmpfs | real SSD | many (2,000 files) tmpfs |
|---|---|---|---|
sequential zstdCompressSync loop | 243.4 | 257.4 | 787.3 |
| worker_threads, 4 workers | 172.0 | — | 312.3 |
| worker_threads, 8 workers | 166.9 | 171.2 | 252.9 |
| worker_threads, 16 workers | 205.0 | 207.7 | 283.1 |
async zstdCompress + Promise.all (16) | 980.9 | 987.3 | (pathological) |
worker_threads with 8 workers is ~1.5x faster than sequential on the 138-file real set and ~3.1x faster on the 2,000-file set, which matters as the blog grows.
A full worker-count sweep (1 to 32 workers) on the real set at level 19 shows the optimum is a plateau, not a single point: workers 4, 8, and 10 are statistically tied, and performance degrades steadily above ~12 as extra V8 isolates cost more than they return (zstd is CPU-bound, so SMT past the 8 physical cores gives little).
| Workers | 1 | 2 | 3 | 4 | 6 | 8 | 10 | 12 | 16 | 24 | 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| tmpfs ms | 281 | 365* | 197 | 170 | 185 | 169 | 168 | 187 | 210 | 261 | 309 |
| SSD ms | 298 | 227 | 204 | 178 | 196 | 177 | 176 | 196 | 217 | 277 | 311 |
(* the W2 tmpfs cell had an outlier run,
stddev +/- 406 ms;
treat it as noise.
) The practical rule is
workers in the 4 to 10 range,
around the physical-core count (8 here);
never oversubscribe past
~12.
A naive os.availableParallelism() returns 16 on this chip,
which is already ~25% past the
optimum,
so the implementation should cap at roughly the physical-core count rather than use the
logical count directly.
There is also a fixed worker-spawn floor of roughly 120 ms (V8 isolate
startup),
which is why worker_threads helps at high levels and on large file counts but not at
trivial levels,
where sequential or the CLI's lower startup wins.
The SSD many numbers are omitted from the table because parallel writers contending on btrfs
copy-on-write plus LUKS encryption produced very high variance there (stddev up to +/- 458 ms across
worker counts);
the tmpfs many numbers isolate the compute scaling cleanly.
worker_threads level curve (real, tmpfs, 8 workers): level 12 = 130.4 ms, level 15 = 136.5 ms, level 19 = 169.1 ms, level 22 = 177.2 ms. Flatter than the sequential curve (the per-file work overlaps across workers), and level 15 saves ~33 ms over level 19 for 0.08 ratio points.
The Node async parallel pathology (observation, mechanism not isolated) #
Node's async zstdCompress driven by Promise.all is anomalously slow in this benchmark,
and the
cause was not isolated.
Reporting the observation,
not a mechanism:
- At level 19 on the 138-file
realset it takes ~1.0 second, versus Bun's 72 ms (about 14x slower) and Node's own sequentialzstdCompressSyncat 257 ms (so parallel is ~4x slower than sequential on the same runtime). - It worsens sharply with level:
tmpfs
realgoes 580 ms (L12), 1007 ms (L19), 1966 ms (L20), 3654 ms (L21), 7838 ms (L22). The sequential path on Node does not do this (267 ms at L22). - In the threading scan its slowest point is concurrency 1 (4.7 s), with more concurrency making it faster, which contradicts an "oversubscription / too many large contexts" explanation.
A plausible-sounding memory-pressure story was considered and rejected because the concurrency-1 data contradicts it. The honest characterization is that Node's async zstd dispatch carries a large per-call overhead here that compounds at high levels, but the benchmark did not instrument the runtime to prove the mechanism. It does not affect the decision: the build runs under Node, where the synchronous worker path avoids the async overhead measured here. It is documented so a future reader does not "optimize" the build by switching it to Node async parallel.
Caveats and threats to validity #
- **Single machine, single run of the suite. ** All numbers are from one AMD Ryzen 7 8700F. Absolute times will differ elsewhere; the relative conclusions (Bun parallel beats the CLI at high levels; CLI cross-file and Node parallel are catastrophic; in-frame MT is useless for small files) are large enough to travel.
- **CPU governor was not pinned.
** It reported 83% scaling,
not locked to performance.
Combined with
background activity,
this produced occasional outlier runs (rows marked
*above, e.g.bun-parL3 on SSD at 178 ms +/- 290, and the current-task SSD head-to-head at 88 ms +/- 121). For those rows, prefer the minimum or median over the mean. The headlinebun-parnumbers are tight (stddev ~1 to 2 ms) and trustworthy; only flagged rows are noisy. - **
--adaptis nondeterministic. ** It tunes its compression level to observed I/O throughput, so the current task produces different output sizes and different wall times on different disks (13 ms / level-3-equivalent on tmpfs versus 88 ms +/- 121 on SSD here). This means the current build's output is not reproducible across environments. A fixed level is, which is an independent argument for the change beyond ratio and speed. - **Page cache.
** Inputs were warm in cache (realistic:
dist/was just written by earlier build phases). The SSD cost captured is dominated by writing and creating.zstfiles (CoW + LUKS + metadata), not cold input reads. This matches the real pipeline, where compression immediately follows generation. - Worker startup is included in every node timing (Bun/Node process launch,
~10 to 80 ms).
This
is correct for the build (the task spawns one process) and is the main reason
bun-parhas a ~35 ms floor; it does not affect the per-level deltas, which are dominated by compression work. - **tmpfs is RAM. ** The tmpfs numbers isolate compute and are not representative of the real build's I/O; the SSD numbers are. Both are reported so the compute-versus-I/O split is visible.
Which precompressed extensions still benefit from zstd #
The compressor skips a blocklist of already-compressed extensions without reading them.
The blocklist
is purely an optimization:
keep-if-smaller (write .zst only when strictly smaller) is the real
safety net,
so the only cost of a wrong "skip" is a missed saving,
and the only cost of a wrong
"compress" is wasted CPU.
The question is therefore empirical:
which "already compressed" formats does
a level-19 zstd pass still shrink on real content?
Methodology #
Representative real content,
not synthetic tones (a pure sine compresses pathologically and would
mislead).
Three frames,
a 20-second audio clip at three timestamps,
and a 6-second video clip were
taken from a 1920x816 AV1 cartoon (ffmpeg),
plus this site's own dist/ assets.
Each frame was
re-encoded to every image format (cwebp,
magick,
ffmpeg with libjxl / libaom-av1);
the audio
clips to every audio codec;
the video clip to h264 / vp9.
Every output was compressed with the exact
production settings (level 19,
content-size off,
checksum off) and compared to its source size.
Audio
codecs were measured across three independent clips;
the spread was within 0.3 points.
Results #
| Extension | Sample | zstd-19 savings | Decision |
|---|---|---|---|
| aac | cartoon audio, n=3 | +6.0 to 6.3% | remove (compress) |
| m4a | cartoon audio, n=3 | +5.8 to 6.0% | remove (compress) |
| ogg (vorbis) | cartoon audio, n=3 | +3.6 to 3.9% | remove (compress) |
| png | site icons + frames | +0 to 15% (icons compress, photos do not) | remove (compress) |
| jpg / jpeg | site + frames, n=7 | +1.0 to 1.3% (every file) | remove (compress) |
| mp3 | cartoon audio, n=3 | +0.7% | keep (skip) |
| flac | cartoon audio, n=3 | +0.3% | keep (skip) |
| avif | site + frames | ~0% (only sub-kB files compressed) | keep (skip) |
| webp (lossy + lossless) | frames, n=6 | ~0% | keep (skip) |
| gif | frames, n=3 | ~0% | keep (skip) |
| jxl (lossy + lossless) | frames, n=6 | ~0% | keep (skip) |
| woff2 | site fonts, n=8 | +0.1% | keep (skip) |
| mp4 / mov (h264) | cartoon video | +0.3% | keep (skip) |
| webm (vp9) | cartoon video | +0.1% | keep (skip) |
woff,
gz,
and br were not sampled (no source on hand) and are kept on first principles:
WOFF
stores deflate-compressed font tables (like woff2's brotli),
and gzip / brotli are compression formats
by definition.
zst is always skipped so a .zst is never recompressed.
Removing png / jpg / jpeg / ogg / aac / m4a from the blocklist raised this site's compressed count
from 176 to 185 files and total savings from 1.18 MB to 1.28 MB,
with every produced .zst still
round-tripping to its source.
Proposed implementation #
Not yet applied. Sketch for when it is.
Figma decompression #
In package/figma/kiwi/src/index.ts,
decompressZstd collapses to:
async function decompressZstd(data: Uint8Array,): Promise<Uint8Array> {
const { zstdDecompressSync, } = await import('node:zlib');
return new Uint8Array(
zstdDecompressSync(Buffer.from(data,),),
);
}
It stays async to preserve the public call contract,
mirroring the inflateRawSync schema decode
already in the same function.
Remove nano-spawn from package/figma/kiwi/package.json
(its only use was the removed fallback).
Verify with the package's existing integration test,
which
decodes real .fig / .deck / .jam files (bun package/figma/kiwi/src/index.unit.test.ts).
ssg compression #
Add package/ssg/aquati.cat/src/build/compress.ts beside postprocess.ts,
and change the
build:compress task from the zstd shell command to node src/build/compress.ts (Node,
since Bun
is being removed).
The script:
on the main thread,
walk dist/,
skip known-incompressible extensions
without reading them,
shard the remaining files across node:worker_threads (worker count = physical
cores,
roughly 8;
cap below the logical count),
and in each worker compress with synchronous
zstdCompressSync at level 19 (ZSTD_c_contentSizeFlag = 0),
writing <file>.zst only when strictly
smaller than the source.
The core engine is exactly the compress-node-wt.ts used in this benchmark
(reproduced below),
adapted into the package's logging and module conventions.
If the worker_threads
machinery is judged not worth its complexity for the current dist/ size,
the sequential
zstdCompressSync fallback is a one-file change away and costs ~75 ms more on today's dist/ (but
~3x more as the file count grows).
Tool and config cleanup #
Remove "github:facebook/zstd" = "latest" from mise.toml and mise.no-env.toml.
Reproduction #
The benchmark scripts were scratch artifacts under /tmp/agent/zbench/ (ephemeral,
RAM-backed) and
a throwaway SSD data dir under /var/home/user/.cache/agent-zstd-bench/.
The two load-bearing units
are reproduced here in full so the measurement can be rebuilt.
compress-node-wt.ts,
the chosen Node engine (worker_threads + synchronous zstd;
run under node):
import { Worker, isMainThread, workerData, parentPort, } from 'node:worker_threads';
import { readdirSync, readFileSync, writeFileSync, mkdirSync, statSync, } from 'node:fs';
import { dirname, join, } from 'node:path';
import zlib from 'node:zlib';
const c = zlib.constants;
function compressOne(path, IN, OUT, params, keep) {
const raw = readFileSync(path,);
const dest = join(OUT, path.slice(IN.length,),);
mkdirSync(dirname(dest,), { recursive: true, },);
const out = zlib.zstdCompressSync(raw, { params, },);
if (keep && out.length >= raw.length) { writeFileSync(dest, raw,); return; }
writeFileSync(`${dest}.zst`, out,);
}
if (isMainThread) {
const arg = (name, fb) => {
const i = process.argv.indexOf(`--${name}`,);
if (i < 0) return fb;
const n = process.argv[i + 1];
return (n === undefined || n.startsWith('--',)) ? 'true' : n;
};
const IN = arg('in',), OUT = arg('out',), LEVEL = Number(arg('level', '19',),);
const WORKERS = Number(arg('workers', '8',),), KEEP = arg('keep-if-smaller',) === 'true';
const files = readdirSync(IN, { recursive: true, },)
.map(rel => join(IN, String(rel,),),).filter(p => statSync(p,).isFile());
const nWorkers = Math.min(WORKERS, files.length,) || 1;
const shards = Array.from({ length: nWorkers, }, () => [],);
files.forEach((f, i) => shards[i % nWorkers].push(f,),);
await Promise.all(shards.map(shard => new Promise((resolve, reject,) => {
const w = new Worker(new URL(import.meta.url,), { workerData: { shard, IN, OUT, LEVEL, KEEP, }, },);
w.on('error', reject,);
w.on('exit', code => code === 0 ? resolve() : reject(new Error(`worker exit ${code}`,),),);
},),),);
}
else {
const { shard, IN, OUT, LEVEL, KEEP, } = workerData;
const params = { [c.ZSTD_c_compressionLevel]: LEVEL, [c.ZSTD_c_contentSizeFlag]: 0, };
for (const path of shard) compressOne(path, IN, OUT, params, KEEP,);
parentPort.postMessage('done',);
}
compress-worker.ts,
the cross-runtime sequential/async unit used to measure the sequential and
(rejected) async paths under both bun and node:
import { readdirSync, readFileSync, writeFileSync, mkdirSync, statSync, } from 'node:fs';
import { dirname, join, } from 'node:path';
import zlib from 'node:zlib';
import { promisify, } from 'node:util';
const zstdCompress = promisify(zlib.zstdCompress,);
const c = zlib.constants;
function arg(name, fallback) {
const i = process.argv.indexOf(`--${name}`,);
if (i < 0) return fallback;
const next = process.argv[i + 1];
if (next === undefined || next.startsWith('--',)) return 'true';
return next;
}
const IN = arg('in',);
const OUT = arg('out',);
const LEVEL = Number(arg('level', '19',),);
const MODE = arg('mode', 'par',);
const CONCURRENCY = Number(arg('concurrency', '16',),);
const LONG = arg('long',) === 'true';
const NBWORKERS = Number(arg('nbworkers', '0',),);
const KEEP_IF_SMALLER = arg('keep-if-smaller',) === 'true';
const params = { [c.ZSTD_c_compressionLevel]: LEVEL, [c.ZSTD_c_contentSizeFlag]: 0, };
if (LONG) { params[c.ZSTD_c_enableLongDistanceMatching] = 1; params[c.ZSTD_c_windowLog] = 27; }
if (NBWORKERS > 0) params[c.ZSTD_c_nbWorkers] = NBWORKERS;
const files = readdirSync(IN, { recursive: true, },)
.map(rel => join(IN, String(rel,),),)
.filter(p => statSync(p,).isFile());
async function one(path) {
const raw = readFileSync(path,);
const dest = join(OUT, path.slice(IN.length,),);
mkdirSync(dirname(dest,), { recursive: true, },);
const out = MODE === 'seq'
? zlib.zstdCompressSync(raw, { params, },)
: await zstdCompress(raw, { params, },);
if (KEEP_IF_SMALLER && out.length >= raw.length) { writeFileSync(dest, raw,); return raw.length; }
writeFileSync(`${dest}.zst`, out,); return out.length;
}
if (MODE === 'seq') { for (const f of files) await one(f,); }
else {
let cursor = 0;
const worker = async () => { while (cursor < files.length) { await one(files[cursor++]!,); } };
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, files.length,), }, worker,),);
}
The full suite consisted of:
prep.ts (deterministic dataset generation on both backends),
ratio.ts (in-memory level sweep under bun and node,
plus a CLI cross-check),
and time-matrix.ts
(the hyperfine orchestrator implementing experiments A through F over both backends,
clearing the
output dir before each run).
Re-running requires only hyperfine,
zstd,
bun,
and node at the
versions in the environment table;
the datasets rebuild deterministically from the ssg dist/.
To reproduce the headline comparison directly:
# build dist first (mise run //package/ssg/aquati.cat:build:site), then:
hyperfine --warmup 3 --runs 12 --prepare 'rm -rf /tmp/out && mkdir -p /tmp/out' \
--command-name current 'cd dist && zstd -q -z -f --no-check --no-content-size -T0 --adapt -r . --output-dir-mirror /tmp/out' \
--command-name 'cli-matched-L19' 'cd dist && zstd -q -19 --ultra --no-check --no-content-size -T0 -r . --output-dir-mirror /tmp/out -f' \
--command-name 'proposed-node-wt-L19' 'node compress-node-wt.ts --in dist --out /tmp/out --level 19 --workers 8 --keep-if-smaller'