# ADR-0053: Response compression (gzip and brotli)

URL: https://scalws.com/docs/adr/0053-response-compression/
Source: `docs/adr/0053-response-compression.md` in the ScalWS repository

Status: accepted, 2026-11-17

## Context

Until 1.1 ScalWS compressed nothing: it only served `.br` and `.gz` files that already lay
next to a static file (`precompressed`). ScalPanel's PHP contract test failed on that
(owner's notes item 2): text files went out uncompressed, so ScalPanel websites on ScalWS
sent several times the bytes of the same website on nginx. The notes ask for gzip
(mandatory) and brotli, `Accept-Encoding` and `Vary: Accept-Encoding` honoured, small files,
already-compressed types and responses with their own `Content-Encoding` skipped, no
compression of Range requests (or correct ETags), precompressed files, and four modes:
`static` (the default), `all`, `types`, `off`.

Compressing dynamic responses is not free of risk. BREACH (and CRIME before it) recovers a
secret from a page that reflects attacker-chosen input next to that secret, by watching the
compressed length over many requests. Static files reflect nothing, so compressing them is
safe; a PHP page may.

## Decision

* **Configuration.** `applications[].compression: {mode, types}`, with `mode` one of:
  * `off` (YAML default, so an upgrade changes nothing): nothing; `.br`/`.gz` siblings only
    as `precompressed` says.
  * `static` (site.json default): only files the static handler serves (also the static
    files of a PHP application), of a fixed list of text-like types (`text/html`,
    `text/css`, `text/plain`, `text/xml`, `text/csv`, `text/markdown`, `text/javascript`,
    `application/javascript`, `application/json`, `application/ld+json`,
    `application/manifest+json`, `application/xml`, `application/xhtml+xml`,
    `application/rss+xml`, `application/atom+xml`, `image/svg+xml`, `image/x-icon`,
    `image/bmp`, `font/ttf`, `font/otf`, `application/vnd.ms-fontobject`,
    `application/wasm`). A response of PHP, a proxy or any other dynamic handler is never
    compressed, whatever its `Content-Type`: the decision is by the handler kind, so a PHP
    page sending `text/css` or a `.html` run through `AddHandler` stays identity. This is
    the BREACH-safe default.
  * `all`: every eligible response, dynamic ones included.
  * `types`: static and dynamic responses whose type is in `types` (`type/subtype`, lower
    case, no parameters, 1 to 64 entries).

  `server.compression.cache_bytes` (default 32 MiB, ScalPanel mode 8 MiB, `0` compresses
  every time) is the memory for compressed variants of static files, shared by all
  applications. A change of an application's `compression` restarts its PHP runtime on
  reload (the static half of a PHP application is built with it).
* **Eligibility** (every rule must hold): `GET` or `HEAD` without `Range` (Range requests
  get identity with `Accept-Ranges: bytes` as before); static `200`, dynamic any status but
  1xx, 204, 205, 206 and 304; no `Content-Encoding`, `Content-Range` or
  `Cache-Control: no-transform` in the response, not an upgrade; a known length of at least
  1024 bytes (a dynamic body of unknown length is peeked at first); a type outside the
  never-compressed list (`image/*` but SVG, ICO and BMP, `video/*`, `audio/*`, WOFF and
  WOFF2, archives, `application/pdf`, `application/octet-stream`, office documents,
  `text/event-stream`, `application/grpc*`; also in `all`); the client accepts `br` or
  `gzip`/`x-gzip` with q > 0 (RFC 9110 12.5.3; equal weights prefer `br`; an invalid
  q-value refuses the coding; nothing acceptable: identity). HTTP/1.0 requests get a
  compressed body only when its length is known (a cached variant or a precompressed file),
  since streaming needs chunked encoding.
* **Headers.** `Content-Encoding: br|gzip`. `Vary: Accept-Encoding` is merged into an
  existing `Vary` (never twice, never next to `Vary: *`) on every response of a type the
  mode compresses, also when it goes out uncompressed, so a cache in front never mixes
  variants. A streamed body has no `Content-Length` and no `Accept-Ranges`. A cached static
  variant gets a strong ETag, the identity tag plus a suffix naming coding and level
  (`-gz6`, `-br5`), so a level change never reuses a tag; a streamed static variant gets a
  weak one (`W/"...-gz1"`); a dynamic response's ETag is weakened (`W/`), as nginx does.
  `If-None-Match` matches the variant's tag or the identity tag; the 304 carries the
  variant's `ETag` and `Vary`.
* **Where.** Static files in `scalws-static` (it knows type, size, identity, Range and
  ETag): precompressed sibling (not older than the file, same access rules) > cached
  variant > compress now. A compressed body is always built from the file's bytes, never
  from the sendfile placeholders of ADR-0027; identity responses keep sendfile. Dynamic
  responses in `scalws-server`'s `finish`, after the handler, the `.htaccess` headers and
  the response cache (the cache stores identity), as a body adapter that compresses each
  frame as it arrives and flushes only when the inner body has nothing ready, so PHP's
  streamed output still reaches the client promptly; trailers pass through.
* **Variant cache.** LRU by bytes, keyed by file identity (device, inode, size,
  modification and change time), the document root and the coding (audit scalpanel N7: a
  reused inode number never meets another file's variant), files of at most 1 MiB, a variant kept only when it is
  under 95 % of the file (otherwise the "not worth it" answer is cached). A miss compresses
  at the cached levels, inline up to 64 KiB (gzip) or 32 KiB (brotli) and on the blocking
  pool above, behind `max(1, cpus / 4)` permits; with no permit free the request streams at
  the fast levels instead of waiting. A failed compression is never stored.
* **Levels.** Cached variants: gzip 6, brotli 5 (window 2^22). Streaming (dynamic bodies,
  files over 1 MiB, no free permit): gzip 1, brotli 3 (window 2^20). Not configurable in
  1.1. Streaming encoders share a memory budget of 16 MiB per CPU (at least 64 MiB); a
  request that finds it spent is sent uncompressed.
* **Crates.** `flate2` 1.1.10 with the `zlib-rs` backend (pure Rust, at zlib-ng speed,
  faster than the default `miniz_oxide`) and `brotli` 9.1.1 (pure Rust port of Google's
  encoder; encoder only), pinned exactly, licences MIT/Apache-2.0, Zlib and BSD-3-Clause/MIT.
  Pure Rust keeps the static musl builds (amd64 and aarch64) free of C builds. Rejected:
  `async-compression` (one more layer; ScalWS needs its own `http_body::Body` adapter
  anyway), `libz-ng-sys`/`libz-sys` (C and cmake for two musl targets). Both encoders sit
  behind the default-on Cargo feature `compression` of `scalws-core`, `scalws-static` and
  `scalws-server`; without it the policy is compiled out.
* **No decompression.** ScalWS never decompresses anything a client or an upstream sends.

## Consequences

* With `mode: off` nothing changes: one `Option` test when the application is routed and
  one in `finish`, `Accept-Encoding` is not parsed, and `pipeline_cost` counts the same
  allocations per request. Measured on xeon (`docs/benchmarks/2026-11-15-compression.md`):
  `off` against the build before compression within 2 % at 1 and 6 CPUs (1.001, 0.996 and
  0.985 at 1 CPU on the re-run; 0.991 to 1.001 at 6 CPUs).
* `static` against nginx 1.31.6 (`gzip on; gzip_comp_level 1; gzip_static on;`): 3.7x to
  38x nginx's requests per second at 1 CPU (100 KiB CSS 10.2x, 20 KiB HTML 3.9x, 300 KiB JS
  37.7x with gzip) and 3.9x to 39x at 6 CPUs, with fewer bytes (CSS 16.7 KB gzip and
  17.0 KB brotli against nginx's 21.7 KB). The difference is the method: ScalWS compresses a
  file once and serves the variant from memory, nginx compresses every response.
* `all` with a 50 KiB PHP page against nginx `gzip on` over FastCGI: 1.55x at 1 CPU and
  1.76x at 6 CPUs, but 23.1 KB per response against nginx's 17.3 KB (zlib-rs's level 1 is
  zlib-ng's fast strategy). Streaming gzip level 2 would send 16.6 KB at 1.14x nginx; level 1
  stays.
* A stream of cache misses on one CPU (every request compressing a 60 KiB file) raises the
  p99 of other requests on that CPU by 1.8x (gzip) to 2.3x (brotli). In normal operation a
  file is compressed once per coding while it stays cached; a site whose compressible
  working set does not fit `cache_bytes` pays this repeatedly. A fill rate limit is a 1.2
  candidate.
* `all` and `types` are opt-ins with a BREACH warning in the guide; `static` cannot leak a
  secret through length because it compresses no dynamic response.
* No `mod_deflate` directives: `.htaccess` `AddOutputFilterByType DEFLATE` lines (common in
  WordPress files) are ignored without a warning; compression is chosen by the configuration
  (site.json `compression` in ScalPanel mode).
* No zstd in 1.1 (browsers support it; the same stage can add it later), no configurable
  levels, no compression of request bodies.
* HTTP/1.0 clients get identity for dynamic and large uncached responses.

## References

* `crates/scalws-core/src/encoding.rs` (negotiation, types, encoders),
  `crates/scalws-static/src/compress.rs`, `compressed_cache.rs`,
  `crates/scalws-server/src/compress_body.rs`.
* Tests: `tests/integration/tests/scalpanel.rs` (`static_mode_never_compresses_dynamic`,
  `all_mode_compresses_php`, `types_mode_follows_the_list`, `streaming_flushes_promptly`,
  `reload_changes_compression`), the `accept_encoding` fuzz target.
* [ScalPanel mode](https://scalws.com/docs/guide/scalpanel/#compression), [configuration](https://scalws.com/docs/guide/configuration/#compression).
