Compression Techniques
Shrink data to save bandwidth and speed up transfers.
1The Vacuum Bag Analogy
Compression reduces data size by encoding information more efficiently. Trade CPU cycles for bandwidth savings.
2Common Algorithms
gzip
Industry standard. Widely supported. Good balance of speed and ratio.
Best for: HTTP responses, file archiving
Brotli
Better compression than gzip. Modern browsers support it.
Best for: Static assets, CDN, pre-compressed files
LZ4
Optimized for speed over ratio. Great for real-time.
Best for: Database storage, Kafka, real-time streaming
Zstandard (zstd)
Facebook's algorithm. Configurable speed/ratio tradeoff.
Best for: Logs, backups, modern systems
3HTTP Compression
Request/Response Headers
// Client advertises what it can decompress
Accept-Encoding: gzip, deflate, br
// Server responds with what it used
Content-Encoding: gzip
// Browser automatically decompresses
// No extra client code needed!Compress These
- ✓JSON responses
- ✓HTML, CSS, JS
- ✓Text-based formats
- ✓SVG images
Skip These
- ⚠JPEG, PNG, WebP (already compressed)
- ⚠Video/audio files
- ⚠Encrypted data
- ⚠Very small responses (<1KB)
4Real Impact
| Content | Original | gzip | Brotli |
|---|---|---|---|
| JSON API response | 100 KB | 25 KB (75%) | 20 KB (80%) |
| React bundle | 500 KB | 150 KB (70%) | 120 KB (76%) |
| HTML page | 50 KB | 12 KB (76%) | 9 KB (82%) |
| JPEG image | 200 KB | 198 KB (1%) | 197 KB (1.5%) |
5When to Compress
API responses (JSON)
Always. gzip is standard. 70-80% reduction.
Static assets (JS, CSS)
Pre-compress with Brotli. Serve from CDN.
Real-time data (streaming)
LZ4 or skip. CPU matters more than size.
Database storage
LZ4 for hot data, zstd for cold. Balance speed/space.
Very small payloads (<1KB)
Skip. Overhead may exceed savings.
6Server Configuration
Nginx
gzip on;
gzip_types application/json
text/css
application/javascript;
gzip_min_length 1000;
# Brotli (module required)
brotli on;
brotli_types application/json;Express.js
const compression = require('compression');
app.use(compression({
threshold: 1024, // min 1KB
level: 6, // 1-9, higher = smaller but slower
filter: (req, res) => {
// Don't compress images
if (req.path.match(/\.(jpg|png)$/)) {
return false;
}
return true;
}
}));7Key Takeaways
?Quiz
1. API returns 50KB JSON. Should you compress?
2. Best compression for real-time streaming?