CDN Operations • Beginner

CDN Configuration Best Practices: 15 Rules for Production Deployments

Sarah Mitchell — Edge Computing Engineer
• 12 min read • Updated Sep 6, 2026
CDN configurationProductionEdge

AEO Answer: What are CDN configuration best practices? Configure precise cache hierarchies, enforce HTTPS with strict origin TLS, normalize cache keys, enable tiered caching and compression, and automate purges with surrogate keys to achieve 90%+ hit ratios, lower origin load, and resilient production deployments.

Why Production CDN Configuration Matters

A production CDN is not just a caching layer; it is your global application front door handling TLS termination, request routing, and failure isolation. A single misconfigured cache rule can amplify origin traffic by 10x during a traffic spike.

Performance Comparison: Edge vs Origin Processing
Metric Edge Processing Origin Processing Improvement
Latency (p50)8–15 ms120–300 ms15–20x faster
Cache Hit Ratio85–95%N/AReduces origin load
TLS Handshake1–5 ms (nearby PoP)50–150 ms10–30x faster
Bandwidth Cost$0.01–0.04/GB$0.05–0.12/GB3–5x cheaper
Availability99.99% (multi-PoP)99.9% (single DC)10x fewer outages

Correct configuration directly impacts Core Web Vitals, origin cost, and resilience. Understanding how a CDN works helps you see why edge decisions—like cache key design and stale serving—determine whether your site stays fast under load or collapses.

Beginners often treat CDN setup as “enable and forget,” but production requires explicit policies for every content class. Static assets, HTML documents, API responses, and personalized pages each need distinct TTLs, headers, and purge strategies.

Production traffic is unpredictable, so you must design for failure modes like origin outages, cache stampedes, and poisoned cache keys. A resilient configuration serves stale content gracefully instead of returning 5xx errors to users.

This guide distills 15 field-tested rules I use when onboarding high-traffic sites to CDNs. Each rule is self-contained, actionable, and includes real configuration snippets you can adapt for Cloudflare, Fastly, Akamai, or AWS CloudFront.

The 15 Rules for Production-Ready CDN Configuration

Rule 1: Define a Cache Hierarchy with Explicit TTLs per Content Class

Never use a single global TTL for your entire site, because different content types have different freshness requirements. Map every path pattern to a content class—immutable assets, versioned media, HTML, API, and personalized content—with its own TTL.

Immutable assets fingerprinted with hashes (e.g., app.a3f1c9.js) should be cached for one year with immutable. HTML documents should have short TTLs (0–60 seconds) combined with stale-while-revalidate to keep them fresh without blocking users.

Use origin headers as the source of truth and let the CDN respect them, rather than overriding everything at the edge. This approach keeps your application logic portable across CDN vendors and avoids hidden edge overrides.

# Origin response headers — Nginx example for content classes
location ~* \.(js|css|woff2|png|webp)$ {
  add_header Cache-Control "public, max-age=31536000, immutable";
  add_header CDN-Cache-Control "public, max-age=31536000";
}
location = /index.html {
  add_header Cache-Control "public, max-age=0, s-maxage=60, stale-while-revalidate=600, stale-if-error=86400";
}
location /api/ {
  add_header Cache-Control "private, no-store";
  add_header CDN-Cache-Control "no-store";
}

Rule 2: Enable Origin Shield and Tiered Caching

Origin Shield (or tiered caching) designates a single mid-tier PoP to collapse all global misses into one origin request. Without it, a cache purge can trigger hundreds of simultaneous origin fetches from every edge location.

Enabling shielding typically improves shield hit ratio to 95%+ and reduces origin egress costs by 60–80%. For AWS CloudFront, this is Origin Shield; for Fastly, it is Shielding; for Cloudflare, it is Tiered Cache with Smart Tiered Caching.

Always place your shield region closest to your origin. If your origin is in us-east-1, shield in IAD or CMH. For multi-origin setups, use separate shields per origin to avoid cross-region latency.

Rule 3: Normalize Cache Keys Ruthlessly

Cache keys determine hit ratio more than any other setting. A single extra query parameter or header variant can fragment your cache into thousands of low-hit entries.

Strip irrelevant query strings (like utm_source, fbclid), normalize case, sort parameters, and exclude cookies from the cache key unless content truly varies by cookie. For most sites, the key should be host + path + normalized query + Accept-Encoding only.

