Best Practices

Industry standards and recommendations for HTTP compression

General Best Practices

Core Principles

  1. Enable compression by default for all text-based content
  2. Use appropriate compression levels based on content type and server resources
  3. Always include Vary: Accept-Encoding header for proper caching
  4. Skip compression for already-compressed formats (images, videos, WOFF fonts)
  5. Set minimum size thresholds (typically 1KB) to avoid overhead
  6. 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

  1. Always use Vary: Accept-Encoding to prevent cache pollution
  2. Pre-compress static assets during build process
  3. Cache compressed versions separately from uncompressed
  4. Set appropriate cache headers for compressed content
  5. 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

  1. Compression ratio by content type
  2. CPU usage during compression
  3. Bandwidth savings over time
  4. Page load times with/without compression
  5. Cache hit rates for compressed content
  6. 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

  1. Follow RFC 7231 for HTTP/1.1 semantics
  2. Implement RFC 7232 for conditional requests
  3. Support RFC 7694 for HTTP Client Hints
  4. Consider WCAG 2.1 performance guidelines
  5. Meet Core Web Vitals thresholds