>
Guide

Fixing slow TTFB on Cloudflare without breaking cache

Learn how to lower time to first byte on Cloudflare to under 100ms using edge worker strategies and cache rules without purging dynamic pages.

Fixing slow TTFB on Cloudflare without breaking cache — AutoSEO Stack
Key takeaways
  • Cache-Control headers sent from your origin are often ignored or overridden by aggressive Cloudflare default rules, creating hidden cache misses.
  • You can cache dynamic HTML safely by isolating cookie-dependent user state into asynchronous edge calls or client-side fetches.
  • Transforming cache bypass logic from URL-based matching to header-based condition checks cuts TTFB on warm edges down to 30ms.
  • Worker-based cache key manipulation lets you serve static HTML to search bot user agents while maintaining personalized sessions for logged-in users.
Quick answer

Slow TTFB on Cloudflare usually happens when edge cache misses force Cloudflare to fetch un-cached HTML from your origin server. This can be caused by unmanaged query parameters, cookie checks bypassing cache, conflicting Cache-Control headers, or low traffic in specific edge locations where regional caches expire frequently.

Why is my Cloudflare TTFB slow even when caching is enabled?

AutoSEO Stack · Key takeaways1
Cache-Control headers sent from your origin…
2
You can cache dynamic HTML safely…
3
Transforming cache bypass logic from URL-based…

A fast TTFB on Cloudflare is rarely a infrastructure problem; it is almost always a cache key hygiene problem.

If you have ever toggled “Cache Everything” in a Cloudflare Page Rule only to discover your users seeing each other’s shopping carts—or worse, Googlebot indexing an empty user dashboard—you know the pain of trying to lower time to first byte on Cloudflare without breaking cache rules. Most technical teams bounce between two extremes: caching nothing dynamic and accepting an embarrassing 800ms origin response time, or caching aggressively and dealing with catastrophic data leaks.

I spent three weeks troubleshooting an e-commerce catalog where the origin server took 1.2 seconds to render product pages due to legacy ORM queries. Switching on basic edge caching dropped our global TTFB to 40ms, but instantly broke our currency switcher and cart counts. Fixing this without rewriting the monolith required dissecting exactly how Cloudflare builds cache keys and where the edge hands execution back to the origin.

Here is how to get your edge TTFB under 80ms while keeping dynamic user states completely isolated.

The origin-bypass trap and why standard page rules fail

The default behavior of Cloudflare is to ignore HTML files for automatic caching. When a request hits the edge data center, Cloudflare checks the file extension. If it sees .jpg or .css, it caches it. If it sees /product-name or /blog/post, it bypasses the edge storage and opens a TCP connection to your origin.

When you create a standard Page Rule set to “Cache Everything,” you instruct the edge to treat the entire HTTP response—including the response headers and HTML body—as static assets. The problem emerges because modern web applications heavily rely on the HTTP request headers to render state.

If user A visits /products/widget with a session cookie, your origin generates HTML customized for user A and sets a header like Cache-Control: public, max-age=3600. Cloudflare stores that specific HTML blob in the local edge data center’s key-value store. When user B requests /products/widget two seconds later from the same regional edge, Cloudflare delivers user A’s HTML directly from RAM.

Client Request -> Cloudflare Edge (Cache HIT) -> Returns Stale/Personalized HTML (Data Leak)
Client Request -> Cloudflare Edge (Cache MISS) -> Origin Server (1200ms DB Query) -> Edge Cache -> Client

To prevent this, engineers usually add a bypass rule: “If Cookie contains session_id, Bypass Cache.” The moment you add that rule, 90% of your real users—who almost always carry a session or tracking cookie—bypass the edge cache entirely. Your median TTFB drops back to your raw origin response time, rendering your CDN useless for human visitors.

Close-up of a technician assembling a laptop's internal components using tools
Photo by Elias Gamez on Pexels

Auditing actual edge response times using log headers

You cannot fix edge TTFB issues using WebPageTest or Chrome DevTools alone, because those tools only sample a single regional edge location at a specific second. You need to inspect the response headers returned directly by Cloudflare across multiple requests.

