Gzip compression

Also known as: gzip

On this page 8

Gzip compression is the lossless compression of HTTP responses by a web server, using the gzip format built on the DEFLATE algorithm, so that HTML, CSS, JavaScript, JSON and other text travel to the client in far fewer bytes. In server performance work, it is one of the cheapest optimizations available: a browser announces support with the Accept-Encoding request header, and the server answers with a compressed body and Content-Encoding: gzip.

Text resources typically shrink by 60 to 80 percent, which shortens transfer time, reduces bandwidth bills and improves perceived speed on slow or mobile connections. The trade-off is extra CPU time on the server for compression and a much smaller cost on the client for decompression.

How gzip compression works in HTTP

Gzip is a file format defined in RFC 1952 that wraps a DEFLATE stream (RFC 1951) with a header and a CRC-32 checksum. DEFLATE combines two techniques: LZ77 matching, which replaces repeated byte sequences with back-references to earlier occurrences within a 32 KB sliding window, and Huffman coding, which assigns shorter bit codes to frequent symbols.

Text formats compress well because they are highly repetitive: HTML repeats tag names and attributes, CSS repeats property names, and minified JavaScript still repeats identifiers and keywords. In HTTP, the exchange is driven by content negotiation. The client sends Accept-Encoding: gzip, deflate, br, the server picks a supported encoding, compresses the body and adds Content-Encoding: gzip plus Vary: Accept-Encoding so that caches store separate variants.

The following table shows typical size reductions for common response types.

Content typeTypical reductionWorth compressing
HTML documents70 to 85 percentYes
CSS stylesheets75 to 85 percentYes
JavaScript bundles65 to 80 percentYes
JSON API responses70 to 90 percentYes
SVG images50 to 80 percentYes
JPEG, PNG, WebP, MP40 to 2 percentNo, already compressed
Typical gzip savings by content type

Compression levels and CPU cost

Gzip offers compression levels from 1 to 9. Higher levels search harder for matches and produce slightly smaller output, but CPU time rises much faster than the savings. The gains beyond level 5 or 6 are usually marginal, often only a few percent, while compression time can double or triple.

For this reason, most production configurations use a middle level for dynamic responses and reserve the highest level for files compressed once, ahead of time. The table summarizes the trade-off in relative terms, since exact figures depend on content and hardware.

LevelRelative output sizeRelative CPU costTypical use
1LargestLowestVery high request volume, weak CPU
4 to 6Close to optimalModerateDefault for dynamic responses
9Smallest gzip outputHighestPrecompressed static assets
Gzip level trade-offs

Tools such as Zopfli produce gzip-compatible output a few percent smaller than level 9 at a far higher CPU cost, which only makes sense for static files compressed during the build.

Gzip compared with Brotli and other encodings

Gzip is the most widely supported HTTP content encoding, but it is no longer the most efficient. Brotli, standardized in RFC 7932, uses a larger window and a built-in dictionary of common web strings, and typically produces files 15 to 25 percent smaller than gzip for text. Zstandard is a newer option with very fast compression that browsers have begun to support.

EncodingCompression ratioSpeedClient support
GzipGoodFast at moderate levelsUniversal, including old clients
BrotliBetter for textSlow at high levelsAll modern browsers over HTTPS
ZstandardSimilar to Brotli at speedVery fastRecent browsers, growing
Deflate (raw)Similar to gzipFastInconsistent implementations
IdentityNoneNo costUniversal fallback
Gzip compared with alternative content encodings

A common strategy is to serve Brotli when the client supports it and fall back to gzip for everything else. Because gzip support is practically universal, it remains the essential baseline encoding even on servers that prefer newer formats.

Configuring gzip on servers

Gzip is enabled in the web server, the reverse proxy or the CDN, rarely in application code. In nginx, the gzip on; directive with gzip_types and gzip_comp_level controls it; in Apache HTTP Server, the mod_deflate module does the same; most CDNs compress automatically at the edge.

Three settings deserve attention. A minimum length threshold, often around 1 KB, avoids compressing tiny responses where headers dominate. A MIME type allowlist limits compression to text formats. Static precompression, such as nginx gzip_static, serves ready-made .gz files and removes per-request CPU cost entirely.

The decision table lists common situations and recommended configurations.

SituationRecommended settingReason
Static CSS and JavaScriptPrecompress at level 9Compressed once, served many times
Dynamic HTML from PHPLevel 4 to 6 on the flyBalances latency and size
CPU-saturated serverLower level or offload to CDNFrees cycles for request handling
Responses under 1 KBSkip compressionOverhead exceeds savings
Images and videoExclude by MIME typeAlready compressed formats
Choosing a gzip strategy

Interaction with caching and performance metrics

Gzip works best when combined with caching. A full-page cache or Varnish can store the compressed variant, so the server compresses a page once instead of on every request. The Vary: Accept-Encoding header is essential here; without it, a cache may serve compressed bytes to a client that cannot decode them.

In metrics, gzip mainly lowers transfer time and bandwidth, which improves response time as seen by users and time to first byte for large documents on slow links. On a busy server it can slightly reduce requests per second because each response costs more CPU, so it should be measured under realistic load rather than assumed to be free.

Limitations, risks and common mistakes

Gzip is mature and safe, but misconfiguration is common. The most frequent problems are listed below.

  • Compressing already compressed files, which wastes CPU and can even enlarge the output slightly.
  • Double compression, when both the application and the proxy compress, producing unreadable responses.
  • Missing Vary header, which leads shared caches to serve the wrong variant.
  • Maximum levels on dynamic content, which raise latency for little size gain.
  • Ignoring compression side channels such as the BREACH attack, where secrets reflected in compressed HTTPS responses can leak through response sizes.

BREACH mitigation does not require disabling gzip globally; separating secrets from user-controlled input and masking CSRF tokens per request are the usual defenses.

A non-technical view

Gzip compression is like vacuum-packing clothes before shipping them. The server squeezes a web page into a smaller package, sends it across the internet faster, and the browser unpacks it into exactly the same page.

Web pages contain many repeated words and patterns, so they shrink a great deal, often to a quarter of their original size. Photos and videos are already packed tightly, so squeezing them again achieves almost nothing. The only cost is a little extra work for the server, which is usually a good bargain.

A concrete example

An online store runs on a single virtual server behind nginx. Its product pages produce about 180 KB of HTML, and the theme loads 420 KB of CSS and JavaScript. Many customers browse on mobile networks, and the hosting plan charges for outbound traffic.

The administrator enables gzip at level 5 for dynamic HTML and JSON and precompresses static assets at level 9 during deployment. Product pages now transfer at roughly 35 KB, and the static bundle drops to about 110 KB. Monthly outbound traffic falls by more than half, and mobile load times improve noticeably, while CPU usage rises by only a few percentage points because the full-page cache stores the compressed variants.