Be explicit about Vary handling. If you vary on Accept-Encoding and Accept-Language, you double or triple variants. Prefer content negotiation at the edge (e.g., serving WebP/AVIF via image optimization) rather than varying HTML by language at the cache layer.

// Cloudflare Cache Rule — normalize cache key (example)
if (http.request.uri.query contains "utm_") {
  remove_query_param("utm_source", "utm_medium", "utm_campaign", "fbclid", "gclid");
}
cache_key = concat(http.host, lower(http.request.uri.path), sorted_querystring());
// Only include cookie for /account/*
if (!starts_with(http.request.uri.path, "/account")) {
  exclude_from_cache_key(http.cookie);
}

Rule 4: Enforce Strict TLS End-to-End

Terminate TLS at the edge with a managed certificate and re-encrypt to origin using Full (Strict) mode. Many outages stem from “Flexible” TLS where edge-to-origin traffic is plain HTTP and gets intercepted or blocked.

Enable TLS 1.2 as minimum, prefer TLS 1.3, and enable HSTS with preload. Automate certificate renewal via the CDN or ACM, and monitor expiration with alerts 30 days in advance. For deeper protocol benefits, see our guide to HTTP/2, HTTP/3 and QUIC at the edge.

Use OCSP stapling and require SNI. If you handle sensitive data, consider mutual TLS (mTLS) between edge and origin to ensure only your CDN can fetch from origin, combined with origin firewall allowlisting of CDN IP ranges.

Rule 5: Use Versioned URLs, Not Short TTLs, for Deployments

Deploying new assets by purging the entire cache is risky and slow. Instead, fingerprint filenames with content hashes and use immutable caching, so new deploys get new URLs and old URLs remain cached safely.

This pattern eliminates purge-related stampedes and lets you roll back instantly by reverting HTML references. Your CI should generate main.8f3a1b.css and upload with long TTLs, while HTML points to the new hash.

If you must purge, use surrogate keys (cache tags). Tag all assets of a release with release-2026-09-06 and purge by tag, not by URL wildcard. Wildcard purges are eventually consistent and can take minutes to propagate globally.

Rule 6: Implement Stale-While-Revalidate and Stale-If-Error

Stale serving is the most underrated resilience feature. stale-while-revalidate lets the edge serve a slightly stale response instantly while fetching a fresh copy in the background, cutting tail latency.

stale-if-error keeps your site online when origin returns 5xx. Set it to 86400 seconds (24h) for HTML and longer for assets. Users see slightly stale content instead of an error page during origin deployments or outages.

Pair stale directives with background revalidation limits to avoid overwhelming origin. Most CDNs allow you to configure “serve stale if origin error” as an edge behavior independent of origin headers—enable it explicitly.

# Ideal Cache-Control for HTML with resilience
Cache-Control: public, max-age=0, s-maxage=30, stale-while-revalidate=300, stale-if-error=86400
CDN-Cache-Control: public, max-age=60, stale-while-revalidate=600
Surrogate-Key: page-home release-2026-09-06

Rule 7: Compress Everything Correctly (Brotli + Gzip)

Enable Brotli (level 4–6) at the edge for text assets and keep Gzip as fallback. Brotli saves 15–20% over Gzip for JS/CSS and directly improves Largest Contentful Paint.

Do not double-compress at origin and edge. Let origin serve uncompressed or pre-compress with Content-Encoding correctly set, and configure the CDN to compress on-the-fly with proper Vary: Accept-Encoding handling. For image-heavy sites, enable automatic WebP/AVIF conversion at the edge.

Set minimum compressible size to ~1KB and exclude already-compressed formats (images, video, WOFF2). Monitor compression ratio in CDN analytics to catch misconfigured MIME types that skip compression.

Rule 8: Configure Negative Caching and Error Caching Carefully

Cache 404s and 500s for short periods to protect origin from crawlers and retry storms. Without negative caching, a broken link can generate thousands of origin hits per minute.

Cache 404s for 10–60 seconds and 500s for 1–5 seconds, with jitter. Never cache 5xx for longer than 10 seconds, or you will prolong outages. Use Cache-Control: no-store for authenticated error pages that contain user-specific data.

For APIs, return Cache-Control: no-store on errors and implement retry-after headers. At the edge, configure custom error pages that are cached separately from origin errors to avoid caching personalized error content.

Rule 9: Lock Down Origin Access

Your origin should not be directly reachable from the internet. Allow only CDN IP ranges and require a shared secret header or mTLS certificate for origin fetches.