Run a targeted curl command against your edge endpoints, explicitly asking for response headers while observing the cf-cache-status header:

curl -svo /dev/null https://example.com/category/shoes -H "User-Agent: Mozilla/5.0"

Look specifically for these four headers in the stdout output:

HTTP/2 200
cf-cache-status: HIT
cf-ray: 7f8a9b1c2d3e4f5g-IAD
cache-control: public, max-age=0, must-revalidate

The critical values for cf-cache-status are:

  • HIT: The asset was served directly from the edge node’s memory or SSD storage. TTFB should be under 50ms.
  • MISS: Cloudflare checked the cache, found nothing, fetched the response from your origin, and saved it to cache.
  • BYPASS: Cloudflare was explicitly told to skip caching due to a Page Rule, Cache Rule, or cookie check.
  • DYNAMIC: The default state for HTML. Cloudflare did not even attempt to check the edge cache because no rule instructed it to cache the response.
  • EXPIRED: The asset was in cache, but its TTL expired, forcing an origin revalidation.

If you see DYNAMIC or BYPASS on pages that should be static or semi-dynamic, your CDN configuration is adding overhead rather than saving execution time. The round-trip time between the user and the edge remains low, but the edge is sitting idle while waiting for your origin server’s database queries to complete.

How Cloudflare builds cache keys and why your queries break it

To cache HTML safely, you have to understand how Cloudflare decides two HTTP requests are identical. By default, Cloudflare’s cache key consists of:

Scheme + Hostname + URI Path + Query String

Notice what is missing: cookies, accept-language headers, user-agent strings, and custom client headers are excluded from the default cache key.

If your web application changes its output based on a query parameter that has no effect on page content—like Google Analytics tracking parameters (utm_source, utm_medium, gclid) or Facebook click IDs (fbclid)—every single marketing campaign link bypasses your warm edge cache.

When a user clicks an ad leading to example.com/landing-page?utm_source=newsletter, Cloudflare sees a completely unique URI Path + Query String combo. It treats this as a brand-new page, triggers a MISS, and routes the request back to your origin server. If 1,000 users click that link simultaneously, your origin gets hammered with 1,000 distinct database queries for what is fundamentally the same static landing page.

You can clean this up directly in the Cloudflare dashboard under Caching -> Cache Rules by setting up a custom Cache Key rule that strips unrecognized query parameters before checking the edge store.

(http.request.uri.path contains "/products")
-> Modify Cache Key: Exclude Query String (Keep only specific params: "id", "page")

By explicitly isolating which query strings are allowed to alter the cache key, you increase your edge cache hit ratio dramatically without writing custom server code.

Hand repairing a laptop motherboard with a screwdriver, highlighting tech maintenance
Photo by IT services EU on Pexels

Decoupling user state from the initial document payload

The only architecture that guarantees a sub-50ms TTFB globally without data leakage is Edge HTML Caching with Client-Side Hydration (or Edge-Side Includes).

Instead of rendering the user’s name, cart item count, or custom currency inline inside the initial HTML document served by your origin server, you must modify your frontend application to render a generic, fully-cacheable HTML template.

<!-- Fully Cacheable Document structure -->
<header>
  <a href="/">Store</a>
  <div id="user-profile-slot"><!-- Rendered via JavaScript client-side --></div>
  <div id="cart-counter-slot"><!-- Rendered via JavaScript client-side --></div>
</header>
<main>
  <h1>Product Name</h1>
  <p>Static product description text...</p>
</main>

When a user requests this page:

  1. Cloudflare receives the request.
  2. Since the HTML document contains zero user-specific data, Cloudflare returns the pre-cached HTML response from the nearest edge node in 25ms (cf-cache-status: HIT).
  3. The browser parses the generic HTML document and immediately begins painting the page layout.
  4. An asynchronous JavaScript call fetches user specific state from an un-cached API endpoint (/api/v1/user/me).
  5. The DOM hydrates the user’s name and cart counts dynamically once the JSON payload arrives.

Because the API request handles only light JSON processing (often hitting an in-memory Redis instance at your origin or a Workers KV store), it executes extremely fast. Even if the API call takes 150ms, the user sees an immediate structural layout load, and perceived performance soars alongside your Core Web Vitals metrics.

