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:
- Browser Cache: Controlled via Cache-Control and Expires headers
- CDN Edge Nodes: Closest to users, stores hot data
- CDN Tiered Layer: Cache layer before origin fetch, reduces origin load
- 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" />
5.4 A Real-World Tuning Case
A news site's homepage had many images and API requests, with a cache hit ratio of only about 55% and an LCP around 4 seconds. The team adjusted in this order: first, every image got Cache-Control: public, max-age=31536000, immutable plus hashed URLs, pushing image hit ratio to 98%; then the article-list API got a short max-age=60 cache with s-maxage so the CDN caches while the browser does not; finally, popular-channel HTML was cached at the CDN for 5 minutes. Two weeks later LCP was down to 1.8 seconds and origin traffic fell about 70%. No advanced tricks here — the key is separating what should be cached from what should not, and giving every resource type an explicit TTL.
6. FAQ
Why is the hit ratio high but the page still slow?
A high hit ratio only means a large share of requests are served from the edge; it says nothing about byte size. If large images are uncompressed or the HTML carries many synchronous scripts, first paint still suffers. Read hit ratio together with resource weight and TTFB.
Should HTML be cached at all?
Public pages that change infrequently can be cached for tens of seconds to a few minutes. Personalized pages like login state and carts must not be cached, or need cache keys that separate users.
Why do users still see the old page after a release?
When a resource URL does not change, browsers and CDNs keep serving the old cache. Hash the filename at release time (for example app.8f3c.css), or purge the CDN cache proactively.
Does caching conflict with SEO?
No. Caching only stores a response copy and does not affect crawling, as long as you return proper 200/304 responses and never cache authenticated pages.
7. Mobile Optimization
Mobile network environments are more complex and require additional optimization:
- AMP (Accelerated Mobile Pages): Google's mobile acceleration solution
- PWA (Progressive Web App): Offline caching + fast loading
- Responsive Images: Load different image sizes based on screen dimensions
- Reduce Third-Party Scripts: Third-party scripts are mobile performance killers
8. 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)
9. 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.
Reference: MDN HTTP caching https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching; Cloudflare Cache Rules docs https://developers.cloudflare.com/cache/how-to/cache-rules/