Website Speed Optimization: CDN + Cache Best Practices Guide

Website loading speed directly impacts user experience, SEO rankings, and conversion rates. Data shows that every 1-second increase in page load time reduces conversions by an average of 7%. This article shares proven CDN + cache optimization strategies validated across multiple projects.

1. Performance Baseline Measurement

Before starting optimization, establish a performance baseline:

Core Web Vitals

Metric Description Target
LCP (Largest Contentful Paint) Main content loading time < 2.5s
FID (First Input Delay) Page interaction responsiveness < 100ms
CLS (Cumulative Layout Shift) Page visual stability < 0.1

Measurement Tools

  • Lighthouse: Built into Chrome DevTools, provides specific optimization recommendations
  • PageSpeed Insights: Google's official tool, simulates real user environments
  • WebPageTest: Multi-location, multi-device testing
  • GTmetrix: Visual performance reports

2. CDN Optimization Strategies

2.1 Choose the Right CDN Configuration

# Nginx configuration snippet - optimized for CDN
# Enable Brotli compression (20-30% better than Gzip)
brotli on;
brotli_types text/plain text/css application/javascript application/json image/svg+xml;

# Set cache headers
location ~* \.(jpg|jpeg|png|gif|ico|webp|svg)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
    add_header Vary "Accept-Encoding";
}

location ~* \.(css|js)$ {
    expires 7d;
    add_header Cache-Control "public, immutable";
}

location / {
    # HTML: no cache or short cache
    add_header Cache-Control "no-cache, must-revalidate";
}

2.2 Cache Tier Optimization

An effective caching strategy requires multiple tiers working together:

Browser Cache → CDN Edge Cache → CDN Tiered Cache → Origin Server
    ↓                ↓                  ↓                ↓
  Short-term      Long-term          Short-term       Real-time

Tier Explanation:

  1. Browser Cache: Controlled via Cache-Control and Expires headers
  2. CDN Edge Nodes: Closest to users, stores hot data
  3. CDN Tiered Layer: Cache layer before origin fetch, reduces origin load
  4. Origin Server: Source of the latest data

2.3 CDN Pre-warming

After major updates, proactively notify CDN to cache content on edge nodes:

# Cloudflare pre-warming (via Cache Rules)
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache" \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  --data '{"prefixes":["https://example.com/assets/"]}'

3. Cache Strategy Details

3.1 Static Resource Cache Strategy

Resource Type Browser Cache CDN Cache Notes
Images (jpg/png/webp/avif) 30 days 30 days Hash filenames
CSS files 365 days 365 days With version or hash
JavaScript files 365 days 365 days With version or hash
Font files 365 days 365 days Preload critical fonts
Video files 7 days 7 days Consider chunking for large files
HTML pages 0 or no cache 0-1 hour Needs real-time updates

3.2 Dynamic Content Caching

For API responses, note the following when using CDN cache:

# Do not cache authenticated requests
location /api/ {
    if ($http_cookie ~* "session|token") {
        set $no_cache 1;
    }
    proxy_no_cache $no_cache;
    proxy_cache_bypass $no_cache;
}

# Short cache for public APIs
location /api/public/ {
    add_header Cache-Control "public, max-age=60";
}

4. Image Optimization (Most Critical)

Images account for 60-70% of total webpage size. Optimizing images is the most cost-effective acceleration method:

4.1 Image Format Selection

Format Compression Ratio Browser Support Use Case
WebP 25-35% smaller than JPEG Widely supported Photos, complex images
AVIF 50% smaller than JPEG Newer browsers Photos, high compression needs
SVG Lossless Universal Icons, logos, illustrations

4.2 CDN Image Processing

Use CDN image processing features:

<!-- Cloudflare Image Resizing -->
<img src="/cdn-cgi/image/width=800,quality=80,format=auto/photo.jpg" />

<!-- Alibaba Cloud image processing -->
<img src="/photo.jpg?x-oss-process=image/resize,w_800/quality,q_80/format,webp" />

4.3 Lazy Loading

<!-- Native lazy loading (modern browsers) -->
<img src="photo.jpg" loading="lazy" alt="..." />

<!-- With Intersection Observer -->
<img data-src="photo.jpg" class="lazy" alt="..." />

5. Advanced Performance Optimization

5.1 HTTP/2 and HTTP/3

  • HTTP/2: Multiplexing, header compression, server push
  • HTTP/3: Based on QUIC protocol, faster connection establishment, more stable in poor network conditions

Ensure both CDN and origin server have HTTP/2/3 enabled:

# Nginx configuration
listen 443 ssl http2;
listen 443 quic reuseport;

5.2 Resource Bundling and Compression

Combine multiple small files to reduce HTTP requests:

# Combine CSS
cat reset.css layout.css style.css > combined.css

# Use build tools (Webpack/Vite) to automate

5.3 Preload Critical Resources

<!-- Preload critical CSS -->
<link rel="preload" href="critical.css" as="style" />

<!-- Preload fonts -->
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin />

<!-- Preconnect to third-party domains -->
<link rel="preconnect" href="https://fonts.googleapis.com" />

6. Mobile Optimization

Mobile network environments are more complex and require additional optimization:

  1. AMP (Accelerated Mobile Pages): Google's mobile acceleration solution
  2. PWA (Progressive Web App): Offline caching + fast loading
  3. Responsive Images: Load different image sizes based on screen dimensions
  4. Reduce Third-Party Scripts: Third-party scripts are mobile performance killers

7. Performance Optimization Checklist

  • Enable CDN and configure caching correctly
  • Use WebP/AVIF image formats
  • Enable Brotli/Gzip compression
  • Enable HTTP/2 or HTTP/3
  • Version or hash resource files
  • Inline critical CSS
  • Async load non-critical resources
  • Use resource hints (preload/preconnect)
  • Enable browser caching
  • Remove unused CSS/JS
  • Reduce redirects
  • Optimize TTFB (Time to First Byte)

8. Summary

Website speed optimization is an ongoing process, not a one-time task. CDN + Caching + Image Optimization are the three measures with the highest ROI, typically showing significant results in a short time. It is recommended to regularly use Lighthouse to measure performance scores and iterate continuously.