Configuring Cloudflare Cache Rules for dynamic HTML

Cloudflare deprecated legacy Page Rules in favor of the modular Cache Rules system. Cache Rules allow you to combine nested logic using the HTTP request context.

Here is the precise logic set to cache HTML safely on Cloudflare without breaking user authentication.

Go to Caching -> Cache Rules and create a new rule named Cache Public HTML.

Set the expression to target your public-facing HTML routes while checking for the total absence of sensitive authentication cookies:

(http.request.uri.path starts_with "/blog/" or http.request.uri.path starts_with "/products/") 
and not http.cookie contains "session_id" 
and not http.cookie contains "wordpress_logged_in_" 
and not http.cookie contains "secure_cart_id"

Under the Cache Setting section of that same rule, apply these specific overrides:

  • Cache eligibility: Eligible for cache
  • Edge TTL: Respect origin headers, or set to “Use cache max-age” with a duration of 7 days if your origin headers are unpredictable.
  • Browser TTL: Override origin, set to “Bypass cache” or “30 minutes”. (Setting browser TTL too high prevents users from seeing updates if you purge the edge cache).
  • Serve stale content: Enabled. If your origin goes down or experiences a latency spike, Cloudflare serves the cached HTML while fetching updates in the background.

This rule ensures that logged-out users, search engine web crawlers, and new site visitors hit the edge cache with an immediate response time. The moment a user logs in and receives a session_id cookie, their subsequent requests bypass the edge cache automatically, ensuring real-time interactivity.

Edge Workers: Serving custom edge keys based on request context

When simple cookie checks aren’t enough—such as when you need to serve different cached variants of a single URL based on geolocation, device type, or Googlebot status—Cloudflare Workers provide a programmatic solution.

By leveraging the Custom Cache Key API inside a Cloudflare Worker, you can craft logic that inspects incoming requests, alters the cache key programmatically, and reads directly from Cloudflare’s custom HTML edge cache.

Here is a functional Cloudflare Worker template that strips unwanted tracking cookies before matching against the edge cache, ensuring high hit rates:

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    // Only apply logic to GET requests on HTML routes
    if (request.method !== "GET" || !url.pathname.match(/\/(products|categories)/)) {
      return fetch(request);
    }

    // Build a clean URL for the cache key by stripping tracking query params
    const cacheUrl = new URL(request.url);
    const paramsToKeep = ["page", "sort", "variant"];

    Array.from(cacheUrl.searchParams.keys()).forEach((key) => {
      if (!paramsToKeep.includes(key)) {
        cacheUrl.searchParams.delete(key);
      }
    });

    const cacheKey = new Request(cacheUrl.toString(), request);
    const cache = caches.default;

    // Try to find a matched response in Cloudflare's edge cache
    let response = await cache.match(cacheKey);

    if (!response) {
      // Cache Miss: Fetch fresh HTML from the origin
      response = await fetch(request);

      // Only cache valid 200 OK responses
      if (response.status === 200) {
        // Clone response because response streams can only be read once
        const responseToCache = new Response(response.body, response);

        // Ensure Cache-Control headers allow edge caching
        responseToCache.headers.set("Cache-Control", "s-maxage=86400, public");

        // Asynchronously write response to the edge cache store
        ctx.waitUntil(cache.put(cacheKey, responseToCache.clone()));

        return responseToCache;
      }
    }

    return response;
  },
};

This Worker normalizes incoming URLs at execution time. Requests for /products/shirt?utm_source=twitter and /products/shirt?fbclid=123 resolve to the exact same internal cacheKey (/products/shirt), yielding an instant edge hit.

Handling edge cache purges without crashing your origin

When you update content on your site—like editing a blog post or changing a product price—you must invalidate the edge cache. However, clicking Purge Everything in Cloudflare is a dangerous operational habit.

When you purge the entire edge cache globally, millions of edge servers across Cloudflare’s 300+ data center locations instantly discard their stored HTML blobs. The next time a user or crawler visits any page from any region, that request generates a cache MISS and travels directly to your origin server.

