The Trade-offs of Compression
Compression trades CPU time for network time.Break-even Point
Finding the Optimal Threshold
Threshold is the minimum size to compress.Effects by Threshold
| Size | Threshold: 256 | Threshold: 1024 | Threshold: 4096 |
|---|---|---|---|
| 100B | No compression (overhead) | No compression | No compression |
| 500B | Compress (small effect) | No compression | No compression |
| 2KB | Compress | Compress | No compression |
| 10KB | Compress | Compress | Compress |
Recommended Thresholds
- Aggressive (256B)
- Default (1KB)
- Conservative (4KB)
- Mobile networks (slow speeds)
- Expensive bandwidth costs
- Most responses are small (< 10KB)
Finding Optimal Value Through Experimentation
Algorithm Selection Strategy
Brotli vs Gzip
| Criteria | Brotli (br) | Gzip |
|---|---|---|
| Compression ratio | Best (15-20% better) | Medium |
| Compression speed | Slow (higher CPU usage) | Fast |
| Decompression speed | Fast | Fast |
| Browser support | Modern browsers | All browsers |
Usage Strategies
- Static Content
- Dynamic API
- Hybrid
Pre-compression -> Use BrotliAdvantages:
- No compression time concerns (pre-compressed)
- Best compression ratio (quality 11)
- No runtime CPU load
Environment-Based Strategy
Combining Caching and Compression
Using compression with caching achieves the best performance.Effect
Per-layer optimization:- Browser cache: 0ms (fastest)
- CDN cache: 10ms (network only)
- Server cache: 50ms (compression only, no DB)
- DB query: 500ms (compression + DB)
CDN and Compression
CloudFront Optimization
- Receive compressed response from origin
- CloudFront caches as-is
- Serve quickly from edge
Vary Header Consideration
When using compression, responses differ based onAccept-Encoding:
Pre-compression
Pre-compressing static files at build time eliminates runtime CPU load.Build Script
Server Configuration
- No runtime CPU load
- Best compression ratio (quality 11)
- Instant response
Performance Measurement
1. Browser Developer Tools
2. Server Logging
3. Load Testing
Practical Optimization Checklist
- Initial Setup
- API Optimization
- Combining Caching
- Monitoring
Enable global compressionSet threshold
- General: 1024 (1KB)
- Mobile: 256 (256B)
- High-performance: 4096 (4KB)
- Static: brotli (pre-compressed)
- Dynamic: gzip (real-time)
Common Mistakes
Performance Benchmark
Based on actual 100KB JSON response:| Configuration | Compression Time | Transfer Size | Network Time | Total Time |
|---|---|---|---|---|
| No compression | 0ms | 100KB | 1000ms | 1000ms |
| Gzip | 2ms | 14KB | 140ms | 142ms |
| Brotli | 5ms | 12KB | 120ms | 125ms |
| Pre-compressed | 0ms | 12KB | 120ms | 120ms |
- Gzip: 85% time savings
- Brotli: 87% time savings
- Pre-compressed: 88% time savings (best)