How to Test Time to First Byte for CDN Cache Hits and Misses
Testing time to first byte for CDN cache hits and misses requires establishing two things at once: the actual cache status of each request, and where the time before the first byte was spent. Start with a GET resource that requires no login, has stable content, and permits shared caching. Keep the URL, request headers, and network egress consistent, and record both cache evidence and curl timings rather than interpreting “the first request was slow and the second was fast” as proof that caching worked.
This experiment primarily covers the client-to-CDN connection, edge-cache processing, upper-tier cache or origin-fetch paths, and origin processing where necessary. New versus reused connections, IPv4 versus IPv6, and an edge miss versus a request that actually reaches the origin can all change the results. If the difference between HIT and MISS mainly occurs during DNS or TLS, address connectivity and measurement consistency first. Further analysis of caching and origin-fetch benefits is appropriate only when the difference consistently appears in the waiting phase after the request is sent.
Define the Measurement: Time to First Byte Is Not Origin Processing Time
Retain Both Full TTFB and the Wait After Request Preparation
curl's time_starttransfer is the cumulative time from the start of the operation until the first response byte is received. For a simple GET request over a new HTTPS connection, with no redirects or explicit proxy, it typically includes DNS resolution, TCP connection establishment, the TLS handshake, request transmission, server processing, and the return of the response.
Comparing two time_starttransfer values therefore measures the difference in first-byte experience from that client's perspective, not simply “how much faster a cache read is than origin processing.” Retain two metrics:
Full TTFB:
time_starttransfer, describing the access experience including connection preparation.Approximate wait after request preparation:
time_starttransfer - time_pretransfer, reducing interference from differences in connection preparation.
The second value still includes request transmission, the client-to-edge round trip, edge queuing, cache lookup, and any upper-tier access or origin fetch. It must not be labeled “origin execution time.” Measuring origin execution requires server logs or distributed tracing.
According to the official curl timing definitions, these time fields are cumulative from the start of the operation. For the simple HTTPS request described above, differences between them can help locate delays:
Metric | Calculation | What it helps identify |
|---|---|---|
DNS resolution |
| Whether name resolution adds significant waiting time |
Approximate TCP connection time |
| The process of establishing a connection from the client to the connection target |
Approximate TLS handshake time |
| HTTPS handshake waiting time |
Wait after request preparation |
| The combined effects of request transmission, edge processing, and upstream waiting |
Transfer after the first byte |
| Subsequent response transfer, rather than waiting for the first byte |
Do not apply this breakdown unchanged to HTTP/3, proxy tunnels, complex authentication, or redirect chains. In particular, do not treat time_connect as TCP time alone or count all of time_appconnect as TLS time.
Cache Warmth and Connection Warmth Are Independent Variables
A cache HIT does not mean a connection is already established, and a cache MISS does not necessarily require a new connection. A HIT over a new connection may be slower than a MISS over a reused connection because of the handshake. That does not demonstrate that caching has no value.
Start with a baseline experiment using independent curl processes and new connections, so both the hit and miss groups incur connection costs. Then test connection reuse separately to better represent consecutive resource loading on a page. curl can attempt to reuse connections across multiple transfers within one invocation, but separate curl processes do not share connections. num_connects can help confirm whether the current transfer opened a new connection.
The baseline experiment can use HTTP/1.1 consistently to reduce differences from multiplexing and negotiation. If production uses HTTP/2 or HTTP/3, add tests for those protocols and report their results separately. Do not combine samples with different protocols or connection states into the same cache-benefit comparison group.
Classify Cache Status from Evidence, Not Speed
Separate HIT, MISS, Revalidation, and Bypass
When the edge directly reuses a fresh object, it usually does not need to wait for an upstream response, making it suitable for the HIT control group. When the edge has no usable object, it may access an upper-tier cache, an origin-facing proxy, or the origin. An expired object may also undergo revalidation through a conditional request. Requests configured to bypass the cache are not objects that can be warmed normally.
Status category | Possible processing | Role in the experiment |
|---|---|---|
Fresh hit | The current cache tier directly reuses the object | Main HIT control group |
Miss | Retrieves the object from an upper-tier cache or the origin | MISS group, with the observed tier identified |
Revalidation | Uses validators to check upstream for changes to the object | Separate group, not included in ordinary HITs |
Bypass or uncacheable | Forwards according to rules, usually without producing a subsequent hit | Dynamic or BYPASS control group |
Stale response | May return an old object first and update it in the background | Label separately to analyze consistency and background origin fetches |
Values such as HIT, MISS, and BYPASS in response headers are common conventions, not universal fields or values across all CDNs. Some responses show results from multiple cache tiers; others show only the nearest tier. Refer to the documentation and log fields for the product used by your account, and first establish which tier each field describes.
Age can provide supporting evidence, but it cannot classify a response on its own. Age: 0 can appear on an object that was just stored or revalidated, and the absence of Age does not prove that a response was not cached. Multi-tier caching may also carry the age of an upper-tier object into a lower tier. For the basic limitations of these fields, consult the explanation of HIT, MISS, and Age.
An Edge MISS Does Not Necessarily Reach Your Origin
This distinction changes the troubleshooting sequence: if you can prove only an edge MISS, first analyze the cost of the edge-to-upstream path rather than immediately attributing the delay to a slow origin. If an upper-tier cache serves the request, the origin may never receive it.
To verify an actual origin fetch, correlate the request time, test-resource path, edge request identifier, upper-tier logs, and origin access records. Before concluding that the origin received no request, also rule out log sampling, logging delays, and requests terminated by a gateway in front of it. The simplest correlation method is to use a dedicated resource path containing no sensitive information and look for matching requests within a short time window.
Likewise, a browser receiving 200 does not prove that the edge made no conditional request to the origin. The edge may receive an upstream 304 and then return 200 to the client using its stored entity. A 304 received directly by the client has no ordinary full response body and should not be mixed into first-byte samples for ordinary GET 200 responses.
Prepare Comparable Resources and Test Conditions
Use a Dedicated Test Path Instead of Purging Popular Production Objects
Choose an existing file with stable content, a moderate size, and no personalized data, such as the example path /cdn-test/ttfb-v1.txt. Confirm that it does not redirect to a login page, depend on cookies, or require third-party API calls. Download it manually and inspect the body first, so that a CAPTCHA page, error template, or empty response returning 200 is not mistaken for a valid sample.
For this dedicated test file, you can configure the following response header at the origin as a starting point:
Cache-Control: public, max-age=60, s-maxage=300
The 60 seconds and 300 seconds here are example test settings, not performance recommendations or vendor defaults. Under standard semantics, max-age controls freshness, while s-maxage applies to shared caches and overrides their max-age. The CDN may also apply a console-configured TTL, cache eligibility rules, edge scripts, or dedicated response headers. Record the rules that ultimately take effect.
MDN's Cache-Control documentation clearly distinguishes no-cache from no-store: the former allows storage but requires validation before reuse; the latter indicates that the response should not be stored. Do not repeatedly add the request header Cache-Control: no-cache to create a supposed “ordinary MISS.” You may instead be measuring forced validation or special handling under account-specific rules.
Apply the configuration only to the experiment path. Do not apply it to personalized content such as login pages, shopping carts, or user APIs. After the experiment, restore the original rules or remove the experiment-specific rules, and confirm that an expanded match scope has not affected production paths.
Keep Request Conditions That Affect the Cache Key Consistent
The same URL does not necessarily access the same cached object. Query strings, hostnames, request methods, compression negotiation, language, and account-specific rules can all affect object selection. Vary also declares which request headers a response depends on. For details, see the MDN HTTP caching guide.
Before sampling, establish an experiment record using these steps:
Record the full URL, method, request headers, expected status code, and body characteristics. Use ordinary GET requests consistently, without Range or conditional requests.
Fix the region, network operator, egress type, and IP address family. Record home broadband, mobile networks, and cloud hosts separately.
Keep compression request conditions consistent. The baseline can use
Accept-Encoding: identity; add the compression variants used by browsers in representative tests.Record the cache key, TTL, query-parameter rules, Cookie and Authorization handling, and whether upper-tier caching is enabled.
Choose a test resource that requires no cookies or credentials. If you need to test authenticated services, create a separate controlled experiment rather than relaxing shared-cache restrictions to achieve hits.
A browser's “disable cache” setting may also change request headers, and a Service Worker may change the request path. Establish a network-level baseline with curl first, then use a browser to check actual access behavior. Do not treat browser refresh results as a cache experiment under identical conditions.
Collect Timings and Response Evidence Together with curl
Verify the Fields and Object with a Single Request First
The following command works in a Unix-like shell with curl installed. The domain and path are examples; replace them with a resource you are authorized to test. The command fixes IPv4, HTTP/1.1, and uncompressed requests, disables explicit proxies configured through the environment, does not follow redirects, and does not retry automatically.
curl -q -4 --http1.1 --noproxy '*' \
--connect-timeout 5 --max-time 20 \
-H 'Accept-Encoding: identity' \
-sS -D sample.headers -o sample.body \
-w 'ip=%{remote_ip} code=%{http_code} connects=%{num_connects} dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ready=%{time_pretransfer} ttfb=%{time_starttransfer} total=%{time_total} bytes=%{size_download}\n' \
'https://www.example.com/cdn-test/ttfb-v1.txt'
Placing -q as the first option prevents the default curl configuration file from changing the experiment conditions. --noproxy '*' excludes curl's explicit proxy settings, but it does not prove that the network path contains no transparent intermediary. If your network requires a proxy, remove this option and record the proxy as an experiment condition. Do not combine those results with direct-connection results.
Inspect the content of sample.body first. Then check sample.headers for the status line, cache-status fields, Age, Cache-Control, Vary, ETag, Last-Modified, and request identifiers that can be used to correlate logs. A response-header file may contain multiple response blocks, such as informational responses. Do not indiscriminately extract the first status line in the file.
If the response is 301 or 302, identify the final resource address first, then have both groups request that same final URL directly. Simply adding -L includes the redirect sequence in the cumulative timing, while the final response headers describe only the last hop, making it easy to mismatch cache status and elapsed time. If you specifically need to measure the redirect experience, run a separate experiment and also record time_redirect.
Do not replace the GET above with curl -I. HEAD is useful for quick checks, but its cache path, origin processing, or cache-fill behavior may differ from GET. Downloading the body to a file does not affect curl's first-byte timing and helps confirm that the application response is valid.
Preserve Raw Records for Every Request in Batch Sampling
The following script performs low-frequency sequential sampling. Each sample starts an independent curl process, so connections are not reused across samples. It does not deliberately create MISS requests; each sample's status must still be confirmed from its response headers and logs.
mkdir -p cdn-ttfb-samples
url='https://www.example.com/cdn-test/ttfb-v1.txt'
for i in $(seq 1 30); do
ts=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
curl -q -4 --http1.1 --noproxy '*' \
--connect-timeout 5 --max-time 20 \
-H 'Accept-Encoding: identity' \
-sS -D "cdn-ttfb-samples/$i.headers" -o /dev/null \
-w "$i,$ts,%{remote_ip},%{http_code},%{num_connects},%{time_namelookup},%{time_connect},%{time_appconnect},%{time_pretransfer},%{time_starttransfer},%{time_total},%{size_download}\n" \
"$url" >> cdn-ttfb-samples/timing.csv \
2> "cdn-ttfb-samples/$i.stderr"
rc=$?
printf '%s,%s\n' "$i" "$rc" >> cdn-ttfb-samples/exit.csv
sleep 1
done
The CSV fields are, in order: sample number, start time, remote IP, HTTP status code, number of new connections, the cumulative timing values, and downloaded bytes. Exit codes are saved separately to distinguish network failures from HTTP errors. Validate the object before discarding bodies during batch sampling. If a status code or byte count is abnormal during sampling, save that type of response body separately for inspection.
The 30 requests are only an example for a small-scale trial, not automatically enough to support reliable tail-latency conclusions. This script is not a load test either. Concurrency introduces request coalescing, queuing, and contention for origin connection pools, so design that testing separately after completing the baseline latency experiment.
Build Reliable HIT and MISS Groups
HIT Group: Confirm Every Sample Even After Warming
Send a warm-up request for the same URL and variant, wait for the response to finish completely, then continue requesting it. Include a sample in the HIT group only if it is a fresh hit under the current product's field semantics. The warm-up request itself does not count as a hit sample, nor does it guarantee that other nodes now hold the object.
If subsequent requests repeatedly miss, first check whether the actual response is cacheable, the TTL is too short, the request carries interfering headers, the cache key changes, or requests are routed to different cache instances. The remote IP can indicate changes in the entry point, but Anycast, load balancing, and cluster sharding mean that even the same IP does not necessarily map to the same cache instance.
If necessary, and only with authorization and an applicable address, use --resolve to fix the entry point for diagnosis. However, this bypasses normal DNS selection, so the conclusions apply only to that entry point and the current egress. It cannot replace user-experience testing under normal routing.
MISS Group: Prefer Exact-URL Purges or Separate Versioned Objects
For the miss group, choose between two controlled methods based on account capabilities and production impact:
Perform an exact-URL cache purge for the dedicated experiment URL, confirm the task status and propagation conditions, then sample the first request. For repeated tests, retain purge times and request identifiers. Do not purge the entire domain.
Prepare several versioned files in advance with identical content, size, response headers, and origin routing. Treat the first request to each file as a candidate MISS, then request the same file repeatedly to obtain HIT samples.
An exact-URL purge keeps the URL identical, but different products may delete the object, mark it stale, or cover only certain cache tiers. You must therefore observe the result rather than automatically equating “purge succeeded” with “cold request to the origin.”
Versioned files reduce the operational impact of repeated purges, but their cache keys still differ. They are suitable for paired experiments with identical content, not for claiming that every variable remained unchanged. If filenames trigger different computation, storage partitions, or authorization at the origin, this method also introduces additional differences.
Avoid continuously adding random parameters to production URLs. If the CDN ignores the parameter, no cold object is created. If the parameter participates in the cache key, it may create substantial cache fragmentation and alter origin application or signature logic. Use this method in an isolated environment only when you clearly understand the parameter semantics and cache-key rules.
Do Not Treat Revalidation After Expiry as a Truly Cold Cache
A request sent after the TTL expires may trigger revalidation rather than a full-object fetch from the origin. If background updating is enabled, the client may quickly receive a stale object while the origin fetch occurs after the response.
The “first request after expiry” can therefore be a separate experiment for observing expiration policies, but it must not automatically be included in the cold MISS group. Confirming a full origin fetch requires examining conditional requests, upstream status, transferred bytes, and origin logs, not just the client-side status code.
To reduce time drift, form multiple pairs consisting of a cold request followed immediately by a hit request, and repeat across time windows. Do not measure all MISS requests in the morning and all HIT requests in the evening. Changes in network and origin load may outweigh the caching benefit.
Analyze Results: Examine Distributions, Then Locate the Delay
Keep Failures and Unknown States in the Statistics
Associate each record with at least its cache status, status evidence, egress conditions, IP address family, remote IP, HTTP status, exit code, full TTFB, and wait after request preparation. Put states that cannot be reliably identified in an “unknown” group. Do not guess labels based on speed.
For successful samples, report the sample count, median, P95, and range separately for HIT, MISS, revalidation, and bypass. With very few samples, P95 is extremely sensitive to individual values, so show the raw distribution and explain the limitations. Use a consistent quantile algorithm, especially for small-sample comparisons.
A timeout does not provide a complete observation that can be treated as normal TTFB. Do not include it as zero or treat the 20-second timeout threshold as the actual time to first byte. Report total requests, valid successes, connection failures, timeouts, HTTP errors, and application-level validation failures separately. Successful-request quantiles describe only the successful subset. Requests whose download fails after the first byte arrives should also be listed separately, not silently counted as fully successful.
Compare regions, network operators, egress types, and IPv4/IPv6 in separate groups. P95 values from multiple regions cannot simply be averaged into an overall P95. An overall quantile requires pooling the relevant raw samples and explaining the sampling weights. For consistent reporting definitions, refer to CdnChart's measurement methodology, but platform observations and your own controlled experiment remain different sources of evidence.
Let the Location of the Difference Determine the Next Step
Observation | Primary interpretation | Minimum verification and next action |
|---|---|---|
Full TTFB is high for both HIT and MISS, with connection preparation accounting for a large share | Connectivity, handshakes, or the local network impose substantial costs | Retest with a fixed IP address family and egress, then test reused connections separately |
MISS has a substantially longer wait after preparation than HIT | The upstream path, object retrieval, or origin processing adds waiting time | Check upper-tier cache and origin logs to confirm which tier was actually reached |
HIT also has a long wait after preparation | Edge processing, the client round trip, or the actual hit tier differs from expectations | Verify field semantics and compare different egress points and time periods |
MISS and HIT are similar and both fast | An upper-tier hit, a nearby origin, or low object-generation cost | Verify upper-tier status rather than immediately extending TTLs for all objects |
MISS is occasionally extremely slow while HIT is relatively stable | Upstream connections, origin queuing, or cache-fill contention | Correlate logs for slow samples, then design a low-risk concurrency experiment |
Time to first byte is similar, but total time differs greatly | The main difference is in the response-transfer phase | Check object size, compression, throughput, and subsequent transfer errors |
“Fast HIT, slow MISS” does not mean all content should be cached for a long time. Versioned static files are suitable for evaluating longer freshness periods and controlled warming. Price, inventory, and permission data must first meet consistency and privacy requirements. If low hit rates result from excessively fragmented cache keys, reducing variants that serve no business purpose is usually more worthwhile to test than simply increasing TTL.
Keep Host and TLS SNI Unchanged When Comparing with the Origin
If MISS requests are substantially slower and you are authorized to test the origin directly, use --resolve to direct the connection to a controlled origin address while keeping the client, URL, and request headers the same:
curl -q -4 --http1.1 --noproxy '*' \
--resolve 'www.example.com:443:203.0.113.10' \
--connect-timeout 5 --max-time 20 \
-H 'Accept-Encoding: identity' \
-sS -D origin.headers -o origin.body \
-w 'code=%{http_code} ready=%{time_pretransfer} ttfb=%{time_starttransfer} total=%{time_total}\n' \
'https://www.example.com/cdn-test/ttfb-v1.txt'
The IP here is a documentation example address. Before running the command, confirm that access to the origin from the test egress is authorized and that the origin can provide the correct certificate and virtual host for the domain. Do not substitute a direct request to an HTTPS IP address with only a Host header added, and do not hide configuration errors by skipping certificate verification.
This experiment preserves the URL, Host, and TLS SNI, but the client-to-origin path is not the same as the CDN-to-origin path. It can help determine whether the origin service is generally slow. You cannot directly subtract direct-to-origin TTFB from CDN MISS TTFB to obtain a supposed “additional CDN overhead.” If the origin permits access only from the CDN, use an authorized diagnostic environment or server logs instead. Do not broadly open the firewall for testing.
Validate Changes with the Same Chain of Evidence
If you decide to adjust TTLs, cache keys, or warming procedures, first limit the change to the experiment path or a small set of resources, save the original configuration, and define rollback conditions in advance. Validation must cover more than HIT TTFB: confirm that content is correct, updates become visible on schedule, error responses are not cached unintentionally, and origin request volume shows no abnormal changes.
During verification, repeat the paired experiment using the same egress, protocol, and request conditions, retaining cache-status evidence for both cold requests and hit requests. Then add the network and browser request conditions of real users. CdnChart's website speed test can help observe domain connectivity performance, but controlled HIT/MISS conclusions still depend on cache evidence for the corresponding requests.
The final report should explain which resource and cache tier were tested, under what connection conditions, how the first-byte distributions differ between hits and misses, how failures were handled, and whether the difference justifies a configuration change. Clearly stating those conditions provides more decision-making value than an out-of-context claim that “caching saved a certain number of milliseconds.”
- CDN time to first byte
- CDN cache hit testing
- cache miss TTFB
- curl timing
- CDN origin-fetch latency
- HIT and MISS
- cold-cache testing