Two teams look at the same slow page and reach opposite conclusions. One blames the CDN (“the edge is far away, the cache isn’t hitting”). The other blames the origin (“the database is slow, PHP takes 800ms”). Both are often right in isolation and wrong about priority, because they’re optimizing whichever layer they happen to understand best.

The honest answer is that “CDN vs. origin” is the wrong framing. Latency is cumulative, and the layer you should fix first is determined by where in the request lifecycle the time is being lost — not by which layer sounds more modern. This post is a checklist for locating that loss, with fixes and verification steps at each stage.


First: understand what the CDN can and cannot fix

Before touching anything, establish the mental model. A CDN reduces latency by placing a cache closer to the user and terminating the TLS handshake near them. It cannot make a slow origin fast. If a request misses the cache, the CDN still has to reach back to your origin — and that origin response time is added on top of the edge-to-user time.

That gives you a rough decomposition of Time to First Byte (TTFB):

TTFB ≈ (edge→user RTT) + (cache lookup) + [on miss: (edge→origin RTT) + origin processing time]

The bracketed portion only exists on a cache miss. This single fact is the crux of the whole decision: if your cache hit ratio is high, origin latency barely matters for most requests. If it’s low, the CDN is mostly acting as a proxy and every miss pays the full round trip to your origin.


Checklist: symptom → cause → fix

Work through these in order. The first symptom that matches your data tells you which layer wins the optimization priority.

Symptom 1: TTFB is fast for some users, terrible for others in the same region

Cause: Cache hit ratio is inconsistent, typically because your cache keys include something user-specific (cookies, query strings, auth headers) or your TTLs are so short that objects expire constantly.

Verify: Pull cache stats from your CDN. On Cloudflare that’s Caching → Overview; on Fastly it’s the hit_ratio in real-time analytics; on CloudFront check Cache Statistics for HitRate. Look at it per content type, not as a single number. A global 85% hit rate can hide a 20% hit rate on your HTML pages while images sit at 99%.

Fix: Make HTML cacheable. A common pattern is a short-TTL edge cache with a stale-while-revalidate fallback:

# Example: cache HTML at the edge for 60s, serve stale up to 24h
# while revalidating in the background
location / {
    add_header Cache-Control "public, max-age=60, stale-while-revalidate=86400";
    # Bypass the edge cache entirely for authenticated users
    if ($http_cookie ~* "session_id") {
        add_header Cache-Control "private, no-store";
    }
    proxy_pass http://origin_backend;
}

The stale-while-revalidate directive is the key lever here: it lets the edge serve a slightly stale copy instantly while it refreshes in the background, so users almost never wait on origin revalidation. The trade-off is that content can be up to 60 seconds stale — fine for marketing pages, wrong for a checkout confirmation or a stock price. If stale data is unacceptable, don’t use swr; instead lower your origin response time (Symptom 3).

Symptom 2: Hit ratio looks healthy, but your Cache-Status header shows misses on the exact pages that matter

Cause: Cookie-based session handling, personalized headers, or a query-parameter-cleanup gap. Many frameworks append tracking parameters (?utm_source=...) that fragment your cache into thousands of unique keys.

Verify: Request the page and inspect the response headers. Look for Cache-Status (RFC 9211), X-Cache, CF-Cache-Status, or X-Cache-Status depending on your provider. A Cache-Status: miss; fwd=uri-miss on a URL that should be cached points at key fragmentation.

Fix: Normalize cache keys. Strip tracking parameters at the edge before the cache lookup (Cloudflare Cache Rules, Fastly Vary, or an nginx map):

# nginx: strip utm_* params from the cache key without touching the upstream
map $args $normalized_args {
    default        $args;
    ~^(.*)(&?utm_[^&]+)  $1;   # rough example only; test against your param set
}

proxy_cache_key "$scheme$request_method$host$normalized_args";

When NOT to do this: Never strip parameters that change the response body (pagination ?page=, search ?q=, filters). Blindly normalizing the cache key is one of the most common ways teams accidentally serve the wrong page to the wrong user.

Symptom 3: Cache misses are slow and the origin is the bottleneck (everyone waits the same amount)

