CDN Cache Miss / Stale Content Fix
In this tutorial, you'll learn about CDN Cache Miss / Stale Content Fix. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Content Delivery Networks (CDNs) cache content at edge locations to reduce latency. When users receive stale content or the CDN misses the cache frequently, the cause is usually misconfigured cache headers, incorrect purge commands, or missing origin cache directives.
The Wrong Way
from flask import Flask, make_response
app = Flask(__name__)
@app.route("/api/data")
def get_data():
response = make_response({"value": "old_data"})
# Missing cache headers
return response
Output:
# Browser and CDN do not cache the response
# Every request hits the origin server
# Cache hit ratio: 0%
The Right Way
Set proper cache headers to control CDN behavior:
from flask import Flask, make_response, jsonify
from datetime import datetime, timedelta
app = Flask(__name__)
@app.route("/api/data")
def get_data():
response = jsonify({"value": "fresh_data"})
# CDN caching
response.headers["Cache-Control"] = "public, max-age=3600"
response.headers["CDN-Cache-Control"] = "public, max-age=7200"
# Browser caching
response.headers["Expires"] = (datetime.utcnow() + timedelta(hours=1)).strftime(
"%a, %d %b %Y %H:%M:%S GMT"
)
return response
Step-by-Step Fix
1. Check current cache headers
curl -I https://cdn.example.com/style.css
# Look for:
# Cache-Control: public, max-age=3600
# Age: 1234 (how long it's been cached)
# X-Cache: HIT or MISS
2. Set proper Cache-Control headers
# Nginx origin server
location /static/ {
root /var/www;
expires 30d;
add_header Cache-Control "public, immutable";
}
3. Purge the CDN cache
# Cloudflare
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache" \
-H "Authorization: Bearer TOKEN" \
-H "Content-Type: application/json" \
-d '{"files":["https://example.com/style.css"]}'
# Fastly
curl -X POST "https://api.fastly.com/service/SERVICE_ID/purge/style.css" \
-H "Fastly-Key: API_KEY"
4. Use cache-busting URL patterns
<!-- Versioned file names -->
<link rel="stylesheet" href="/style.v2.css">
<!-- Hash-based URLs -->
<link rel="stylesheet" href="/style.a1b2c3.css">
5. Configure origin cache rules
# Cloudflare Page Rules
example.com/wp-admin/* -> Cache Level: Bypass
example.com/*.css -> Cache Level: Standard, Edge TTL: 1 month
6. Monitor cache hit ratio
import requests
resp = requests.get("https://cdn.example.com/style.css")
cache_status = resp.headers.get("CF-Cache-Status", "MISS")
print(f"Cache status: {cache_status}")
# HIT = served from CDN cache
# MISS = fetched from origin
# DYNAMIC = not cached
Prevention Tips
- Set explicit
Cache-Controlheaders on all cacheable responses. - Use cache-busting techniques (versioned filenames, hashes) for static assets.
- Purge only specific files instead of clearing the entire cache.
- Monitor
X-Cacheheaders to verify CDN Caching behavior. - Set appropriate
Edge TTLvalues in your CDN configuration.
Common Mistakes with cache miss
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world CDN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro