Chapters

Cloud CDN: caching at the edge

Chapters 12.1 and 12.2 turned Cloud CDN on with one flag and moved on. This chapter covers what that flag does: which responses are stored and for how long, how the cache decides two requests are the same, how to replace a file that is already cached, and why the API must never be cached by accident.

The front door · chapter 18 of 26 · 18 min read

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:

1 · first request: a missShopperCloud CDNno copy: fetch one, keep itbucketsends rice.jpg2 · next requests: a hitShopperCloud CDNhas a copy: answers herebucketnot contacted3 · after the TTL: a checkShopperCloud CDNcopy too old: asks firstbucket304: not changed
  • 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:

Shopper, Colomboedge cachehas rice.jpg: hitVisitor, Singaporeedge cacheempty: miss, then fillsVisitor, Londonedge cacheempty: miss, then fillsbucketkade-static-assetsno trip: answered here
  • 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:

1 · a GETnot POST or PUTfails any one: not stored, every request goes to the origin2 · no cookieno Set-Cookie3 · not privateno private, no-store4 · mode says yessee the three belowstoredat the edge
  • 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 modeStoresKadé's use
1CACHE_ALL_STATICStatic content types (images, CSS, JS, fonts) even with no header, plus anything the origin marks cacheablekade-static and kade-media-backend
2USE_ORIGIN_HEADERSOnly what the origin marks cacheable with Cache-ControlNone yet. The right mode if the API is ever cached
3FORCE_CACHE_ALLEvery successful response. Ignores private and no-storeNever on anything that knows who the shopper is

Try each response under each mode:

Cache mode
origin sends /media/rice-640w.jpgContent-Type: image/jpegno Cache-Control headeredge cachekeeps it 1 hourthen asks the origin againbrowserkeeps it 1 hourno request at all

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:

The origin saysmax-age = 7 daysThe edge keeps itmax TTL caps it at 1 dayA browser keeps itclient TTL caps it at 1 hour7 days1 day1 hour
  • 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.

#SettingDefaultWhat it does in CACHE_ALL_STATIC
1Default TTL1 hourUsed when the origin gives no lifetime
2Max TTL1 dayCaps how long the edge keeps a copy
3Client TTL1 hourCaps how long browsers are told to keep it
In 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 sendsMeaning
1public, max-age=86400Anyone may keep it, for a day
2s-maxage=600A lifetime for shared caches such as Cloud CDN only. It wins over max-age there
3privateOnly the shopper's own browser may keep it. Not stored at the edge
4no-storeNobody keeps it. Kadé's API sends this on everything
5immutableThis 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:

httpsprotocolin the keywww.kade.lkhostin the key/media/rice-640w.jpgpathalways in the key?fmt=webp&utm_source=mailquery stringin the key, unless you say otherwise
  • 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:

The key includes
/media/rice-640w.jpg?fmt=webp/media/rice-640w.jpg?fmt=webp&utm_source=mail/media/rice-640w.jpg?fmt=webp&utm_source=insta/media/rice-640w.jpg?fmt=avif/media/rice-640w.jpg?fmt=webpholds the WebP image/media/rice-640w.jpg?fmt=webp&utm_source=mailholds the WebP image/media/rice-640w.jpg?fmt=webp&utm_source=instaholds the WebP image/media/rice-640w.jpg?fmt=avifholds the AVIF image

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:

browsersold copy · up to 1 hourCloud CDN edgesold copy · up to 1 daybucketnew banner.jpgno command reaches thesean invalidation clears thesea new name instead: banner.8c1d.jpgno browser and no edge has a copy, so the next request gets the new filethe other way
  • Cloud CDN
  • The origin

Wide by design - scroll it sideways.

#WayHowUse it for
1A new name for every versionThe build puts a hash in the name (app.3f9c.js), and the page links to the new nameEverything a page links to: scripts, styles, banners. These can then be cached for a year
2InvalidationA 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
3A short lifetimemax-age=300 on the fileThe one file whose name cannot change: index.html
The three fit together: the page is cached for minutes and names the versioned files, which are cached for a year.

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:

freshserved as it isstale, still servedrefreshed in the backgroundgonemust reach the originTTL endsserve-while-stale endsorigin slow or down? shoppers still get an answeronly with serve-while-stale turned on

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:

kade-apisigns the URLShopperowns invoice 1042Cloud CDN checkssignature · expiryprivate bucketCDN-only readsigned link, 10 minAnyone elseguesses the URL✕no signature, or expired: 403
  • 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.

#ToolCoversUse it for
1Signed URLOne fileA download link in an email
2Signed cookieEverything under a pathA video made of hundreds of small files
A signed link is a key, not a login: anyone who has it can use it until it expires. Keep the expiry short. Kadé has no private files yet, so this is not part of its setup.

Reading hits and misses

Each load balancer log entry says what the cache did (logging is set per backend, chapter 12.1 section 10):

httpRequest.cacheLookup: truethe cache was checkedhttpRequest.cacheHit: trueanswered from the cachehttpRequest.cacheValidatedWithOriginServer: falsetrue = it asked the origin firstjsonPayload.statusDetails: "response_from_cache"who answered, in wordsjsonPayload.cacheId: "SIN-4d2a81"which edge location
  • 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 seeLikely causeLook at
1Low ratio, many different query stringsThe key holds too muchSection 05
2cacheLookup: true, never a hitThe response fails a check: a cookie, private, a Vary headerSection 03, and the response headers (command 3)
3Hits, then a wave of misses every hourA short TTLSection 04
4Low ratio on rarely requested filesEach location fills its own cacheNormal. 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:

GET /api/orders · cache mode FORCE_CACHE_ALLShopper Alogged inCloud CDNkeeps a copy of A's orderskade-apireturns A's ordersShopper Bsomeone elseCloud CDNsame URL: a hitkade-apinever askedgets A's orders
  • 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.

#TrapWhat happensAvoid it by
1FORCE_CACHE_ALL on an appOne shopper's page is served to anotherOnly ever on a backend of public files
2Replacing a file under the same nameOld copies live on in browsers, out of reachVersioned names (section 06)
3The whole query string in the keyTracking parameters split the cacheAn include list (section 05)
4A Set-Cookie or Vary: Cookie on static filesNothing is cached, with no errorChecking the response headers (command 3)
5Relying on the backend policy for cached contentA blocked address still gets cache hitsAn edge security policy (chapter 12.3 section 01)
6Long negative cachingA new file stays "not found"A minute or two, not hours
7Invalidating on every deploySlow deploys, rate limits, and browsers still staleVersioned names

Back to Kadé

#BackendCDNSettings
1kade-static (bucket)On, CACHE_ALL_STATICMax TTL and client TTL 1 year, so each file's own header decides. Serve while stale 1 day. Negative caching on
2kade-media-backend (VMs)On, CACHE_ALL_STATICKey: only fmt from the query string. Serve while stale 1 day. 404 cached for 1 minute
3kade-api-backend (Cloud Run)OffThe API sends Cache-Control: no-store
#Files in kade-static-assetsCache-Control on the objectChanged by
1/assets/* (hashed names)public, max-age=31536000, immutableA new name
2/images/*public, max-age=86400A new name, or an invalidation
3index.htmlpublic, max-age=300Waiting five minutes
Chapter 13 puts Cloudflare's cache in front of this one. The headers above then steer both caches.

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 the cacheKeyPolicy.
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: True and response_from_cache on 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 age header on the second run. A set-cookie or vary: cookie line 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, miss or revalidated in 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 cdnPolicy in 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-caching

Keep 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-control line 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/*"

Spotted a mistake, or something unclear? Suggest an edit on GitHub