What a cache does
A cache keeps a copy of a response, so the next request for the same thing is answered from the copy. The server that made the original is called the origin. For Kadé the origins are the bucket kade-static-assets and the kade-media VMs.
Every request ends in one of three ways:
- Cloud CDN
- The origin
- Allowed traffic and replies
A hit never reaches the origin. A miss does, once. How long a copy counts as fresh is its TTL (time to live). After that, Cloud CDN asks the origin "has it changed?", which is called revalidation: a 304 answer costs almost nothing, because the file itself is not sent again.
Wide by design - scroll it sideways.
Where Cloud CDN sits
Builds on33. Proxies and load balancers
Cloud CDN is not a separate product in front of the load balancer. It is a switch on a backend service or backend bucket (link 4 of the chain in chapter 12.1), the same place Cloud Armor attaches. It works only on the external Application Load Balancer, because only a proxy has read the request and the response (chapter 11 section 05).
The copies are kept at Google's edge locations, close to users. Each location keeps its own cache:
- Cloud CDN
- The origin
- Allowed traffic and replies
So "the first request is a miss" is true once per location, not once in the world. A file that few people ask for may never be a hit anywhere.
Wide by design - scroll it sideways.
Where the cache falls among Cloud Armor's checks matters (chapter 12.3 section 01): an edge security policy runs before the cache, a backend security policy runs after it. A cache hit is never seen by kade-edge-policy.
What gets stored
Not every response is kept. It must pass four checks:
- Cloud CDN
- A check the response must pass
Wide by design - scroll it sideways.
Check 4 is the cache mode, one setting per backend:
| # | Cache mode | Stores | Kadé's use |
|---|---|---|---|
| 1 | CACHE_ALL_STATIC | Static content types (images, CSS, JS, fonts) even with no header, plus anything the origin marks cacheable | kade-static and kade-media-backend |
| 2 | USE_ORIGIN_HEADERS | Only what the origin marks cacheable with Cache-Control | None yet. The right mode if the API is ever cached |
| 3 | FORCE_CACHE_ALL | Every successful response. Ignores private and no-store | Never on anything that knows who the shopper is |
Try each response under each mode:
Stored at the edge for 1 hour. Browsers keep it for 1 hour.
No header from the origin, but the content type is a static one, so it is stored anyway, for the default TTL. This is why a bucket of images works with no setup.
The TTL settings here are the defaults: default TTL 1 hour, max TTL 1 day, client TTL 1 hour.
How long it is kept
The origin states a lifetime in the Cache-Control header. Cloud CDN adds three settings of its own, which act as a fallback and two caps:
- Cloud CDN
A cap can only shorten what the origin asked for. To keep a file longer, the origin must ask for longer and the cap must allow it.
Wide by design - scroll it sideways.
| # | Setting | Default | What it does in CACHE_ALL_STATIC |
|---|---|---|---|
| 1 | Default TTL | 1 hour | Used when the origin gives no lifetime |
| 2 | Max TTL | 1 day | Caps how long the edge keeps a copy |
| 3 | Client TTL | 1 hour | Caps how long browsers are told to keep it |
USE_ORIGIN_HEADERS none of the three apply: the origin's header is followed as it is. In FORCE_CACHE_ALL the default TTL and client TTL replace the origin's header.The parts of Cache-Control worth knowing:
| # | The origin sends | Meaning |
|---|---|---|
| 1 | public, max-age=86400 | Anyone may keep it, for a day |
| 2 | s-maxage=600 | A lifetime for shared caches such as Cloud CDN only. It wins over max-age there |
| 3 | private | Only the shopper's own browser may keep it. Not stored at the edge |
| 4 | no-store | Nobody keeps it. Kadé's API sends this on everything |
| 5 | immutable | This URL's content will never change, so browsers need not re-check it |
The cache key
When a request arrives, Cloud CDN has to decide whether it already holds "the same thing". It does that by building a cache key from the request and looking the key up. Two requests with the same key share one stored copy.
For a backend service, the default key is the whole URL:
- The part you usually change
Wide by design - scroll it sideways.
The query string is where this goes wrong, in both directions. kade-media can return another file format with ?fmt=, and marketing adds ?utm_source= to every link:
4 requests · 4 cache entries · 4 trips to the origin
The default. The two links from the mail and Instagram campaigns ask for the same WebP image, but their URLs differ, so each is stored separately and each costs a trip to kade-media. Nothing is wrong, the cache is just used badly.
Left: what shoppers ask for. Right: what the edge stores. Requests that join one line share one stored copy.
Changing a file
This is the stale banner from the top of the chapter. After banner.jpg is replaced in the bucket, the old copy still exists in two kinds of place, and you can only reach one of them:
- Cloud CDN
- The origin
Wide by design - scroll it sideways.
| # | Way | How | Use it for |
|---|---|---|---|
| 1 | A new name for every version | The build puts a hash in the name (app.3f9c.js), and the page links to the new name | Everything a page links to: scripts, styles, banners. These can then be cached for a year |
| 2 | Invalidation | A command that tells every edge to drop matching copies (command 8) | A mistake that must go now. It is rate limited, takes a moment, and does not reach browsers |
| 3 | A short lifetime | max-age=300 on the file | The one file whose name cannot change: index.html |
When the origin is slow or down
A copy does not have to be thrown away the second it expires. Two settings make the cache carry on when the origin cannot:
Serve while stale: for a set time after the TTL, shoppers get the old copy at once while Cloud CDN fetches a fresh one behind them. If the origin is failing, they keep getting the old copy.
Wide by design - scroll it sideways.
Negative caching stores error answers too, for a short time. Without it, every request for a photo that does not exist is a miss, and a bot asking for thousands of missing files reaches kade-media with every one. With it, the 404 is answered from the edge for a minute or two.
Private files
Cloud CDN is built for files anyone may read. Some files are not: an invoice, a paid download. For these the app hands out a signed URL, a link that carries an expiry time and a signature made with a key only the app and Cloud CDN know:
- The origin
- Allowed traffic and replies
- Cloud CDN checks the link
The bucket itself is private. Only Cloud CDN's own service account may read it, so the signed link is the only way in.
Wide by design - scroll it sideways.
| # | Tool | Covers | Use it for |
|---|---|---|---|
| 1 | Signed URL | One file | A download link in an email |
| 2 | Signed cookie | Everything under a path | A video made of hundreds of small files |
Reading hits and misses
Each load balancer log entry says what the cache did (logging is set per backend, chapter 12.1 section 10):
- What the line tells you
Wide by design - scroll it sideways.
The number to watch is the cache hit ratio: hits divided by all requests. The Cloud CDN page in the console draws it per backend.
| # | You see | Likely cause | Look at |
|---|---|---|---|
| 1 | Low ratio, many different query strings | The key holds too much | Section 05 |
| 2 | cacheLookup: true, never a hit | The response fails a check: a cookie, private, a Vary header | Section 03, and the response headers (command 3) |
| 3 | Hits, then a wave of misses every hour | A short TTL | Section 04 |
| 4 | Low ratio on rarely requested files | Each location fills its own cache | Normal. Section 02 |
The trap: caching personal data
"Cache the API too" is how this happens. The cache key is the URL. It does not include the cookie or the login token, so two shoppers asking for /api/orders have the same key:
- Cloud CDN and kade-api
- Allowed traffic and replies
Nothing is broken and nothing is logged as an error. One shopper simply sees another's orders.
Wide by design - scroll it sideways.
| # | Trap | What happens | Avoid it by |
|---|---|---|---|
| 1 | FORCE_CACHE_ALL on an app | One shopper's page is served to another | Only ever on a backend of public files |
| 2 | Replacing a file under the same name | Old copies live on in browsers, out of reach | Versioned names (section 06) |
| 3 | The whole query string in the key | Tracking parameters split the cache | An include list (section 05) |
| 4 | A Set-Cookie or Vary: Cookie on static files | Nothing is cached, with no error | Checking the response headers (command 3) |
| 5 | Relying on the backend policy for cached content | A blocked address still gets cache hits | An edge security policy (chapter 12.3 section 01) |
| 6 | Long negative caching | A new file stays "not found" | A minute or two, not hours |
| 7 | Invalidating on every deploy | Slow deploys, rate limits, and browsers still stale | Versioned names |
Back to Kadé
| # | Backend | CDN | Settings |
|---|---|---|---|
| 1 | kade-static (bucket) | On, CACHE_ALL_STATIC | Max TTL and client TTL 1 year, so each file's own header decides. Serve while stale 1 day. Negative caching on |
| 2 | kade-media-backend (VMs) | On, CACHE_ALL_STATIC | Key: only fmt from the query string. Serve while stale 1 day. 404 cached for 1 minute |
| 3 | kade-api-backend (Cloud Run) | Off | The API sends Cache-Control: no-store |
| # | Files in kade-static-assets | Cache-Control on the object | Changed by |
|---|---|---|---|
| 1 | /assets/* (hashed names) | public, max-age=31536000, immutable | A new name |
| 2 | /images/* | public, max-age=86400 | A new name, or an invalidation |
| 3 | index.html | public, max-age=300 | Waiting five minutes |
The CDN settings as Terraform
resource "google_compute_backend_bucket" "kade_static" {
name = "kade-static"
bucket_name = "kade-static-assets"
enable_cdn = true
cdn_policy {
cache_mode = "CACHE_ALL_STATIC"
default_ttl = 3600
max_ttl = 31536000
client_ttl = 31536000
serve_while_stale = 86400
negative_caching = true
}
}
resource "google_compute_backend_service" "kade_media" {
name = "kade-media-backend"
enable_cdn = true
# backend, health check, security policy and logging: chapter 12.2
cdn_policy {
cache_mode = "CACHE_ALL_STATIC"
default_ttl = 3600
max_ttl = 86400
client_ttl = 3600
serve_while_stale = 86400
negative_caching = true
negative_caching_policy {
code = 404
ttl = 60
}
cache_key_policy {
include_protocol = true
include_host = true
include_query_string = true
query_string_whitelist = ["fmt"]
}
}
}
Commands in this chapter
Commands 1 to 3 are read-only. Commands 4 to 8 change the project.
See the CDN settings of a backend
- What it shows: Whether CDN is on, the cache mode, the three TTLs and the cache key.
- What to look for:
enableCDN: true,cacheMode, and for kade-media thecacheKeyPolicy.
gcloud compute backend-buckets describe kade-static --format="yaml(enableCdn,cdnPolicy)"gcloud compute backend-services describe kade-media-backend --global --format="yaml(enableCDN,cdnPolicy)"See hits and misses in the logs
- What it shows: Recent requests to kade-media, with what the cache did for each.
- What to look for:
cacheHit: Trueandresponse_from_cacheon most lines. The same photo missing again and again is a key or header problem.
gcloud logging read 'resource.type="http_load_balancer" AND resource.labels.backend_service_name="kade-media-backend"' --freshness=1h --limit=20 \ --format="table(timestamp,httpRequest.requestUrl,httpRequest.cacheLookup,httpRequest.cacheHit,jsonPayload.statusDetails)"Read the headers of one response
- What it shows: What the origin said about caching, and whether this answer came from the cache.
- What to look for: An
ageheader on the second run. Aset-cookieorvary: cookieline explains a file that is never cached.
curl -sI https://www.kade.lk/media/rice-640w.jpgcurl -sI https://www.kade.lk/media/rice-640w.jpg | grep -iE "^(age|cache-control|set-cookie|vary)"Add a hit-or-miss header to responses (changes the project)
- What it shows: A response header filled in by Cloud CDN itself.
- What to look for:
cache-status: hit,missorrevalidatedin command 3.
gcloud compute backend-services update kade-media-backend --global \ --custom-response-header="Cache-Status: {cdn_cache_status}"Set the TTLs, serve while stale and negative caching (changes the project)
- What it shows: The settings of sections 04 and 07 on the bucket backend.
- What to look for: The new values under
cdnPolicyin command 1.
gcloud compute backend-buckets update kade-static \ --enable-cdn --cache-mode=CACHE_ALL_STATIC \ --default-ttl=3600 --max-ttl=31536000 --client-ttl=31536000 \ --serve-while-stale=86400 --negative-cachingKeep only fmt in the cache key (changes the project)
- What it shows: Section 05's fix for kade-media.
- What to look for:
queryStringWhitelist: [fmt]in command 1, then a rising hit ratio.
gcloud compute backend-services update kade-media-backend --global \ --cache-key-include-query-string --cache-key-query-string-whitelist=fmt \ --serve-while-stale=86400 --negative-caching --negative-caching-policy="404=60"Set Cache-Control on files in the bucket (changes the project)
- What it shows: The lifetime each kind of file asks for.
- What to look for: The new
cache-controlline in command 3. Set it in the upload step of the build, so new files get it too.
gcloud storage objects update "gs://kade-static-assets/assets/**" \ --cache-control="public, max-age=31536000, immutable"gcloud storage objects update gs://kade-static-assets/index.html \ --cache-control="public, max-age=300"Invalidate cached copies (changes the project)
- What it shows: Every edge location dropping its copies of the matching paths.
- What to look for: The next request is a miss. Browsers that already hold the file are not affected. A
*is allowed only at the end of the path.
gcloud compute url-maps invalidate-cdn-cache kade-url-map \ --host=www.kade.lk --path="/images/banner.jpg"gcloud compute url-maps invalidate-cdn-cache kade-url-map \ --host=www.kade.lk --path="/images/*"