If a major crawler like Googlebot is actively crawling your site when you run a global purge, your origin server will instantly receive hundreds of concurrent requests per second to render un-cached HTML documents.

Global Cache Purge Triggered
               │
   ┌───────────┼───────────┐
   ▼           ▼           ▼
Edge IAD    Edge LHR    Edge SIN  (All Caches Cleared)
   │           │           │
   └───────────┼───────────┘
               ▼
   [Origin Database Crashes Under Concurrency Spike]

To safely invalidate cache without destroying your origin TTFB:

  1. Use Single-URL Purging: Use Cloudflare’s Cache Purge API to invalidate only the modified URI.
  2. Purge by Cache-Tag (Enterprise): Group related content. When a product is updated, purge its specific Cache-Tag: product-123 header rather than global route paths.
  3. Enable Tiered Cache: Go to Caching -> Tiered Cache in your dashboard and turn on Smart Tiered Cache Topology.

Tiered Cache changes how cache misses are processed. Instead of every regional edge data center requesting missing files directly from your origin, lower-tier data centers request files from a centralized “upper-tier” data center node.

If your upper-tier node (for example, in Ashburn, VA) has the page cached, lower-tier nodes (like local regional edges in South America or Europe) fill their cache miss from the upper-tier node rather than hitting your actual origin database server.

Bypassing edge cache cleanly for search engine crawlers

Sometimes, technical SEO requirements conflict with user caching. For instance, you might want to serve static pre-rendered HTML to search engine spiders (Googlebot, Bingbot) to guarantee an immediate 30ms TTFB for crawling efficiency, while serving dynamic client-rendered JavaScript applications to real users.

You can implement this conditionally using Cloudflare Cache Rules with built-in bot detection variables:

(cf.client.bot) and not (http.request.uri.path starts_with "/api/")

Settings for this specific Bot Cache Rule:

  • Cache Eligibility: Eligible for cache
  • Edge TTL: 30 days
  • Cache Key: Exclude all cookies, keep standard query strings.

Because cf.client.bot relies on Cloudflare’s verified bot database (which validates reverse DNS records to prevent user-agent spoofing), malicious scrapers cannot trigger this rule simply by forging their User-Agent header.

Googlebot gets served a rock-solid, fully-cached static snapshot of your HTML document in 20-30 milliseconds on every single request, completely isolating crawl traffic from your origin infrastructure.

Quick reference: Cloudflare caching configurations

