We are going to explain various caching strategies and components. We'll cover:
- CDN (Content Delivery Network)
- Reverse Proxy Caching
- Application Caches (in-memory, distributed)
- Database Caches (query cache, buffer pool, etc.)
- Invalidation Patterns (TTL, LRU, explicit invalidation, etc.)
- Cache Keys
- TTLs (Time To Live)
- Consistency Trade-offs (cache aside, write through, write behind, etc.)
We'll provide code/config sketches for:
- CDN: configuration example (using Cloudflare or AWS CloudFront as an example)
- Reverse Proxy: nginx configuration for caching
- Application Cache: example using Redis in a Python (Flask) app
- Database Cache: example of using query cache in MySQL and buffer pool in PostgreSQL
- Invalidation: example of cache invalidation in application cache (Redis)
- Cache Keys: example of generating cache keys
- TTLs: setting TTL in Redis
- Consistency: example of cache-aside pattern in code
Let's break it down.
Note: The examples are for illustration and may require adjustments for production use.
I'll explain caching strategies with practical examples and configuration sketches.
1. Content Delivery Network (CDN)
What it is: Edge servers caching static/dynamic content close to users.
Use Case: Global static assets, video streaming, API acceleration.
Configuration Sketch (AWS CloudFront):
# cloudfront.yml (conceptual)
Distribution:
Origins:
- ID: "app-origin"
DomainName: "app.example.com"
CustomOriginConfig:
HTTPPort: 80
HTTPSPort: 443
DefaultCacheBehavior:
TargetOriginId: "app-origin"
ViewerProtocolPolicy: "redirect-to-https"
AllowedMethods:
- GET
- HEAD
CachedMethods:
- GET
- HEAD
MinTTL: 0
DefaultTTL: 86400 # 24 hours
MaxTTL: 31536000 # 1 year
Compress: true
CachePolicyId: "managed-CachingOptimized"
Code Sketch (Cache control headers):
# Flask/Django example
from flask import make_response
@app.route('/static/<path:path>')
def static_files(path):
response = send_file(f'static/{path}')
# CDN will cache for 1 year (immutable assets)
response.headers['Cache-Control'] = 'public, max-age=31536000, immutable'
return response
2. Reverse Proxy Caching
What it is: Intermediate server caching responses before reaching application.
Use Case: API caching, microservices, load reduction.
Nginx Configuration:
# nginx.conf
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m
inactive=60m use_temp_path=off;
server {
location /api/ {
proxy_cache api_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_pass http://backend;
# Cache control
add_header X-Cache-Status $upstream_cache_status;
}
}
3. Application Caches
In-Memory Cache (Python Redis example):
import redis
import pickle
from functools import wraps
class CacheManager:
def __init__(self, host='localhost', port=6379, db=0):
self.redis = redis.Redis(host=host, port=port, db=db)
def cached(self, ttl=300, key_prefix='cache:'):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Generate cache key
cache_key = f"{key_prefix}{func.__name__}:{args}:{kwargs}"
# Try get from cache
cached = self.redis.get(cache_key)
if cached:
return pickle.loads(cached)
# Execute and cache
result = func(*args, **kwargs)
self.redis.setex(cache_key, ttl, pickle.dumps(result))
return result
return wrapper
return decorator
# Usage
cache = CacheManager()
@cache.cached(ttl=600)
def get_user_profile(user_id):
return db.query("SELECT * FROM users WHERE id = %s", user_id)
Distributed Cache (Hazelcast/Infinispan for Java):
// Spring Boot example
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
return new HazelcastCacheManager(hazelcastInstance);
}
@Cacheable(value = "users", key = "#userId")
public User getUser(Long userId) {
return userRepository.findById(userId).orElse(null);
}
}
4. Database Caches
MySQL Query Cache (deprecated in 8.0, but relevant for older versions):
-- Enable query cache (MySQL 5.7)
SET GLOBAL query_cache_size = 104857600; -- 100MB
SET GLOBAL query_cache_type = 1;
-- Check status
SHOW STATUS LIKE 'Qcache%';
PostgreSQL Buffer Pool (shared_buffers):
-- postgresql.conf
shared_buffers = 4GB # 25% of RAM typically
effective_cache_size = 12GB # Estimate of OS + DB cache
work_mem = 64MB
maintenance_work_mem = 1GB
Application-Level DB Cache:
# Django database caching
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
}
}
# Create cache table
# python manage.py createcachetable
5. Cache Invalidation Patterns
TTL-Based (Time-Based Expiration)
# Redis TTL example
redis.setex('product:123', 3600, serialized_product) # 1 hour
Explicit Invalidation
def update_product(product_id, data):
# Update database
db.update('products', data, where={'id': product_id})
# Invalidate cache
cache_key = f'product:{product_id}'
redis.delete(cache_key)
# Or update cache immediately
redis.setex(cache_key, 3600, serialize(data))
Write-Through Pattern
class WriteThroughCache:
def set(self, key, value, ttl=None):
# Write to both cache and DB
redis.setex(key, ttl, value) if ttl else redis.set(key, value)
db.execute("INSERT OR REPLACE INTO cache_table VALUES (?, ?)", (key, value))
def get(self, key):
# Always read from cache (cache is source of truth)
return redis.get(key)
Write-Behind Pattern
class WriteBehindCache:
def __init__(self):
self.write_queue = []
self.processing = False
def set(self, key, value):
# Write to cache immediately
redis.set(key, value)
# Queue DB write
self.write_queue.append({'key': key, 'value': value})
if not self.processing:
self._process_queue()
def _process_queue(self):
self.processing = True
while self.write_queue:
item = self.write_queue.pop(0)
db.execute("INSERT INTO table VALUES (?, ?)",
(item['key'], item['value']))
self.processing = False
Cache-Aside (Lazy Loading)
def get_user_profile(user_id):
cache_key = f"user:{user_id}:profile"
# Try cache first
cached = redis.get(cache_key)
if cached:
return json.loads(cached)
# Cache miss - load from DB
profile = db.query("SELECT * FROM users WHERE id = %s", user_id)
# Store in cache
redis.setex(cache_key, 3600, json.dumps(profile))
return profile
def update_user_profile(user_id, data):
# Update DB
db.execute("UPDATE users SET ... WHERE id = %s", user_id, data)
# Invalidate cache (delete so next read repopulates)
redis.delete(f"user:{user_id}:profile")
6. Cache Keys Design
Structured Key Naming:
def generate_cache_key(prefix, *args, **kwargs):
"""
Example keys:
user:123:profile
product:456:reviews:page:2:sort:date
api:v1:users:filter:active:sort:name
"""
key_parts = [prefix]
key_parts.extend(str(arg) for arg in args)
for k, v in sorted(kwargs.items()):
key_parts.append(f"{k}:{v}")
return ":".join(key_parts)
# Usage
key = generate_cache_key(
'product',
123,
'reviews',
page=2,
sort='date',
filter='verified'
)
# Result: "product:123:reviews:page:2:sort:date:filter:verified"
Hash Tags for Redis Cluster:
# Ensure related keys are on same shard
user_key = "{user}:123:profile" # Hash tag = {user}
friends_key = "{user}:123:friends" # Same hash tag
# Both keys will be on same Redis shard
7. TTL Strategies
class SmartTTL:
@staticmethod
def dynamic_ttl(data_type, access_count=None, last_updated=None):
"""Calculate TTL based on data characteristics"""
base_ttls = {
'user_profile': 3600, # 1 hour
'product': 1800, # 30 minutes
'config': 86400, # 24 hours
'session': 1800, # 30 minutes
'api_response': 300, # 5 minutes
}
ttl = base_ttls.get(data_type, 300)
#Adjust based on popularity
if access_count and access_count > 1000:
ttl = min(ttl * 2, 86400) # Max 24 hours
return ttl
8. Consistency Trade-offs
Consistency Models:
| Pattern | Read Consistency | Write Consistency | Latency | Complexity |
|---|
| Cache-Aside | Eventually consistent | Eventually consistent | Low | Low |
| Write-Through | Strong (cache = DB) | Strong (sync write) | Medium | Medium |
| Write-Behind | Eventually consistent | Eventually consistent | Very Low | High |
| Refresh-Ahead | Strong (proactive) | Eventually consistent | High | High |
Practical Trade-off Configuration:
# cache-config.yaml
strategies:
user_profile:
pattern: "cache-aside"
ttl: 3600
invalidate_on_write: true
stale_ttl: 300 # Serve stale while updating
product_inventory:
pattern: "write-through"
ttl: 60 # Very short TTL
sync_writes: true
configuration:
pattern: "refresh-ahead"
ttl: 86400
refresh_threshold: 0.8 # Refresh at 80% of TTL
shopping_cart:
pattern: "write-behind"
ttl: 1800
batch_size: 100
flush_interval: 5 # seconds
9. Complete Example: E-commerce Caching Stack
# config/settings.py
CACHE_CONFIG = {
'cdn': {
'enabled': True,
'ttl_static': 31536000, # 1 year
'ttl_dynamic': 300, # 5 minutes
},
'reverse_proxy': {
'enabled': True,
'cache_path': '/var/cache/nginx',
'zone_size': '100m',
},
'application': {
'backend': 'redis',
'host': 'redis-cluster.example.com',
'port': 6379,
'max_connections': 50,
},
'database': {
'query_cache': False, # Disable MySQL query cache
'buffer_pool_size': '4GB', # PostgreSQL
}
}
# services/cache_service.py
class EcommerceCacheService:
def __init__(self):
self.redis = redis.RedisCluster(...)
self.logger = logging.getLogger(__name__)
def get_product(self, product_id, include_reviews=False):
"""Multi-level caching strategy"""
# 1. Check CDN (handled by nginx/cloudfront)
# 2. Check application cache
cache_key = f"product:{product_id}"
if include_reviews:
cache_key += ":with_reviews"
cached = self.redis.get(cache_key)
if cached:
self.logger.debug(f"Cache HIT: {cache_key}")
return json.loads(cached)
# 3. Cache miss - load from DB
product = self.db.load_product(product_id, include_reviews)
# 4. Write to cache with appropriate TTL
ttl = self._calculate_product_ttl(product)
self.redis.setex(cache_key, ttl, json.dumps(product))
return product
def _calculate_product_ttl(self, product):
"""Dynamic TTL based on product characteristics"""
base_ttl = 1800 # 30 minutes
# Popular products get longer TTL
if product['sales_count'] > 1000:
return base_ttl * 4
# New products get shorter TTL (frequent updates)
if (datetime.now() - product['created_at']).days < 7:
return base_ttl // 2
return base_ttl
def invalidate_product_cache(self, product_id):
"""Invalidate all product-related caches"""
pattern = f"product:{product_id}:*"
keys = self.redis.keys(pattern)
if keys:
self.redis.delete(*keys)
10. Monitoring & Metrics
# Example cache monitoring
class CacheMonitor:
def __init__(self, redis_client):
self.redis = redis_client
def get_metrics(self):
info = self.redis.info()
return {
'hit_rate': self._calculate_hit_rate(),
'memory_usage': info['used_memory_human'],
'keys_count': info['keyspace']['db0']['keys'],
'evictions': info['evicted_keys'],
'connected_clients': info['connected_clients'],
}
def _calculate_hit_rate(self):
stats = self.redis.info('stats')
hits = stats['keyspace_hits']
misses = stats['keyspace_misses']
total = hits + misses
return hits / total if total > 0 else 0
Key Takeaways:
- Layer caching: CDN → Reverse Proxy → App Cache → DB Cache
- Key design: Namespace + ID + context + version
- Invalidation is harder than caching: Prefer TTL where possible
- Consistency vs performance trade-off: Choose pattern based on business requirements
- Monitor everything: Hit rates, memory usage, evictions
- Cache warmup: Preload hot data after deployments
- Don't cache everything: Identify hot paths (Pareto principle)
Anti-Patterns to Avoid:
- Caching everything → Memory bloat, stale data
- No invalidation strategy → Stale data forever
- Cache stampede → Many requests miss cache simultaneously
- Key collisions → Poor key naming causing overwrites
- Caching personal/sensitive data → Security/privacy issues
Advanced Patterns:
# Cache stampede prevention with locking
def get_with_lock(key, ttl, fetch_func, lock_ttl=10):
value = redis.get(key)
if value:
return json.loads(value)
# Try acquire lock
lock_key = f"lock:{key}"
acquired = redis.set(lock_key, "1", nx=True, ex=lock_ttl)
if acquired:
try:
# Only this thread fetches
value = fetch_func()
redis.setex(key, ttl, json.dumps(value))
return value
finally:
redis.delete(lock_key)
else:
# Wait briefly and retry
time.sleep(0.1)
return get_with_lock(key, ttl, fetch_func, lock_ttl)
This comprehensive approach balances performance, consistency, and complexity based on your specific use case requirements.