Implementing Response Compression
1. Using gzip Compression
| Property | Value |
|---|---|
| Algorithm | DEFLATE (LZ77 + Huffman) |
| Browser support | Universal |
| Compression ratio (JSON) | 60-80% |
| CPU cost | Low-moderate |
| Header | Content-Encoding: gzip |
2. Using Brotli Compression
| Property | Value |
|---|---|
| Compression ratio | 15-25% better than gzip |
| Decompression speed | Comparable to gzip |
| Compression speed (high level) | Slower than gzip |
| Browser support | All modern (HTTPS only) |
| Header | Content-Encoding: br |
3. Using deflate Compression
| Note | Detail |
|---|---|
| Status | Legacy; rarely used |
| Compatibility issues | Implementations differ (raw deflate vs zlib wrap) |
| Recommendation | Skip; offer gzip + br |
4. Configuring Compression Thresholds
| Setting | Typical |
|---|---|
| Min size to compress | 1 KB (smaller = overhead exceeds gain) |
| Skip already-compressed | image/*, video/*, application/zip |
| Compress JSON / HTML / CSS / JS | Always |
5. Setting Content-Encoding Header
| Header | Use |
|---|---|
Content-Encoding: gzip | Response gzipped |
Content-Encoding: br | Response Brotli |
Vary: Accept-Encoding | Required for caches |
6. Handling Compressed Request Bodies
| Pattern | Notes |
|---|---|
Client sends Content-Encoding: gzip | Server must decompress |
| Less common than response compression | Useful for large uploads (logs, telemetry) |
| Reject unsupported encoding | 415 Unsupported Media Type |
7. Implementing Conditional Compression
| Condition | Action |
|---|---|
| Client supports br | Use Brotli (best ratio) |
| Client supports gzip only | Use gzip |
| Neither | Send uncompressed |
| Already compressed type | Skip compression |
8. Optimizing Compression Levels
| Algorithm | Levels | Recommendation |
|---|---|---|
| gzip | 1 (fast) – 9 (max) | Level 6 (balanced) |
| Brotli | 0 – 11 | 4-6 dynamic, 11 static |
| Pre-compress static | Generate .gz / .br | Serve directly |
9. Measuring Compression Performance
| Metric | Track |
|---|---|
| Compression ratio | Bytes out / bytes in |
| CPU time | ms per request added |
| Bandwidth saved | Total bytes saved per day |
| Time-to-first-byte | May increase slightly with compression |
10. Handling Compression Errors
| Error | Mitigation |
|---|---|
| Out-of-memory on huge response | Stream compression, chunk transfer |
| Client decompression failure | Fallback to identity |
| BREACH attack on HTTPS+gzip | Avoid reflecting user input in compressed responses with secrets |