On AWS, use Origin Access Control (OAC) for S3 or security groups that allow only CloudFront/Cloudflare IPs. On Nginx, validate a header like X-Origin-Verify that the CDN injects and origin checks. Rotate secrets via your infrastructure-as-code pipeline.

# Nginx — only allow CDN shield to fetch origin
server {
  if ($http_x_origin_verify != "s3cr3t-shield-token-2026") { return 403; }
  # Also restrict by CDN IP ranges via allow/deny or AWS WAF
  allow 130.176.0.0/16; # Example CDN range
  deny all;
}

Rule 10: Tune HTTP/2 and HTTP/3 (QUIC) at the Edge

Enable HTTP/2 and HTTP/3 at the edge for better multiplexing and loss resilience, especially for mobile users. HTTP/3 over QUIC reduces connection migration failures when users switch from Wi-Fi to cellular.

Keep origin fetches on HTTP/1.1 or HTTP/2 depending on origin support; most origins do not yet need QUIC to shield. Test with curl --http3 and monitor protocol distribution. If you serve global audiences, HTTP/3 can cut 0–RTT connection time by 30% on high-loss networks. Learn more in our HTTP/2 vs HTTP/3 deep dive.

Enable 0-RTT cautiously—only for idempotent GET requests—and disable it for POST/PUT to avoid replay risks. Pair with proper TLS session resumption settings.

Rule 11: Set Up WAF, Rate Limiting, and Bot Management Before Launch

Do not launch production without a WAF in log-or-block mode. Start with OWASP Core Rule Set, then tune for false positives on your application paths. Block obvious attacks (SQLi, XSS, path traversal) at the edge before they reach origin.

Add rate limiting per IP and per ASN for login, search, and API endpoints. Use token bucket rules like 60 requests/minute for /api/login and challenge (JS challenge or CAPTCHA) on exceed, not hard block, to avoid blocking NAT users.

For e-commerce, bot protection is critical during launches and sales. See CDN strategies for e-commerce for cart and checkout-specific rules that preserve conversion while blocking scalper bots.

Rule 12: Automate Configuration as Code and Preview Changes

Treat CDN configuration like application code: version it in Git, review via pull requests, and deploy via Terraform, Pulumi, or vendor APIs. Manual dashboard changes cause drift and unrepeatable outages.

Use Terraform for CloudFront, Fastly, and Cloudflare, and run terraform plan in CI to preview diffs. Require two reviewers for cache rule changes, and maintain separate staging and production distributions with identical rules.

# Terraform — CloudFront cache behavior example
resource "aws_cloudfront_distribution" "prod" {
  origin {
    domain_name = "origin.example.com"
    origin_id   = "primary"
    custom_origin_config {
      origin_protocol_policy = "https-only"
      origin_ssl_protocols   = ["TLSv1.2"]
    }
  }
  default_cache_behavior {
    compress               = true
    viewer_protocol_policy = "redirect-to-https"
    cache_policy_id        = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad" # CachingOptimized
    origin_request_policy_id = "88a5eaf4-2fd4-4709-b370-b4c650ea3fcf" # CORS-S3Origin
  }
}

Rule 13: Observe the Right Metrics and Alert on Them

Instrument cache hit ratio, origin latency, edge error rate (4xx/5xx), and bytes saved. A drop in hit ratio from 92% to 85% often signals a bad deploy or cache key regression before users notice.

Export CDN logs to your observability stack (Datadog, Grafana, CloudWatch) and create SLOs: 95th percentile edge TTFB < 100ms, origin offload > 85%, and 5xx < 0.1%. Alert on shield miss spikes and origin concurrency, not just edge status codes.

Correlate CDN metrics with Core Web Vitals—LCP and INP improve directly with higher hit ratios and proper compression. Use Real User Monitoring (RUM) to validate that edge improvements translate to user experience gains.

Rule 14: Plan Purge Strategy and Test Failure Modes

Define a purge runbook: who can purge, what keys to purge, and how to verify propagation. Prefer soft purges (revalidate in background) over hard purges (immediate eviction) to avoid thundering herds.

Test origin failure by simulating 5xx or disconnecting origin in staging and verifying that stale-if-error serves stale content. Test cache poisoning by sending malformed headers and ensuring the CDN strips or ignores them rather than caching poisoned responses.

Document TTL overrides for emergencies. During an incident, you may need to temporarily bypass cache for a path pattern—ensure you have a tested “bypass” rule that can be enabled via feature flag without a full deploy.