Cause: Origin response time is high — slow database queries, cold PHP workers, missing indexes, or serial work done at request time. When the cache does miss, users pay the full origin cost.

Verify: Measure origin response time independent of the CDN. Hit your origin directly (via its IP or a hostname that bypasses the CDN) or read origin timing from your CDN’s logs. On Fastly, the Origin timing breakdown in vcl-level logs or the origin.response.time-style fields isolates it. Compare p50 vs p95 vs p99 — a high p95 while p50 is fine points at request-level variance (cache stampedes, slow queries for specific content), not steady slowness.

Fix: Two angles. First, reduce the cost of a miss with a request-collapsing lock so a burst of identical misses doesn’t hit your database simultaneously:

# nginx: collapse concurrent requests for the same cache key
# only the first request goes to origin; the rest wait for its result
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
proxy_cache_lock_age 5s;

Second, reduce origin work on the miss path itself. Profile the actual handler — an ORM query without an index, a synchronous third-party call, or an N+1 loop dwarf any CDN tuning. This is the case where origin wins the priority. Edge caching can’t help you here; it only raises the hit ratio, which doesn’t fix the misses that remain.

Symptom 4: Time is spent before any byte arrives — TLS and DNS dominate

Cause: The CDN is not terminating TLS close to the user, or DNS resolution is slow (missing EDNS Client Subnet, many CNAME hops, short TTLs causing constant re-resolution).

Verify: In browser DevTools, open a request and read the Timing tab. “DNS Lookup” and “Initial connection” (TLS) segments tell you directly. A DNS lookup over ~40ms or a TLS handshake over ~100ms on a repeat visit points at the connection layer.

Fix: Ensure your origin has TLS 1.3 enabled and that the CDN terminates TLS at the edge (most do by default). Reduce CNAME chain depth. Enable HTTP/3 on the CDN if offered — it cuts a round trip from the handshake and helps on mobile networks in particular. These are edge-layer wins, and they’re often the cheapest latency you can reclaim, because they apply to every first request regardless of cache status.

Symptom 5: Everything is “fast” in isolation but the page is still slow

Cause: Latency is not the bottleneck — the CDN and origin are both fine, but you’re shipping too many requests, too much JS, or blocking resources. TTFB is only one input to Largest Contentful Paint (LCP).

Verify: Check LCP and Total Blocking Time in Chrome DevTools Performance or PageSpeed Insights. If server response time is a small slice of LCP, stop optimizing the network and look at render path and resource weight.

Fix: This isn’t a CDN-vs-origin question at all. It’s a front-end concern. Chasing origin milliseconds when your LCP is dominated by a hero image and a blocking font is wasted effort.


Decision summary

ObservationLikely culpable layerFirst fix
Inconsistent latency for users in the same regionCDN (cache keys / TTLs)Normalize cache keys, add stale-while-revalidate
Healthy global hit ratio but misses on key pagesCDN (key fragmentation)Strip tracking params; audit Cache-Status
Misses are uniformly slow, p95 badly worse than p50OriginAdd cache lock, profile the miss path (queries, indexes)
Slow DNS / TLS before first byteCDN / connection layerTLS 1.3 at edge, shorten CNAME chain, enable HTTP/3
Page slow but TTFB is a small share of LCPNeither (front end)Trim JS, fix render-blocking resources

A concrete implementation path, end to end

Pick one URL that users complain about and walk it:

  1. Setup: Note its cache headers and confirm what the CDN returns today.
  2. Change: Apply a targeted cache rule for that URL class (a Cache-Control header plus parameter normalization), scoped so it can’t affect dynamic endpoints.
  3. Verify: Hit the URL twice — once cold and once warm — and read Cache-Status / X-Cache on both. Compare origin timing on the miss against your previous baseline using CDN logs, not gut feel.

If the warm response still shows a miss, your change didn’t apply (wrong scope, a cookie override, or a rule ordering issue). That verification step is where most “we optimized the CDN” projects silently fail.

Related guides: Mastering Script Loading: A Deep Dive into Async vs. Defer for Peak Performance, HTTP/3 Isn’t Just Faster, It’s Smarter: Debunking Myths About the Web’s Next Evolution, and Caching Strategies for Beginners: A Step-by-Step Guide to Faster Page Loads.