Freshness and caching
Live fetch vs cache latency: measure both on your own pages
Time live page reads and stored-copy reads on your own sources, in milliseconds, compare medians and 95th percentiles, and decide where a live read fits.
By Curtis Mccann, Live Web Data team · Published
This article was drafted with AI assistance from the sources listed below and edited and published by the Live Web Data team. Disclosure: the Live Web Data API, which this article mentions, is this site's own product.
- 1Split one live readRun curl with -w and subtract its cumulative timers: DNS, connect, TLS, first byte, download.
- 2Time 30 reads of each pathLive reads 1 second apart, store reads back to back, both with time.perf_counter() in milliseconds.
- 3Compare p50 and p95The median shows the typical read; the 95th percentile shows what slow requests feel like.
- 4Count failures apartA timed-out read is a failure, not a latency sample.
- 5Check the miss rateIf more than 5% of cached-path requests miss, and misses are slower than hits, the p95 of that path is a live read.
A stored copy is faster than a live read. Everyone agrees on that much. The question your app actually has is how much faster, on your sources, from your servers, and whether the difference matters to a user who is waiting. Latency numbers measured on other pages, from other places, do not answer it. You can answer it yourself with curl and a short standard-library Python script.
The guide on live vs cached web data says to measure live read time for your own sources and set a timeout that fits how long your users can wait. This post is the measurement.
Split one live read into phases
Start with a single read, because the total hides where the time goes. curl's --write-out (-w) option prints timers after the transfer. Each one is measured from the start of the request, in seconds:
curl -s -o /dev/null -w 'dns %{time_namelookup}\nconnect %{time_connect}\ntls %{time_appconnect}\npretransfer %{time_pretransfer}\nfirst_byte %{time_starttransfer}\ntotal %{time_total}\nstatus %{response_code}\n' https://example.com/
The curl man page defines them this way:
time_namelookup: from the start until name resolving was completed.time_connect: until the TCP connect to the remote host (or proxy) was completed.time_appconnect: until the SSL/SSH/etc connect or handshake was completed.time_pretransfer: until immediately before the file transfer was about to begin.time_starttransfer: until the first byte was received.time_total: the whole operation.
Because the timers are cumulative, the phases are differences. TCP connect is time_connect minus time_namelookup. The TLS handshake is time_appconnect minus time_connect. The wait for the first byte is time_starttransfer minus time_pretransfer. The download of the body is time_total minus time_starttransfer.
This split tells you what a cache can save. A copy in your own store skips all of it: name lookup, connect, handshake, the site's wait and the download. A large wait for the first byte points at the site itself; a large download points at page size. Recent curl versions add two more timers: time_posttransfer (added in 8.10.0) and time_queue (added in 8.12.0).
Time both paths the same way
One read is an anecdote. Run the same timer around both paths, many times, and keep every sample. Python's time.perf_counter() is documented as the clock with the highest available resolution for short durations, and on CPython it is monotonic, so it cannot go backwards. Do not use time.time() for durations: Python's docs say it can return a lower value than a previous call if the system clock was set back.
import sqlite3
import statistics
import time
import urllib.request
URL = "https://example.com/"
RUNS = 30
def live_read(url):
with urllib.request.urlopen(url, timeout=10) as resp:
return resp.read()
def summary(label, samples, failures):
if len(samples) <= 20:
print(f"{label}: only {len(samples)} samples, {failures} failed")
return
cuts = statistics.quantiles(samples, n=20) # 19 cut points: 5%, 10%, ... 95%
print(f"{label}: n={len(samples)} failed={failures} "
f"p50={statistics.median(samples):.1f} ms p95={cuts[18]:.1f} ms")
# Live path: 30 reads, 1 second apart, so the site sees a slow trickle.
live, failed, body = [], 0, b""
for _ in range(RUNS):
start = time.perf_counter()
try:
body = live_read(URL)
live.append((time.perf_counter() - start) * 1000)
except Exception: # URLError, HTTPError, TimeoutError and the like
failed += 1
time.sleep(1)
# Stored path: replace this SQLite file with the store your app really uses.
db = sqlite3.connect("pages.db")
db.execute("CREATE TABLE IF NOT EXISTS pages (url TEXT PRIMARY KEY, body BLOB)")
db.execute("INSERT OR REPLACE INTO pages VALUES (?, ?)", (URL, body))
db.commit()
stored = []
for _ in range(RUNS):
start = time.perf_counter()
db.execute("SELECT body FROM pages WHERE url = ?", (URL,)).fetchone()
stored.append((time.perf_counter() - start) * 1000)
summary("live", live, failed)
summary("stored", stored, 0)
Three details in this script matter.
- Failures are counted, not timed. A read that times out never gets a latency sample. Mixing a failure into the list as a number would hide it in the percentiles. Report the failure count next to the latency.
- The timeout is not a total cap. The
urllib.requestdocs saytimeoutis in seconds and applies to blocking operations like the connection attempt. It does not promise that the whole read ends within 10 seconds. If you need a hard limit on the whole read, enforce it around the call. - The store must be the real one. A local SQLite file on the same disk is close to the best case. If your app reads copies from a database or cache across the network, time that, from the same server that serves users.
Run the script against a handful of URLs from each source you actually read, not one test page. Read only public pages you are allowed to fetch, respect robots.txt and the site's terms, and keep the pacing slow: 30 reads, 1 second apart, is at least 30 seconds per URL.
Compare percentiles, not averages
The Service Level Objectives chapter of Google's SRE book makes the case plainly. Most metrics are better thought of as distributions than averages, and "a simple average can obscure these tail latencies, as well as changes in them." The chapter says its teams prefer percentiles to the mean. The 50th percentile, the median, emphasizes the typical case; a high percentile such as the 99th or 99.9th shows a plausible worst-case value.
With 30 samples, stay at the 95th percentile. Python's statistics.quantiles() docs say the number of data points should be larger than n for meaningful results, which is why the script uses n=20 (cut points every 5%, the last at 95%) and not n=100, which gives the 99 percentile cut points. For the 99th percentile, collect more than 100 samples, spread over a day rather than one burst.
Read the results as a set:
- Live p50 is what a typical live read costs your user, in milliseconds.
- Live p95 is the time that 1 in 20 live reads reaches or exceeds. This is the number to hold against your user's wait budget and your timeout.
- Stored p50 and p95 are the floor for any request that has to look in the store first.
The cached path has a miss rate
A cache is not a separate path in production. It is a path that sometimes turns into a live read: when there is no copy, or the copy is older than the maximum age for its page type. So the latency of "read from cache" is a mix of store reads and live reads.
Percentiles make the consequence clear. Suppose every miss is slower than every hit, which is what you expect when a miss includes a live read. If more than 5% of requests on the cached path miss, the slowest 5% of requests are all misses, and the 95th percentile of the cached path is a live read time. Caching then improves the median, while your slow requests stay as slow as a live read.
That gives you the decision:
- Measure live p95 and stored p95 for each source.
- Log your real miss rate per page type, from production, not from a guess.
- If the miss rate is above 5%, judge the slow end of the user experience by live p95, and set the live read timeout from it.
- If live p95 fits the wait budget, the latency argument for a cache is weak. Keep a stored copy where freshness allows it and it saves load on the site; the post on serving a stale copy when a live read fails covers the fallback case.
Measuring a page-fetch API
The same timer works around any fetch call, including an HTTP API that reads pages for you. Time the whole call from your server, keep failures apart, and compare its p50 and p95 with your direct reads and your store.
If you read pages through Live Web Data API: "Every request fetches the page live; there is no cache." Every call belongs in the live column of your measurement, and livecrawlTimeout caps how long a read may wait. "Failed fetches cost 0 credits." You can try a URL of your own in the playground.
Frequently asked questions
How much slower is a live web fetch than a cache read?
It depends on the target site, the distance to it and your own store, so measure it. Time about 30 live reads and 30 reads from your store with a monotonic clock, then compare the median and the 95th percentile of each in milliseconds.
Should I compare average latency for live and cached reads?
Use percentiles instead. Google's SRE book says a simple average can obscure tail latencies and changes in them, and that its teams prefer percentiles to the mean. Compare the median for the typical read and a high percentile for the slow ones.
Which curl timing shows how long the server took to answer?
curl's -w timers are cumulative from the start of the request. time_starttransfer is the time until the first byte was received and time_pretransfer the time until just before the transfer began, so the difference is the wait for the first byte.
Why use time.perf_counter() and not time.time() to time fetches?
Python documents time.perf_counter() as the clock with the highest available resolution for short durations, and on CPython it is monotonic. time.time() can return a lower value than a previous call if the system clock is set back, which would corrupt a duration.
Sources
- curl man page (--write-out variables) (Documentation)
- Service Level Objectives (Google SRE book) (Documentation)
- time: Time access and conversions (Python docs) (Documentation)
- statistics: Mathematical statistics functions (Python docs) (Documentation)
- urllib.request (Python docs) (Documentation)