Rule 15: Document and Review Quarterly

Maintain a living CDN runbook that maps every path pattern to its cache policy, WAF rule, and owner. Include diagrams, header examples, and purge procedures so on-call engineers can act without guessing.

Schedule quarterly reviews to audit unused rules, expired certificates, and overly broad cache bypasses. New features often add Cache-Control: no-store headers that accidentally disable caching for entire sections of the site.

Share knowledge across teams by linking your runbook to foundational resources like the CDN fundamentals guide and edge computing guide so new engineers understand why each rule exists, not just what it does.

Cache Strategy Comparison for Production

Choosing the right cache strategy depends on how often content changes and how sensitive it is to staleness. The table below summarizes production-tested patterns for common content classes.

Use this as a starting point and adjust TTLs based on your deployment frequency and tolerance for stale content. All strategies assume Origin Shield is enabled and stale-if-error is configured globally.

Content Class Example Path Recommended Cache-Control Edge TTL Purge Method
Immutable Assets /assets/app.a1b2c3.js public, max-age=31536000, immutable 1 year Never purge (new URL per deploy)
Versioned Images /images/hero-*.webp public, max-age=86400, stale-while-revalidate=3600 24h Surrogate key: img-hero
HTML Documents /, /blog/* public, s-maxage=60, stale-while-revalidate=600, stale-if-error=86400 60s Tag: page-* soft purge
API (Public) /api/products public, s-maxage=30, stale-while-revalidate=30 30s Key: api-products
API (Private) /api/me, /cart private, no-store No cache Bypass cache entirely
Error Responses 404 / 500 public, max-age=10 (404) / max-age=2 (500) 10s / 2s Short negative cache

Notice how HTML uses short s-maxage with long stale windows, while immutable assets use a full year. This combination maximizes hit ratio without sacrificing freshness for frequently updated pages.

Pro Tip: Start strict, then relax. Begin with shorter TTLs and conservative stale windows, measure hit ratio and origin load for a week, then gradually extend TTLs. It is far safer to increase caching than to recover from over-caching personalized content.

Automation, Testing & Observability Checklist

Production CDN configuration is never “done.” Treat it as a continuous loop of codify, test, measure, and refine. Automate validation so that every pull request checks cache headers and purge logic.

Add header assertions to your CI pipeline: fetch staging URLs and assert that Cache-Control, CDN-Cache-Control, and Surrogate-Key match expectations. Fail the build if HTML is accidentally marked immutable or if an API leaks public caching.

Run synthetic tests from multiple geographies using tools like WebPageTest or Catchpoint to verify TTFB and hit ratio. A single-region test can hide cache fragmentation caused by regional query parameter variations.

Finally, keep your configuration portable. Even if you are locked to one vendor today, using standard headers (Cache-Control, Surrogate-Key, Vary) and versioned URLs makes future migrations far less painful and keeps your architecture aligned with open web standards.

FAQ: Production CDN Setup

What is the most important CDN configuration for production?

The most critical setting is a correct Cache-Control and CDN-Cache-Control hierarchy. Set long TTLs for immutable assets (1 year), short TTLs for HTML (0–60s with stale-while-revalidate), and always use origin cache headers as the source of truth. This single rule prevents origin overload and ensures consistent performance.

Should I use CDN managed TLS or bring my own certificate?

For most production sites, use the CDN's managed TLS with automatic renewal and enable strict origin TLS validation (Full Strict). Bring your own certificate only if you need Extended Validation, custom private CA, or mutual TLS. Always enforce TLS 1.2+ and HSTS at the edge.

How do I safely purge CDN cache in production?

Use surrogate keys (cache tags) or versioned URLs instead of wildcard purges. Tag assets by content type or release ID, then purge by key on deploy. Combine with soft purges and stale-while-revalidate to avoid thundering herds. Test purge propagation in staging first.

What cache hit ratio should I target?

Aim for 90–95% edge hit ratio for static sites and 80–90% for dynamic or e-commerce workloads. If you are below 85% on static assets, review cache-key normalization, query string handling, and TTLs. Use tiered caching and origin shield to improve shield hit ratio to 95%+.

How often should I review CDN configuration?

Review configuration on every major release and at least quarterly. Audit cache rules, WAF, rate limiting, compression, and HTTP/3 settings. Use infrastructure-as-code and diff checks in CI to catch drift, and monitor cache hit ratio, origin load, and edge errors continuously.

References & Standards: Cloudflare documentation · OWASP CDN Security