Caching Layers
A complete caching strategy uses multiple layers, each optimized for different content types:
- Browser cache — static assets (CSS, JS, images)
- CDN — global edge caching
- Reverse proxy cache — Varnish or Nginx FastCGI cache
- Application cache — Redis or Memcached
- Database cache — query cache, buffer pool
Varnish (HTTP Accelerator)
Varnish sits in front of your web server and caches full HTTP responses:
sudo apt install -y varnishEdit /etc/varnish/default.vcl:
backend default {
.host = "127.0.0.1";
.port = "8080";
}
sub vcl_recv {
# Don't cache POST requests
if (req.method == "POST") { return (pass); }
# Don't cache authenticated users
if (req.http.Cookie ~ "session") { return (pass); }
}
sub vcl_backend_response {
set beresp.ttl = 1h;
}Varnish can serve cached pages in microseconds — 100-1000x faster than generating dynamically.
Redis (Application Cache)
# Cache database queries
$cacheKey = "user:profile:" . $userId;
$cached = $redis->get($cacheKey);
if ($cached) return json_decode($cached);
$user = $db->fetch("SELECT * FROM users WHERE id = ?", [$userId]);
$redis->setex($cacheKey, 300, json_encode($user));
return $user;CDN (Content Delivery Network)
A CDN caches your content on servers worldwide, reducing latency for global visitors. Popular options:
- Cloudflare — free tier, DNS-based setup
- BunnyCDN — affordable, fast
- AWS CloudFront — integration with AWS
Cache Invalidation
The hardest part of caching. Common strategies:
- TTL-based — cache expires after a set time
- Event-based — purge cache when data changes
- Versioned URLs —
style.css?v=13