A comprehensive guide to caching strategies for web performance optimization, including browser caching, CDN caching, server-side caching, and cache invalidation techniques.
Caching is a performance optimization technique that stores frequently accessed data in temporary storage locations to reduce access time, bandwidth usage, and server load. Effective caching strategies are essential for creating fast, scalable web applications.
Client-side caching that stores resources locally in the user's browser:
| Cache Type | Storage Location | Use Case | Persistence |
|---|---|---|---|
| HTTP Cache | Browser cache | Static assets | Based on headers |
| Service Worker Cache | Cache API | Offline functionality | Programmatic control |
| Memory Cache | RAM | Current session | Session only |
| Disk Cache | Hard drive | Persistent storage | Survives restarts |
Caching implemented on the server to reduce processing time:
// Express.js caching middleware
const express = require('express');
const app = express();
// Static assets with long-term caching
app.use('/static', express.static('public', {
maxAge: '1y', // Cache for 1 year
etag: true,
lastModified: true,
immutable: true
}));
// API responses with short-term caching
app.get('/api/data', (req, res) => {
res.set({
'Cache-Control': 'public, max-age=300', // 5 minutes
'ETag': generateETag(data),
'Last-Modified': new Date().toUTCString()
});
res.json(data);
});
// No caching for sensitive data
app.get('/api/user', (req, res) => {
res.set({
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
});
res.json(userData);
});
// Conditional caching with ETags
app.get('/api/content/:id', (req, res) => {
const content = getContent(req.params.id);
const etag = generateETag(content);
res.set('ETag', etag);
// Check if client has current version
if (req.headers['if-none-match'] === etag) {
return res.status(304).end(); // Not Modified
}
res.json(content);
});| Directive | Description | Use Case |
|---|---|---|
| public | Can be cached by any cache | Static assets |
| private | Only cached by browser | User-specific content |
| no-cache | Must revalidate before use | Dynamic content |
| no-store | Never cache | Sensitive data |
| max-age | Cache lifetime in seconds | All cached content |
| must-revalidate | Must check with server when stale | Critical content |
| immutable | Content never changes | Versioned assets |
// Service Worker with multiple caching strategies
class ServiceWorkerCache {
constructor() {
this.CACHE_NAME = 'app-cache-v1';
this.STATIC_CACHE = 'static-cache-v1';
this.DYNAMIC_CACHE = 'dynamic-cache-v1';
this.API_CACHE = 'api-cache-v1';
this.init();
}
init() {
self.addEventListener('install', this.handleInstall.bind(this));
self.addEventListener('activate', this.handleActivate.bind(this));
self.addEventListener('fetch', this.handleFetch.bind(this));
}
async handleInstall(event) {
event.waitUntil(
caches.open(this.STATIC_CACHE).then(cache => {
return cache.addAll([
'/',
'/css/app.css',
'/js/app.js',
'/images/logo.svg',
'/manifest.json'
]);
})
);
}
async handleActivate(event) {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== this.STATIC_CACHE &&
cacheName !== this.DYNAMIC_CACHE &&
cacheName !== this.API_CACHE) {
return caches.delete(cacheName);
}
})
);
})
);
}
handleFetch(event) {
const { request } = event;
// Route to appropriate caching strategy
if (request.url.includes('/api/')) {
event.respondWith(this.networkFirst(request));
} else if (request.destination === 'image') {
event.respondWith(this.cacheFirst(request));
} else if (request.mode === 'navigate') {
event.respondWith(this.staleWhileRevalidate(request));
} else {
event.respondWith(this.cacheFirst(request));
}
}
// Cache First Strategy - Good for static assets
async cacheFirst(request) {
const cachedResponse = await caches.match(request);
if (cachedResponse) {
return cachedResponse;
}
try {
const networkResponse = await fetch(request);
if (networkResponse.ok) {
const cache = await caches.open(this.DYNAMIC_CACHE);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
// Return fallback for images
if (request.destination === 'image') {
return caches.match('/images/fallback.jpg');
}
throw error;
}
}
// Network First Strategy - Good for API calls
async networkFirst(request) {
try {
const networkResponse = await fetch(request);
if (networkResponse.ok) {
const cache = await caches.open(this.API_CACHE);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
const cachedResponse = await caches.match(request);
if (cachedResponse) {
return cachedResponse;
}
// Return offline page for navigation requests
if (request.mode === 'navigate') {
return caches.match('/offline.html');
}
throw error;
}
}
// Stale While Revalidate - Good for HTML pages
async staleWhileRevalidate(request) {
const cachedResponse = await caches.match(request);
const fetchPromise = fetch(request).then(networkResponse => {
if (networkResponse.ok) {
const cache = caches.open(this.DYNAMIC_CACHE);
cache.then(c => c.put(request, networkResponse.clone()));
}
return networkResponse;
});
return cachedResponse || fetchPromise;
}
// Cache with timeout
async cacheWithTimeout(request, timeout = 3000) {
const cachedResponse = await caches.match(request);
const networkPromise = fetch(request);
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Network timeout')), timeout);
});
try {
const networkResponse = await Promise.race([networkPromise, timeoutPromise]);
if (networkResponse.ok) {
const cache = await caches.open(this.DYNAMIC_CACHE);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
if (cachedResponse) {
return cachedResponse;
}
throw error;
}
}
}
// Initialize service worker cache
const swCache = new ServiceWorkerCache();// Simple in-memory cache with TTL
class MemoryCache {
constructor(defaultTTL = 300000) { // 5 minutes default
this.cache = new Map();
this.timers = new Map();
this.defaultTTL = defaultTTL;
}
set(key, value, ttl = this.defaultTTL) {
// Clear existing timer
if (this.timers.has(key)) {
clearTimeout(this.timers.get(key));
}
// Set value
this.cache.set(key, {
value,
timestamp: Date.now(),
ttl
});
// Set expiration timer
const timer = setTimeout(() => {
this.delete(key);
}, ttl);
this.timers.set(key, timer);
}
get(key) {
const item = this.cache.get(key);
if (!item) {
return null;
}
// Check if expired
if (Date.now() - item.timestamp > item.ttl) {
this.delete(key);
return null;
}
return item.value;
}
delete(key) {
this.cache.delete(key);
if (this.timers.has(key)) {
clearTimeout(this.timers.get(key));
this.timers.delete(key);
}
}
clear() {
this.cache.clear();
this.timers.forEach(timer => clearTimeout(timer));
this.timers.clear();
}
size() {
return this.cache.size;
}
// Get or set pattern
async getOrSet(key, factory, ttl) {
let value = this.get(key);
if (value === null) {
value = await factory();
this.set(key, value, ttl);
}
return value;
}
}
// Usage example
const cache = new MemoryCache();
// Cache API responses
async function fetchUserData(userId) {
return cache.getOrSet(
`user:${userId}`,
() => fetch(`/api/users/${userId}`).then(r => r.json()),
300000 // 5 minutes
);
}
// Cache expensive computations
function fibonacci(n) {
return cache.getOrSet(
`fib:${n}`,
() => {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
},
3600000 // 1 hour
);
}// Redis-based caching for distributed applications
const redis = require('redis');
class RedisCache {
constructor(options = {}) {
this.client = redis.createClient(options);
this.defaultTTL = options.defaultTTL || 300; // 5 minutes
this.client.on('error', (err) => {
console.error('Redis Cache Error:', err);
});
}
async set(key, value, ttl = this.defaultTTL) {
const serialized = JSON.stringify(value);
if (ttl > 0) {
await this.client.setex(key, ttl, serialized);
} else {
await this.client.set(key, serialized);
}
}
async get(key) {
const value = await this.client.get(key);
if (value === null) {
return null;
}
try {
return JSON.parse(value);
} catch (error) {
console.error('Cache deserialization error:', error);
return null;
}
}
async delete(key) {
await this.client.del(key);
}
async exists(key) {
return await this.client.exists(key);
}
async ttl(key) {
return await this.client.ttl(key);
}
async flush() {
await this.client.flushall();
}
// Pattern-based operations
async deletePattern(pattern) {
const keys = await this.client.keys(pattern);
if (keys.length > 0) {
await this.client.del(...keys);
}
}
// Cache with tags for invalidation
async setWithTags(key, value, tags = [], ttl = this.defaultTTL) {
await this.set(key, value, ttl);
// Store tag associations
for (const tag of tags) {
await this.client.sadd(`tag:${tag}`, key);
if (ttl > 0) {
await this.client.expire(`tag:${tag}`, ttl);
}
}
}
async invalidateTag(tag) {
const keys = await this.client.smembers(`tag:${tag}`);
if (keys.length > 0) {
await this.client.del(...keys);
}
await this.client.del(`tag:${tag}`);
}
// Distributed locking for cache warming
async lock(key, ttl = 30) {
const lockKey = `lock:${key}`;
const result = await this.client.set(lockKey, '1', 'EX', ttl, 'NX');
return result === 'OK';
}
async unlock(key) {
await this.client.del(`lock:${key}`);
}
}
// Usage with Express.js
const cache = new RedisCache();
// Caching middleware
function cacheMiddleware(ttl = 300) {
return async (req, res, next) => {
const key = `cache:${req.originalUrl}`;
try {
const cached = await cache.get(key);
if (cached) {
res.set('X-Cache', 'HIT');
return res.json(cached);
}
// Override res.json to cache response
const originalJson = res.json;
res.json = function(data) {
cache.set(key, data, ttl);
res.set('X-Cache', 'MISS');
return originalJson.call(this, data);
};
next();
} catch (error) {
console.error('Cache middleware error:', error);
next();
}
};
}
// Use caching middleware
app.get('/api/products', cacheMiddleware(600), (req, res) => {
// API logic here
});// Cache invalidation manager
class CacheInvalidator {
constructor(cache) {
this.cache = cache;
this.dependencies = new Map();
this.watchers = new Map();
}
// Set cache dependencies
setDependencies(key, dependencies) {
this.dependencies.set(key, dependencies);
// Register reverse dependencies
dependencies.forEach(dep => {
if (!this.watchers.has(dep)) {
this.watchers.set(dep, new Set());
}
this.watchers.get(dep).add(key);
});
}
// Invalidate cache and dependents
async invalidate(key) {
await this.cache.delete(key);
// Invalidate dependent caches
const dependents = this.watchers.get(key);
if (dependents) {
for (const dependent of dependents) {
await this.invalidate(dependent);
}
}
// Clean up
this.dependencies.delete(key);
this.watchers.delete(key);
}
// Time-based invalidation
scheduleInvalidation(key, delay) {
setTimeout(() => {
this.invalidate(key);
}, delay);
}
// Event-based invalidation
onDataChange(entity, callback) {
// Listen for data changes and invalidate related caches
const pattern = `*${entity}*`;
// This would integrate with your data layer
// to detect changes and trigger invalidation
callback(pattern);
}
}
// Usage example
const invalidator = new CacheInvalidator(cache);
// Set up cache dependencies
invalidator.setDependencies('user:123', ['users', 'profiles']);
invalidator.setDependencies('user:list', ['users']);
// When user data changes, invalidate related caches
async function updateUser(userId, data) {
await updateUserInDatabase(userId, data);
await invalidator.invalidate(`user:${userId}`);
await invalidator.invalidate('user:list');
}// Cache performance monitoring
class CacheAnalytics {
constructor() {
this.metrics = {
hits: 0,
misses: 0,
sets: 0,
deletes: 0,
errors: 0
};
this.hitRateHistory = [];
this.responseTimeHistory = [];
}
recordHit(responseTime) {
this.metrics.hits++;
this.responseTimeHistory.push(responseTime);
this.updateHitRate();
}
recordMiss(responseTime) {
this.metrics.misses++;
this.responseTimeHistory.push(responseTime);
this.updateHitRate();
}
recordSet() {
this.metrics.sets++;
}
recordDelete() {
this.metrics.deletes++;
}
recordError() {
this.metrics.errors++;
}
updateHitRate() {
const total = this.metrics.hits + this.metrics.misses;
const hitRate = total > 0 ? (this.metrics.hits / total) * 100 : 0;
this.hitRateHistory.push({
timestamp: Date.now(),
hitRate
});
// Keep only last 100 entries
if (this.hitRateHistory.length > 100) {
this.hitRateHistory.shift();
}
}
getReport() {
const total = this.metrics.hits + this.metrics.misses;
const hitRate = total > 0 ? (this.metrics.hits / total) * 100 : 0;
const avgResponseTime = this.responseTimeHistory.length > 0 ?
this.responseTimeHistory.reduce((sum, time) => sum + time, 0) / this.responseTimeHistory.length :
0;
return {
...this.metrics,
hitRate: `${hitRate.toFixed(2)}%`,
averageResponseTime: `${avgResponseTime.toFixed(2)}ms`,
totalRequests: total
};
}
}
// Integrate analytics with cache
const analytics = new CacheAnalytics();
// Wrap cache methods with analytics
const originalGet = cache.get;
cache.get = async function(key) {
const startTime = performance.now();
const result = await originalGet.call(this, key);
const responseTime = performance.now() - startTime;
if (result !== null) {
analytics.recordHit(responseTime);
} else {
analytics.recordMiss(responseTime);
}
return result;
};Explore these comprehensive pillar articles related to Caching
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Comprehensive guide to triadic color schemes - three colors evenly spaced around the color wheel that create balanced, vibrant, and dynamic visual compositions with mathematical precision and artistic appeal.
Discover more about Caching and related color theory concepts
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
A comprehensive guide to monochromatic color schemes - sophisticated single-hue harmonies that create unified visual experiences through systematic variations in saturation, lightness, and tonal relationships, essential for elegant design compositions, brand consistency, and advanced color theory applications requiring cohesive aesthetic unity.
A comprehensive guide to split-complementary color schemes - sophisticated three-color harmonies that combine a base color with two colors adjacent to its complement, creating balanced visual contrast with reduced tension compared to direct complementary pairs, essential for refined design compositions, brand identity systems, and advanced color theory applications.
A comprehensive guide to tetradic color schemes - sophisticated four-color harmonies that use two complementary pairs arranged in rectangular or square formations on the color wheel, providing maximum color variety while maintaining structured relationships essential for dynamic design compositions, brand systems, and advanced color theory applications.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary