General Best Practices
Core Principles
- Enable compression by default for all text-based content
- Use appropriate compression levels based on content type and server resources
- Always include Vary: Accept-Encoding header for proper caching
- Skip compression for already-compressed formats (images, videos, WOFF fonts)
- Set minimum size thresholds (typically 1KB) to avoid overhead
- Test thoroughly across browsers and devices
Security Considerations
BREACH Attack Prevention
- Disable compression for sensitive data that includes user input
- Use CSRF tokens that change with each request
- Separate static and dynamic content on different domains
- Consider rate limiting for compressed responses
- Implement length hiding by adding random padding
Security Headers Example
# Nginx security configuration
location /api/sensitive {
# Disable compression for sensitive endpoints
gzip off;
brotli off;
# Add security headers
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options DENY;
add_header Content-Security-Policy "default-src 'self'";
}
Content-Type Specific Guidelines
Always Compress
- HTML files (.html, .htm)
- CSS files (.css)
- JavaScript (.js, .mjs)
- JSON data (.json)
- XML files (.xml)
- SVG images (.svg)
- Plain text (.txt, .csv)
Never Compress
- JPEG images (.jpg, .jpeg)
- PNG images (.png)
- GIF images (.gif)
- WebP images (.webp)
- WOFF/WOFF2 fonts
- Video files (mp4, webm)
- ZIP/RAR archives
Conditional Compression
- PDF files (check if optimized)
- Binary data (case by case)
- Large API responses
- Log files
- Database exports
Compression Level Guidelines
Recommended Compression Levels
# Dynamic content (real-time compression)
gzip_comp_level 5; # Balanced performance
brotli_comp_level 4; # Good for dynamic content
# Static content (pre-compressed)
gzip -9 static.css # Maximum compression
brotli -11 static.css # Maximum Brotli compression
# API responses
gzip_comp_level 6; # Default level
brotli_comp_level 5; # Slightly better than gzip
Caching and Compression
Cache Configuration
- Always use Vary: Accept-Encoding to prevent cache pollution
- Pre-compress static assets during build process
- Cache compressed versions separately from uncompressed
- Set appropriate cache headers for compressed content
- Use ETags carefully with compressed content
Proper Cache Headers
location ~* \.(js|css|html)$ {
# Enable compression
gzip_static on;
brotli_static on;
# Cache headers
expires 1y;
add_header Cache-Control "public, immutable";
add_header Vary "Accept-Encoding";
# ETag handling
etag on;
}
Mobile Optimization
Mobile-First Compression
- Lower compression levels for faster decompression on mobile CPUs
- Consider network conditions - higher compression for slow networks
- Test battery impact of decompression on target devices
- Use adaptive compression based on User-Agent when necessary
- Monitor real user metrics to optimize settings
API Design Best Practices
RESTful API Compression
// Express.js middleware for API compression
app.use(compression({
filter: (req, res) => {
// Don't compress if client doesn't support it
if (req.headers['x-no-compression']) {
return false;
}
// Don't compress Server-Sent Events
if (res.getHeader('Content-Type') === 'text/event-stream') {
return false;
}
// Compress JSON responses
return /json|text|javascript|css|html|xml/.test(
res.getHeader('Content-Type')
);
},
threshold: 1024,
level: 6
}));
Monitoring and Metrics
Key Metrics to Track
- Compression ratio by content type
- CPU usage during compression
- Bandwidth savings over time
- Page load times with/without compression
- Cache hit rates for compressed content
- Error rates related to compression
Common Mistakes to Avoid
Compression Anti-Patterns
- Double compression: Compressing already-compressed content
- Missing Vary header: Causes cache pollution
- Compressing small files: Overhead exceeds benefits
- Wrong MIME types: Incorrect Content-Type headers
- Ignoring CPU limits: High compression levels on busy servers
- Forgetting about proxies: Some proxies strip compression
Future-Proofing
Preparing for the Future
- Implement content negotiation properly to support new algorithms
- Monitor browser adoption of new compression methods
- Keep server software updated for latest compression modules
- Use feature detection not browser detection
- Plan for dictionary compression standards
- Consider QUIC/HTTP3 compression implications
Compliance and Standards
Standards Compliance
- Follow RFC 7231 for HTTP/1.1 semantics
- Implement RFC 7232 for conditional requests
- Support RFC 7694 for HTTP Client Hints
- Consider WCAG 2.1 performance guidelines
- Meet Core Web Vitals thresholds