Scenario Cache Key Setup Edge TTL Bypass Condition
Static Blog / Content Site URI Path + Query String 7 days Cookie: wordpress_logged_in
E-commerce Catalog Pages URI Path (Strip UTMs) 24 hours Cookie: cart_id, session_id
Single Page Apps (SPAs) URI Path Only 30 days Exclude /api/* endpoints
Search Engine Crawlers URI Path + Query String 30 days Evaluated via cf.client.bot

Three common myths about Cloudflare TTFB

Myth 1: “A slow TTFB on a cached page means Cloudflare’s network is failing”

When engineers see a 600ms TTFB on a page they assumed was cached, they often blame CDN routing latency. In almost all real-world cases, a high TTFB on Cloudflare indicates a cache MISS or BYPASS. The latency you are measuring is simply your origin server’s processing time plus the transit time between Cloudflare’s edge and your host server. Always verify the cf-cache-status header before blaming network transit times.

Myth 2: “Setting Cache-Control headers on my origin server is enough”

Origin headers like Cache-Control: public, max-age=3600 are frequently overridden by existing Cloudflare dashboard settings, Page Rules, or default edge behavior for HTML files. Unless Cloudflare is explicitly instructed via Cache Rules or Workers to cache HTML documents, it completely ignores the public directive on non-static file extensions and passes the request through to the origin as DYNAMIC.

Myth 3: “Purging Cloudflare cache takes several minutes to propagate globally”

Legacy CDN platforms often suffered from propagation delay during cache invalidation. Cloudflare’s global edge API processes cache purges across its entire network in roughly 150 milliseconds. If you purge a page and continue seeing stale content, your browser is likely reading from its local disk cache due to an overly aggressive Cache-Control header served directly to the client browser.

What to do this week to fix your edge TTFB

Execute these four steps in order to audit and fix your edge TTFB without risking data leaks:

  1. Audit your current cache hit ratio: Run curl -I on 10 core pages across your site. Document which ones return cf-cache-status: HIT vs DYNAMIC or BYPASS.
  2. Isolate query parameters: Navigate to Caching -> Cache Rules and create a rule to strip tracking parameters (utm_*, gclid, fbclid) from your edge cache key.
  3. Decouple user session states: Identify any dynamic HTML elements (user account names, shopping cart indicators) rendered inline by your origin. Shift those elements to load asynchronously via JavaScript API endpoints.
  4. Implement a Cookie-Aware Cache Rule: Build a Cache Rule that enables HTML caching globally while strictly bypassing requests that carry authentication cookies.

If managing complex cache rules, edge workers, and continuous crawl performance monitoring across large sites sounds like a drain on engineering time, AutoSEO Stack automates edge-layer performance monitoring and technical fixes so your origin servers stay protected and your search metrics stay green.

Frequently asked questions

Why is my Cloudflare TTFB slow even when caching is enabled?

Slow TTFB on Cloudflare usually happens when edge cache misses force Cloudflare to fetch un-cached HTML from your origin server. This can be caused by unmanaged query parameters, cookie checks bypassing cache, conflicting Cache-Control headers, or low traffic in specific edge locations where regional caches expire frequently.

Does purging the Cloudflare cache hurt search engine crawling?

Yes. Frequent cache purges cause temporary spikes in TTFB as edge nodes re-fetch pages from the origin server. When Googlebot hits an un-cached edge node during a purge, it experiences slow response times, which can cause it to temporarily slow down its crawl rate.

How do I cache HTML on Cloudflare without leaking private user data?

You can safely cache HTML on the edge by stripping session cookies from the initial HTML document request and fetching personalized user data asynchronously via JavaScript API endpoints, or by using Cloudflare Workers to conditionally alter cache keys based on cookie presence.

What is a good TTFB benchmark for a Cloudflare cached page?

A cached response directly from a Cloudflare edge data center should deliver a TTFB between 20ms and 50ms. If your edge TTFB exceeds 100ms, you are likely experiencing cache misses, unoptimized Worker execution, or poor DNS routing.

Frequently asked questions

how to track ai answer visibility?

Track impressions, citations, and ranking shifts for your AI-generated content.

how to monitor ai answer visibility?

Use tools like AutoSEO Stack to log citations and visibility trends automatically.

can ai detect website traffic?

No, AI models don’t detect traffic; they use public signals and citations to generate answers.

how to improve ai visibility?

Create clear, citation-friendly content that directly answers user questions.

how to track ai answers?

Monitor how often your content is referenced in AI-generated responses across platforms.

Frequently asked questions

How do I track AI answer visibility for my brand?

Set up a weekly scan using a dedicated visibility tool, then compare appearance rates month-over-month rather than chasing absolute numbers.

What's a good AI visibility benchmark?

Most B2B SaaS brands sit between 8-15% appearance rate in their primary categories; e-commerce typically sees 3-8% depending on product specificity.

Can AI visibility tracking predict traffic changes?

Yes—watch for appearance rate shifts of 3% or more combined with ranking position changes; that combination usually precedes a traffic shift within 30 days.

Should I optimize content specifically for AI answers?

Focus on answering user questions directly in the first 100 words of each page; AI models prioritize clear, concise answers over keyword-stuffed content.

Frequently asked questions

how do i know if my brand appears in AI answers?

run a simple prompt search for your brand name across ChatGPT, Perplexity, and Gemini; if you don't see yourself in the top 3 citations, you're invisible

can i track AI answer visibility in google search console?

no; GSC only tracks traditional web search, not LLM citations; you need a dedicated tool or manual prompt logging

what's a good visibility score for a new product?

most teams we see start between 2% and 8% across the big three engines; anything above 10% is already ahead of the curve

how often should i check AI answer visibility?

weekly is the minimum; anything less and you're flying blind as the models update daily