Cloud CDN in Google Cloud

Cloud CDN in Google Cloud

A complete, plain-English guide to Google's content delivery network: what it is, how it works inside, how to make websites and downloads load faster, how to keep cached content fresh and private content safe, and how to control the cost.

Think about the last time a web page felt slow. You tapped a link, stared at a blank screen, and wondered whether to give up. Often the reason is simple distance. The computer that holds the page may be thousands of kilometers away, and every picture, script and style sheet must travel that whole way, one trip after another.

Now imagine that popular pages were also kept in small shops near every city, so the next person asking for the same page could pick it up from a shop around the corner. The trip would be short and the page would open at once. That idea is called a content delivery network, or CDN, and Google Cloud’s version is named Cloud CDN.

In this guide you will learn what Cloud CDN is, why it exists, how a web request travels, how Cloud CDN decides what to keep and for how long, how to connect it to your servers, how to keep content fresh and private, how to measure it, and how to avoid common mistakes. Every new word is explained the first time it appears, and almost every idea comes with an everyday example.

WWhat Cloud CDN Is and Why It Exists

Before the details, let us understand the problem that Cloud CDN solves, using a simple story.

The problem: distance makes things slow

Imagine you run an online shop from a data center in one city. Your customers live all over the world. When a customer far away opens your home page, their request must cross oceans and many networks to reach your server, and the answer must come all the way back. Even at the speed of light in a cable, long distances add delay. A page is not one file, either. It may need dozens or hundreds of files, such as pictures, fonts and scripts, and each needs its own trip.

There is a second problem. If a thousand customers ask for the same big picture at the same moment, your server must send the same picture a thousand times. It works hard doing the same job again and again, and your network bill grows. In a big sale, the server may simply give up under the load.

Analogy

Picture a famous bakery that makes one special bread in a single city. Customers in far cities must wait days for a delivery. Now suppose the bakery sends a few loaves each morning to small shops in every city. Local customers buy from the nearby shop in seconds, and the main bakery is no longer swamped. Cloud CDN is that network of nearby shops for web content.

The Cloud CDN answer: keep copies near the users

A CDN keeps copies of your content in many places around the world. Each place is a small data center that is close to where people live. When someone asks for a file, the CDN tries to answer from the nearest copy. This is called caching, which means keeping a copy of something so that the next request can be answered faster. If the CDN does not have a copy, it fetches the file from your server, answers the user, and keeps a copy for the next person.

Cloud CDN uses Google’s own worldwide network, the same kind of infrastructure that serves Search and YouTube. It works together with Google Cloud’s load balancing, so it feels like a built-in feature of your web front door rather than a separate system to run.

What a CDN gives you

Speed

Faster pages

Content comes from a place near the user, so the first byte arrives sooner and pages finish loading earlier.

Load

Less work for your servers

Most requests for common files are answered by the CDN, so your servers handle far fewer.

Cost

Lower origin traffic

Less data leaves your servers, which often reduces both compute and network costs.

Scale

Handling spikes

A sudden crowd for the same content is absorbed by the cache instead of crushing the origin.

Safety

A buffer in front

The CDN stands between users and your servers, adding resilience and a place for security controls.

Resilience

Survive short outages

Cached copies can keep serving users for a time even when the origin has trouble.

A short history

The first commercial CDNs appeared in the late 1990s, when websites began to carry images and video and the internet struggled with the load. Over time CDNs became a standard part of nearly every large website. Google Cloud introduced Cloud CDN in the mid 2010s, built on top of its global load balancers, and has added features such as signed access, custom cache keys, serving stale content and support for outside origins. Google also offers a separate product, Media CDN, aimed at very large video and download delivery.

Where Cloud CDN sits among Google Cloud services

ServiceJobRelationship to Cloud CDN
Cloud CDNCaches content at Google’s edge, close to usersThe subject of this guide
External Application Load BalancerReceives web traffic and routes it to backendsCloud CDN is switched on at the load balancer’s backends
Cloud StorageStores files in bucketsA common origin for images, downloads and static sites
Compute Engine, GKE, Cloud RunRun your application codeCommon origins for dynamic and static content
Cloud ArmorWeb application firewall and attack protectionWorks at the same front door to filter traffic
Media CDNDelivery for large-scale video and downloadsA sibling product for very heavy media workloads
i
Pro Tip

A simple rule: if your website, app or download service serves the same files to many people in many places, a CDN will almost always help. The more your content repeats, the more a CDN can save you.

Production example: global online stores

Large online shops serve the same product pictures, style sheets and scripts to millions of visitors. By placing these files in a CDN, the shop’s own servers are left to handle the work that is truly unique, such as carts, logins and payments. Shoppers in distant countries see the pages open about as quickly as shoppers near the data center.

HHow Web Delivery Works: The Basics You Need

To understand a CDN, you first need a simple picture of what happens when you open a web page.

Clients and servers

A client is the program asking for something, such as your web browser or a mobile app. A server is the computer that answers. The client sends a request, such as “give me the picture at this address”. The server sends a response, which contains the file and some extra information called headers.

URLs and domain names

Every file on the web has an address, called a URL. A URL names the site, such as shop.example.com, and the path to the file, such as /images/shoes.jpg. People use names, but computers use numbers called IP addresses. A system called DNS, the Domain Name System, is like the phone book that turns a name into an IP address.

The trip and its delays

Before any content flows, the client and server must do some setup. First, DNS finds the address. Then they open a connection, which takes a short exchange of messages. If the site uses HTTPS, which is the secure version, they also agree on encryption, which takes a few more messages. Only then does the request for the file go out. Each of these steps takes at least one round trip across the network, and a round trip across a continent can take over a hundred milliseconds. These small delays add up.

Analogy

Sending a letter overseas and waiting for the reply is slow because every message travels far. If you could talk to someone in your own street instead, you could ask ten questions in the time one letter takes to cross the ocean. A CDN moves the other end of the conversation to your own street.

Latency and bandwidth

Latency is the time one message takes to travel and be answered. It depends mostly on distance and the number of hops between networks. Bandwidth is how much data can flow per second, like the width of a pipe. A CDN mainly reduces latency, by shortening the distance, and it also relieves bandwidth pressure on your servers.

Static and dynamic content

Static content is the same for everyone and does not change often. Examples include logos, product photos, style sheets, scripts, fonts, videos and software downloads. Dynamic content is made fresh for each request or each person, such as a shopping cart, a bank balance or a search result. Static content is perfect for caching. Dynamic content is harder, because a copy made for one person would be wrong for another.

Kind of contentExamplesGood for caching?
Static, sharedLogos, images, style sheets, scripts, fonts, downloadsExcellent
Semi-staticProduct pages, news articles, public API results that change slowlyGood, with short lifetimes
PersonalAccount pages, carts, private messagesNo, never share between people
Real-timeLive prices, chat messagesUsually no, or only for a second or two

What caching is

A cache is a place that keeps copies of things that were recently used, so they can be found quickly the next time. Your browser has a cache. Your computer has caches. A CDN is a very large, shared cache spread across the world. The big question for any cache is: when is a stored copy still good? That question leads to the idea of a lifetime.

Lifetime, or TTL

Every cached copy has a TTL, which stands for Time To Live. It is the number of seconds the copy may be used before it is considered old. Within its TTL, a copy is fresh, and the cache may serve it without asking the original server. After the TTL ends, the copy is stale, and the cache must check with the origin before using it again.

Analogy

A cached copy is like milk in the fridge with a date on the carton. Before the date, you pour without worrying. After the date, you check whether it is still good before drinking. A short lifetime keeps things fresh but means more trips to the shop. A long lifetime saves trips but risks serving something old.

Cache hit and cache miss

When the cache has a fresh copy and uses it, that is a cache hit. When it has no usable copy and must go to the origin, that is a cache miss. The share of requests that are hits is the cache hit ratio. A higher ratio means more speed and more savings, so much of CDN tuning is about raising it safely.

Headers that guide caching

Servers use headers to tell caches what to do. The most important is Cache-Control. It can say how long to keep something, for example “keep for one hour”, or forbid keeping it, for example “private” for data meant for one person only, or “no-store” for data that must never be saved. Other headers help a cache check whether a copy is still valid, such as ETag, a label for a version of a file, and Last-Modified, the time the file last changed.

i
Remember

The whole CDN idea rests on three simple questions: Where is the nearest copy? Is the copy still fresh? Is it safe to share this copy with this person? Everything in this guide is about answering those three questions well.

Production example: news and media sites

A news site updates its front page every few minutes, but its pictures, scripts and style sheets rarely change. Publishers give the front page a short lifetime of seconds or minutes, and give the images and scripts a lifetime of weeks. This gives readers fresh headlines and fast pages, while the CDN absorbs most of the traffic during breaking news.

CCore Concepts You Must Know First

Cloud CDN has its own small vocabulary. Learn these words once, and the rest of the guide will feel familiar.

Origin

The origin is the place where the real, original content lives. It may be a group of virtual machines, a Kubernetes service, a Cloud Run service, a Cloud Storage bucket, or even a server outside Google Cloud. The CDN fetches from the origin when it has no copy.

Edge and point of presence

The edge is the part of the network closest to users. A point of presence, often written PoP, is one location at the edge where Google has network equipment and caches. When people say “the edge cache”, they mean the cache at one of these locations.

External Application Load Balancer

A load balancer receives incoming traffic and spreads it across backends. The external Application Load Balancer is Google’s load balancer for public web traffic. Cloud CDN is switched on for it, so the load balancer is the “front door” that also checks the cache.

Backend service and backend bucket

A backend service describes a group of servers that handle requests, together with health checks and settings. A backend bucket connects the load balancer to a Cloud Storage bucket. You enable Cloud CDN on a backend service or a backend bucket, one at a time.

Network endpoint group

A network endpoint group, or NEG, is a way to name a set of targets for the load balancer. A serverless NEG points to a serverless service such as Cloud Run. An internet NEG points to an outside server by its name or address, which lets Cloud CDN work with origins that are not inside Google Cloud.

Cache key

A cache key is the label a CDN uses to decide whether two requests are asking for the same thing. By default, it includes the protocol, the host name and the full URL with its query string. Two requests with the same key share one cached copy. Changing what goes into the key changes how many separate copies exist.

Cache mode

The cache mode decides what Cloud CDN is allowed to cache. In one mode it follows the headers sent by the origin. In another it caches common static file types automatically. In the strongest mode it caches nearly every successful response regardless of headers. We study these in detail later.

Invalidation

Invalidation means telling the CDN to forget cached copies before their lifetime ends, for example because you published a fix and cannot wait.

Signed URL and signed cookie

A signed URL is a web address with a secret signature and an expiry time. Only people who hold such an address can fetch the content, and only until it expires. A signed cookie does the same job for many files at once. They protect paid or private content while still using the CDN.

Source

Origin

The place where the real content lives and where the CDN fetches from.

Location

Edge and PoP

The caches near users, in many cities around the world.

Front door

Load Balancer

Receives web traffic and checks the cache before using the origin.

Label

Cache Key

Decides which requests share the same cached copy.

Time

TTL

How long a cached copy counts as fresh.

Access

Signed URL

A temporary, secret-signed address for private content.

!
Common Trap

Cloud CDN is not a stand-alone product that you point a domain name at. It works through Google’s external Application Load Balancer. If your site does not use that load balancer, you must set one up first. Beginners often search for a separate “CDN switch” and cannot find it.

i
Note

Google adds features and changes details over time, including which load balancer types and origin types are supported. Treat the specifics in this guide as general examples, and confirm them in Google’s current documentation before you design a real system.

AArchitecture and Main Components

Now let us zoom out and see how Cloud CDN fits between your users and your servers.

A typical setup has four groups of parts. First, the users, with browsers and apps all over the world. Second, the Google edge, which includes the points of presence, the global front-end network and the load balancer with Cloud CDN. Third, the origins: your servers or buckets. Fourth, the supporting services: security rules, certificates, monitoring and logs.

flowchart TD
  U1["User in Asia"] --> E1["Google Edge PoP Asia"]
  U2["User in Europe"] --> E2["Google Edge PoP Europe"]
  U3["User in Americas"] --> E3["Google Edge PoP Americas"]
  subgraph GFE["Google Global Front End"]
    E1 --> LB["External Application Load Balancer"]
    E2 --> LB
    E3 --> LB
    LB --> ARMOR["Cloud Armor Security Policy"]
    ARMOR --> CDN["Cloud CDN Cache Lookup"]
  end
  CDN -->|"cache hit - answer from cache"| E1
  CDN -->|"cache miss"| BS["Backend Service"]
  CDN -->|"cache miss"| BB["Backend Bucket"]
  BS --> MIG["VM Instance Group or GKE"]
  BS --> RUN["Cloud Run via Serverless NEG"]
  BS --> EXT["External Origin via Internet NEG"]
  BB --> GCS["Cloud Storage Bucket"]
  MON["Cloud Monitoring and Logging"] -.-> LB
  CERT["Managed TLS Certificates"] -.-> LB
Figure 1: A typical Cloud CDN layout. Users reach a nearby Google edge location, then the load balancer, security policy and cache. Only cache misses go on to the origins.

Walking through the picture

At the top are users in different parts of the world. Each user’s request is sent to a nearby Google edge location. Google uses a technique called anycast, which lets one public IP address be announced from many places, so the network automatically delivers each user’s traffic to the closest one. The user does not choose and does not need to know.

From the edge, the request flows into Google’s global front end and reaches the external Application Load Balancer. The load balancer ends the secure connection, reads the request, and applies a Cloud Armor security policy if you have one. Then Cloud CDN performs a cache lookup. If a fresh copy exists, the answer goes straight back to the user. That path is the hit path, and it is the fastest and cheapest.

If there is no usable copy, Cloud CDN passes the request to the backend. A backend can be a backend service, which points to virtual machines, Kubernetes pods, Cloud Run or even an outside server, or a backend bucket that points to Cloud Storage. The origin answers, and Cloud CDN keeps a copy of the response, if the rules allow, for the next requester.

Around everything are supporting services: managed certificates for HTTPS, and monitoring and logging that record each request and whether it was a hit or a miss.

Analogy

Think of a chain of convenience stores backed by a central warehouse. A customer walks into the nearest store (the edge). The cashier (the load balancer) checks the shelf (the cache). If the item is there, the sale is done in seconds. If not, the store orders it from the warehouse (the origin), serves the customer, and keeps extras on the shelf for the next person.

Why this design works

The cache sits at the same place as the load balancer, so there is no extra hop and no separate product to connect. The same front door that routes traffic, terminates encryption and applies security rules also serves cached content. This keeps the system simple, and it lets you add or change origins, rules and security without redesigning the delivery path.

Production example: one front door for many origins

Many companies use a single load balancer address for an entire site. Requests for picture and script paths are routed to a Cloud Storage bucket with caching on, requests for the application are routed to servers with caching only for public pages, and requests for private account pages are routed to servers with caching off. One domain, three behaviors, all at the same front door.

IInternal Working: What Happens Under the Hood

This is the part many tutorials skip. Knowing it explains why Cloud CDN behaves the way it does.

Step 1: finding the nearest edge

When a user types your address, DNS returns one IP address belonging to your load balancer. That address is announced from many Google locations at once through anycast. The user’s request follows the internet’s normal routing to the closest location that announces it. From there, Google carries the traffic over its own private backbone, which is faster and steadier than the open internet for the long part of the trip.

Step 2: terminating the connection early

Setting up an encrypted connection takes several round trips. If these trips went all the way to your origin, the user would wait a long time. Instead, the connection ends at the nearby edge, so the setup round trips are short. Google’s front end also supports modern protocols, such as HTTP/2 and HTTP/3, which send many files over one connection and handle poor networks better. Good news for users on mobile networks, even before any caching happens.

Step 3: computing the cache key

Next, the request is turned into a cache key. By default, this is made of the protocol, host and full URL including the query string. You may customize it, for example to ignore tracking parameters in the address or to include a certain header. The key decides which stored copy, if any, answers this request.

Step 4: the cache lookup

Cloud CDN looks in the edge cache for an entry with that key. Three outcomes are possible.

1

Fresh hit

A copy exists and its lifetime has not ended. It is returned at once, and the origin never hears about the request.

2

Stale hit

A copy exists but its lifetime has ended. Depending on settings, Cloud CDN asks the origin whether the copy is still valid, or serves the old copy while it refreshes in the background.

3

Miss

No copy exists. Cloud CDN must fetch from the origin, which is called a cache fill.

Step 5: cache fill and tiered caching

On a miss, Cloud CDN does a cache fill: it requests the file from the origin, returns it to the user and, if the rules allow, stores it. Google caches in more than one layer. If the nearest edge does not have the file, it may first ask a larger cache elsewhere in Google’s network before bothering your origin. This arrangement is sometimes called tiered caching, and it means the origin sees fewer requests than a simple one-layer design would produce. The exact arrangement is managed by Google and may change.

Step 6: request collapsing

Imagine a popular new video is released and a thousand people ask for it in the same second, before any copy exists. A naive system would send a thousand identical requests to the origin. Cloud CDN can collapse these requests, which means it sends one request to the origin and makes the others wait for that one answer. This protects the origin from stampedes and is one reason CDNs help during sudden crowds.

Analogy

When a hundred people in an office all want the same report, one person goes to the archive to fetch it and photocopies it for everybody. The archive clerk sees one visitor, not one hundred.

Step 7: revalidation

When a cached copy goes stale, asking the origin to resend the whole file would waste bandwidth. Instead Cloud CDN can send a small conditional request that says, “I have the version labeled with this ETag. Has it changed?” If it has not, the origin replies with a tiny “not modified” message, and the copy becomes fresh again for another lifetime. This is cheap and fast, and it is a good reason to make your origin send proper ETag or Last-Modified headers.

Step 8: eviction

Caches have limited space. When room runs out, or when content has not been requested for a long time, old entries are removed to make space for newer ones. This is called eviction. It means that unpopular files may be dropped before their lifetime ends, so a rarely used file may need to be fetched from the origin again even when its TTL is long. Popular files tend to stay.

Why different users may see different results

Because there are many edge locations, and each keeps its own copies, a file may be cached in Mumbai but not yet in Frankfurt. The first person in each region to ask for a file after it is published is likely to get a miss, and later people get hits. This is why a CDN’s benefit grows with the number of repeat requests in each region.

i
Remember

The edge is the first hit, the larger cache is the second chance, and the origin is the last resort. Each layer exists to keep requests away from the next. Your job is to make as many requests as possible end early.

!
Common Trap

Do not test a CDN by loading a page once and judging the speed. The first request in each region is usually a miss and will be slower. Test with repeated requests, from several places, to see the true effect of caching.

Production example: software release day

When a popular program or game patch is released, millions of people may download the same file in hours. Without a CDN, the origin would serve millions of copies. With a CDN and request collapsing, the origin serves each file to the cache a few times, and the caches serve the rest. The release goes out smoothly and the origin bill stays small.

TThe Life of a Request and a Cached Object

Two stories matter in a CDN: the story of one request, and the story of one cached file as time passes.

The story of one request

Let us follow two requests for the same picture. The first arrives when no copy exists. The second arrives soon after.

sequenceDiagram
  participant B as Browser
  participant E as Google Edge and Load Balancer
  participant C as Cloud CDN Cache
  participant O as Origin
  B->>E: Request logo picture
  E->>C: Look up cache key
  C-->>E: Miss - no copy
  E->>O: Fetch logo picture
  O-->>E: Picture with Cache-Control one day
  E->>C: Store copy for one day
  E-->>B: Picture delivered - first visitor
  B->>E: Second visitor requests same picture
  E->>C: Look up cache key
  C-->>E: Hit - fresh copy found
  E-->>B: Picture delivered from cache
Figure 2: A miss followed by a hit. The first visitor pays the cost of the trip to the origin, and later visitors are served from the cache.

What the picture shows

The first browser asks for the logo. The edge computes the cache key and checks the cache. It finds nothing, so it fetches the logo from the origin. The origin sends the file along with a header saying it may be kept for one day. The edge stores a copy and also delivers the picture to the first visitor. When the second visitor asks, the cache finds the fresh copy and the origin is not involved at all. The second visitor’s answer comes from a place that may be a few kilometers away instead of thousands.

The story of a cached object

A cached copy lives through several stages.

1

Filled

The copy is stored after a cache fill. Its clock starts, based on the TTL from the origin headers or from your settings.

2

Fresh

While the TTL has not ended, every request for the same key is a hit, and the origin sees nothing.

3

Stale

After the TTL ends, the copy is old. Cloud CDN must either revalidate with the origin or, if you allow it, serve the old copy for a while longer as it refreshes.

4

Revalidated or replaced

If the origin says “not modified”, the copy becomes fresh again. If the file changed, the new version replaces the old one.

5

Invalidated or evicted

The copy may be removed early by an invalidation you request, or evicted because space is needed or because nobody asks for it.

Two clocks: the CDN and the browser

There are two caches between the origin and a person. The CDN keeps copies at the edge. The user’s own browser also keeps copies. Each has its own lifetime. Cloud CDN lets you set a client TTL, which controls how long browsers may keep the file, separately from the lifetime in the CDN. This matters a lot: you can invalidate the CDN copy, but you cannot reach into every person’s browser to erase theirs. A file that browsers keep for a year cannot be corrected quickly for people who already have it.

Analogy

Think of a newspaper. The printing house prints new copies each morning, and the newsstand keeps some (the CDN). Readers also keep yesterday’s paper on their table (the browser). If the printer makes a correction, the newsstand can swap its stack at once, but nobody can walk into every home and replace the paper on the table.

Different responses are treated differently

Cloud CDN mostly caches successful responses, such as “OK”, but it can also cache certain error and redirect responses for a short time, which is called negative caching. For example, caching a “not found” answer for a few minutes prevents a flood of requests for a missing file from reaching the origin repeatedly. You can set how long each kind of status code is cached. Check the current list of cacheable status codes in the documentation.

Partial requests and large files

Many large downloads and videos are fetched in pieces using byte range requests, where the client asks for only part of a file. Cloud CDN supports these, which makes it a good fit for large downloads, video and resuming interrupted downloads. Very large files may be stored in the cache in chunks.

!
Common Trap

People often set a long browser lifetime on a file that they later need to change, such as a script with a fixed name. Once browsers have cached it for a year, the old version stays on their devices. The safe fix is to put a version or fingerprint in the file name, so a new version has a new address.

Production example: fingerprinted assets

Modern web build tools rename files with a short code made from their content, such as app followed by a code and then the file type. When the content changes, the code changes, so the address changes. Sites then give these files a very long lifetime, since an address never points to different content. Updates appear instantly, because the page itself points to the new name.

OOrigins: Where Your Content Comes From

A CDN is only as good as the origin behind it. Cloud CDN supports several kinds of origins, each suited to different content.

Origin type 1: Cloud Storage buckets

The simplest origin is a Cloud Storage bucket holding static files such as images, videos, documents and whole static websites. You connect it through a backend bucket, and enable Cloud CDN on it. Because storage is durable and cheap, this is an excellent place for large files that rarely change. Access to the bucket must be arranged so that the CDN can read it. Google provides options for this, including making objects publicly readable or using more controlled access, and the details can change, so check the current documentation.

Origin type 2: Compute Engine virtual machines and GKE

Dynamic web applications often run on groups of virtual machines or on Kubernetes pods. These sit behind a backend service. Cloud CDN can cache the public, repeatable parts of their responses, such as product pages and API results that do not depend on the user, while private parts bypass the cache.

Origin type 3: Cloud Run and other serverless services

Serverless services connect to the load balancer through a serverless NEG. Cloud CDN can cache their responses too. This is a good combination, since cached responses mean fewer serverless invocations and a lower bill, as well as faster pages.

Origin type 4: external origins

Your content might live outside Google Cloud, such as in another cloud, in your own data center or on a partner’s server. An internet NEG lets the load balancer treat that server as a backend, identified by a name or address. Cloud CDN can then cache its responses. This is useful for gradual migrations, where you want a CDN in front of old servers before you move them.

flowchart LR
  USERS["Users"] --> LB["External Application Load Balancer with URL Map"]
  LB -->|"path: /static/*"| BB["Backend Bucket - CDN on"]
  LB -->|"path: /media/*"| BB2["Backend Bucket for large files - CDN on"]
  LB -->|"path: /api/public/*"| BS1["Backend Service - CDN on with short TTL"]
  LB -->|"path: /account/*"| BS2["Backend Service - CDN off"]
  LB -->|"path: /legacy/*"| NEG["Internet NEG - CDN on"]
  BB --> GCS1["Cloud Storage Bucket A"]
  BB2 --> GCS2["Cloud Storage Bucket B"]
  BS1 --> GKE["GKE Service"]
  BS2 --> VM["Compute Engine VMs"]
  NEG --> OLD["Server in Another Data Center"]
Figure 3: One front door, many origins. A URL map sends each path to the right backend, and caching is switched on or off for each backend separately.

URL maps: routing by path and host

The load balancer uses a URL map to decide where each request goes. It can send requests by host name, such as images.example.com, or by path, such as /static/. This allows one domain to mix origins. Because Cloud CDN is enabled per backend, URL maps are how you apply the right caching rules to the right content.

Choosing the origin for each kind of content

ContentGood originCaching approach
Images, fonts, style sheets, scriptsCloud Storage bucket, or the app itselfLong lifetime, fingerprinted names
Large downloads and videosCloud Storage bucketLong lifetime, byte range support
Public pages that change slowlyBackend service on VMs, GKE or Cloud RunShort lifetime, serve stale while refreshing
Public API resultsBackend serviceSeconds to minutes, careful cache keys
Private or personal pagesBackend serviceNo caching
Content on another cloud or data centerInternet NEGAs above, plus origin protection

Origin health and location

Backends in a backend service are checked by health checks, small repeated tests that ask, “Are you working?” Unhealthy backends receive no traffic. The placement of the origin matters too. When there is a cache miss, the fill travels from the origin to Google’s network. An origin in a region close to your main audience will fill caches faster, and a well-chosen region reduces cost.

Origin capacity

A CDN reduces origin load, but it does not remove it. Cache misses, revalidations and uncacheable requests still arrive. Size your origin for the miss traffic, plus the worst case of a cache that has been emptied or a sudden burst of requests for new content. Also plan for the cold start of a new region, where every first request is a miss.

Analogy

An origin is like the central warehouse behind a chain of shops. Even if the shops serve most customers from their shelves, the warehouse must still stock new items, restock the shelves and handle special orders. A warehouse that is too small will fail the day the shelves run empty.

i
Pro Tip

Split your content by behavior, not just by type. Put the files that never change into one backend with a long lifetime, the public pages that change often into another with a short lifetime, and the private content into a third with caching off. Separate backends make your rules simple, and mistakes less likely.

Production example: static site on a bucket

Many marketing sites, documentation sites and single-page applications are simply files. Teams place them in a Cloud Storage bucket, put a load balancer with Cloud CDN in front and use a managed certificate. The site is fast worldwide, needs no servers to patch and costs little, even at high traffic.

CCache Modes and Lifetimes (TTLs)

The cache mode is the most important single setting in Cloud CDN. It decides what gets cached, and for how long.

The three cache modes

Mode 1

Use origin headers

Cloud CDN caches only what the origin explicitly says may be cached, using headers such as Cache-Control. Without such headers, nothing is cached. This gives the origin full control.

Mode 2

Cache all static content

Cloud CDN automatically caches common static file types, such as images, scripts and style sheets, even if the origin sends no caching headers. It still respects headers that forbid caching, such as private and no-store.

Mode 3

Force cache all

Cloud CDN caches all successful responses, ignoring headers that would normally forbid caching. This is powerful and risky.

QuestionUse origin headersCache all staticForce cache all
Who decides what is cached?The origin, through headersCloud CDN by file type, with origin headers respectedCloud CDN for everything successful
Safe for mixed public and private content?Yes, if the origin sets headers correctlyUsually yes, since private headers are respectedNo, dangerous
Effort at the originNeeds correct headers on every responseLowLowest
Best forApps that already send good headersSites with static assets and lazy headersContent that is truly all public, such as a static bucket
!
Common Trap

Force cache all can cause a serious data leak if it is used on a backend that sometimes returns personal pages. A page made for one customer could be cached and then shown to the next. Use it only for backends that serve content that is truly the same for everyone, such as a bucket of public files.

The lifetime settings

Cloud CDN has several TTL settings. Names may vary slightly in tools, but the ideas are these.

  • Default TTL: the lifetime used when the origin gives no lifetime of its own. A typical default is one hour.
  • Maximum TTL: an upper limit. Even if the origin asks for a very long lifetime, Cloud CDN will not keep a copy longer than this. A typical default is one day.
  • Client TTL: the lifetime that browsers are told to use. It cannot be longer than the maximum TTL.

In some modes, you can also override the origin’s lifetime with your own value. That is useful if you cannot change the origin’s headers.

Serve stale content

Cloud CDN can be allowed to serve stale content. When a copy has just expired, instead of making the user wait while the cache fetches a fresh copy, Cloud CDN can serve the old copy straight away and refresh it in the background. It can also serve a stale copy if the origin is down or returns errors, for a limited extra time. This improves both speed and resilience, at the cost of occasionally showing slightly old content.

Analogy

Serving stale content is like a restaurant that hands you yesterday’s bread right away while the new batch is baking, instead of asking you to wait twenty minutes. Most customers do not mind, and nobody goes hungry if the oven breaks.

Negative caching

You can choose to cache certain error and not-found responses for a short time, such as a few minutes. This protects the origin from repeated requests for something that does not exist. Keep these lifetimes short, so that when the content is later published, users are not told “not found” for long.

Choosing lifetimes in practice

ContentSuggested lifetime in the CDNSuggested lifetime in browsers
Fingerprinted scripts, styles, fontsOne yearOne year
Product photos with versioned namesWeeks to monthsWeeks to months
Images with fixed names that may changeHours to a dayMinutes to hours
Public article and product pagesSeconds to minutes, plus serve staleSeconds to minutes
Public API resultsSecondsSeconds or none
Personal pages and cartsNot cachedNot cached
i
Pro Tip

Even a lifetime of a few seconds can be very powerful for popular public pages. If a page is requested one thousand times a second, a ten-second lifetime means the origin builds that page about once per ten seconds in each cache, instead of ten thousand times. Users see almost no staleness, and the origin load collapses.

Production example: micro-caching a busy page

A ticket-selling site has a high-traffic event page that is the same for everyone, but changes as tickets sell. The team gives it a lifetime of a few seconds. During an on-sale, thousands of visitors per second share a handful of cached copies, and the page stays accurate within seconds, while the booking system behind it stays calm.

CCache Keys: When Two Requests Are the Same

A cache key decides how many separate copies of a file exist. Getting it right is one of the most effective ways to raise your hit ratio.

The default cache key

By default, the cache key includes the protocol (HTTP or HTTPS), the host name and the full path with its query string. So a request for one address with one set of options is a different cache entry from the same address with different options. This is safe, but it can create many near-duplicate copies.

Query strings

A query string is the part of an address after a question mark, such as options for a search or tracking tags from an advertisement. Suppose a marketing link adds a different tracking code for every campaign and every user. The page is the same, but each address is different, so each request creates its own cache entry and nearly all are misses. The cure is to exclude parameters that do not change the content from the cache key, or to include only the parameters that do.

Analogy

Imagine a library that shelves a book separately for every reader’s library card number written on the cover slip. Thousands of copies of one book would fill the building, and nobody could find the real one. Removing the card number from the label puts all readers on the same single copy.

Headers and cookies in the key

Sometimes the response really does vary with a header or cookie. For example, a site may send a different page to mobile and desktop devices, or in different languages. You can include such a header in the cache key, so each version gets its own cached copy. Be careful: including a header with many different values, such as a user-agent string, creates an enormous number of separate copies and ruins the hit ratio. It is much better to include a small, clean value, such as “mobile” or “desktop”, prepared by a rule.

The Vary header

Servers can send a Vary header, which says that the response depends on certain request headers. Caches must then keep separate copies for each combination. Cloud CDN handles Vary in a limited way and gives you cache key controls as the main tool, so check the current documentation for which headers it supports and how.

Protocol and host in the key

You can choose whether the protocol and host name are part of the key. If your site serves the same files on several names, such as a main name and a regional name, and you want them to share cached copies, you may remove the host from the key. Do this only when the content is truly identical.

A cache key checklist

1

List what changes the response

Which parts of the request truly make the content different: path, language, device class, version?

2

Remove what does not

Tracking tags, session identifiers, timestamps and random numbers should not be in the key.

3

Keep variations small and clean

Prefer a small set of values, such as two device classes, rather than raw headers with endless values.

4

Measure the hit ratio

Watch the hit ratio before and after, and look at logs for the most common misses.

Personalization and caching

Many pages are mostly the same for everyone, with one small personal part, such as “Hello, Maya”. If the whole page is made on the server, you cannot cache it for everyone. A common solution is to cache the shared page and load the personal part separately, using a small request that bypasses the cache, or code that runs in the browser. This keeps the big, heavy part cached while the private part stays private.

!
Common Trap

Never remove from the cache key a value that really changes the content, such as a user identifier on a personal page, or a language code on a translated page. The result would be people seeing someone else’s page or the wrong language. If a value changes the response, it must be in the key, or the response must not be cached at all.

i
Pro Tip

Look at your logs for the most requested addresses that are misses. Very often you will find the same file requested with endless different query strings. Fixing the cache key for those few patterns can double a hit ratio in a day.

Production example: campaign links

A retailer runs email and social campaigns whose links carry tracking tags that differ for every recipient. Before tuning, every click was a cache miss, and the origin buckled on sale mornings. After removing the tracking tags from the cache key, all those clicks shared one copy of each page, and the hit ratio rose sharply.

WWhat Is Cacheable: Headers and Rules

Not every response may be cached. This chapter explains the headers and rules that decide it.

The Cache-Control header

The Cache-Control header is the main tool the origin uses to talk to caches. It contains directives, which are small instructions. The most useful are these.

Directive

public

Any cache, including a shared CDN, may keep this response.

Directive

private

Only the user’s own browser may keep it. Shared caches must not.

Directive

max-age

The number of seconds the copy is fresh, for browsers and caches alike.

Directive

s-maxage

The number of seconds the copy is fresh for shared caches such as a CDN, overriding max-age for them.

Directive

no-store

Do not save this response anywhere. Used for very sensitive data.

Directive

no-cache

A copy may be kept, but it must be checked with the origin before every use.

Other headers

  • Expires: an older way to give a date after which the copy is stale.
  • ETag: a label that identifies a version of the file, used for revalidation.
  • Last-Modified: the time the file last changed, also used for revalidation.
  • Vary: lists request headers that change the response.
  • Set-Cookie: sets a cookie in the browser. Responses that set cookies are normally not shared between users, so caches treat them with care, and you should avoid cookies on static content.

Using s-maxage for the CDN and max-age for browsers

A useful pattern is to give the CDN a long lifetime using s-maxage, and browsers a short one using max-age. Then you can keep content at the edge for an hour, while browsers check back every minute. When you change the content and invalidate the CDN, users see the update within a minute, instead of waiting for a long browser lifetime to end.

What Cloud CDN will usually cache

In general, Cloud CDN caches successful responses to simple read requests, which are the GET requests for files and pages. It does not cache requests that change things, such as POST requests used for forms and payments. It does not cache responses that the origin marks as private or no-store, unless you choose the force mode. It also has limits on object size and on the lifetimes it will keep, so check the current limits for large files.

Compression

Compressing text files, such as pages, scripts and style sheets, makes them much smaller and faster to send. Typically the origin compresses and sends the compressed version, and the CDN keeps and serves it. The client says which compression it can handle through a header, and the cache may keep separate copies for different compression types. Cloud CDN has features related to compression, and the details have changed over time, so check the current documentation. Do not compress files that are already compressed, such as most images and videos.

Protocols at the edge

The load balancer at the edge supports modern web protocols. HTTP/2 allows many files to travel on one connection at once. HTTP/3, built on a protocol called QUIC, is even better on poor and mobile networks, because a lost packet does not stall every file. These benefits apply even to responses that are not cached, since the connection to the user ends at the edge.

A short checklist for cacheable responses

1

Is it a simple read?

Only GET-style requests are good candidates.

2

Is it the same for everyone?

If not, it must not be cached for everyone.

3

Does it have a clear lifetime?

Set Cache-Control with public and a sensible lifetime.

4

Does it set cookies?

Remove cookies from static and public responses.

5

Can it be revalidated?

Send an ETag or a Last-Modified header, so stale copies can be refreshed cheaply.

!
Common Trap

A very common reason why nothing is cached is that the application sends a cookie, or a no-cache or private header, on every response, even on images and scripts. Frameworks often do this by default. Check the actual response headers for your static files, and fix them at the origin.

Production example: fixing a zero hit ratio

A team turns on Cloud CDN and sees almost no hits. Looking at the headers, they find that their application framework adds a session cookie and a private cache directive to every response, including pictures. After fixing the settings for the static paths, their hit ratio goes from near zero to over ninety percent, and the origin load falls to a fraction.

SSetting Up Cloud CDN Step by Step

This chapter walks through the setup in plain terms. The exact buttons and commands change over time, so follow the current documentation for the details, and use this chapter for the order of thinking.

What you need before you start

  • A Google Cloud project with billing enabled.
  • Content to serve, in a Cloud Storage bucket, on servers, on Cloud Run, or on an outside server.
  • A domain name that you control, so that you can point it at the load balancer, and a certificate for HTTPS. Google can create and renew a managed certificate for you.
  • Permissions to create load balancers and backends in the project.

The setup path

1

Prepare the origin

Put static files in a bucket or make sure your servers or Cloud Run service are ready. Make sure the origin sends sensible Cache-Control headers for each kind of content.

2

Create the backend

Create a backend bucket for storage, or a backend service for servers, a serverless NEG or an internet NEG. Attach health checks to services.

3

Enable Cloud CDN on the backend

Turn on Cloud CDN for that backend, choose a cache mode, and set default, maximum and client lifetimes.

4

Create the load balancer front end

Create the external Application Load Balancer with a URL map, a reserved global IP address, an HTTPS proxy and a managed certificate.

5

Point your domain at the load balancer

In DNS, create a record that points your site name to the load balancer’s IP address. Certificates may need some time to become active.

6

Test

Request a file twice and examine the response headers. A header showing the age of the copy, or logs showing a cache hit on the second request, proves that caching works.

7

Tune and monitor

Adjust cache keys and lifetimes, turn on logging, set alerts, and review the hit ratio weekly at first.

How to test that caching works

Request the same file twice from the same place, using a browser’s developer tools or a command line tool that shows response headers. On the second request, look for signs of a hit, such as an Age header, which tells you how many seconds the copy has been in the cache, and a faster response time. In the load balancer logs, each request records whether the cache was looked up and whether it was a hit. Also test from different regions or with a different network, because each edge location has its own cache.

Turning on logging

Enable request logging on the backend, with a sampling rate you can afford. A full record of every request is the most useful in the beginning, since it shows exactly which requests are hits or misses and why. After tuning, you may reduce the sampling to save on cost.

Custom response headers

At the backend, you can add custom headers to responses, such as headers showing the cache status for debugging, or security headers that tell browsers how to behave. You can also add custom request headers sent to the origin, for example to tell it the location of the user. Check the documentation for the variables that can be used in headers.

Safe rollout

  • Start with one low-risk path, such as pictures, and enable Cloud CDN there only.
  • Watch the logs and the hit ratio for a few days.
  • Extend to other static paths, then to public pages with short lifetimes.
  • Keep private paths uncached from the first day.
  • Keep a way back: you can disable Cloud CDN on a backend at any time, and traffic will simply flow to the origin.
Analogy

Rolling out a CDN is like opening new shop branches. You do not open fifty at once. You open one, learn how customers behave, fix problems with stock and signs, and then open more. Along the way, the main warehouse stays open, so you can always go back if a branch has a problem.

i
Pro Tip

Define the load balancer, backends and Cloud CDN settings as code, with a tool such as Terraform, and keep the code in version control. You get a record of every change, easy review by a second person and a quick way to rebuild or copy the setup for testing.

Production example: stage-by-stage adoption

A company adds Cloud CDN to its existing site over a month. Week one covers images. Week two adds scripts and styles with fingerprinted names. Week three adds the public article pages with a lifetime of one minute and serve-stale enabled. Private account pages are never cached. At every step they compare origin traffic, page speed and error rates before moving on.

PPerformance and Optimization

A CDN can make a site feel dramatically faster, but only when it is set up with care. This chapter shows what to measure and how to improve it.

The measures that matter

  • Cache hit ratio: the share of requests answered from the cache. Higher is better, but remember to watch the ratio by kind of content, since a high overall ratio can hide a low ratio on the important pages.
  • Byte hit ratio: the share of data, in bytes, served from the cache. This matters most for cost, since big files dominate the bill.
  • Time to first byte, often written TTFB: the time from the request until the first part of the answer arrives. A good CDN greatly reduces this for cached content.
  • Page load time and the user-focused measures built on it, such as how soon the main content appears.
  • Origin load: how many requests and how many bytes still reach your servers.

Ways to raise the hit ratio

Keys

Clean the cache key

Drop tracking parameters and other values that do not change the content.

Lifetimes

Lengthen lifetimes safely

Use fingerprinted names with very long lifetimes for files that never change in place.

Headers

Fix origin headers

Remove cookies and private directives from public and static responses.

Stale

Serve stale content

Allow slightly old copies while refreshing, so expired copies do not always cause a slow fill.

Micro-cache

Cache public pages briefly

Even a few seconds can remove most of the load from popular pages.

Paths

Separate content by behavior

Route static, public and private content to different backends with their own rules.

Ways to make cache hits faster and lighter

  • Compress text content such as pages, scripts and styles.
  • Use modern image formats and the right sizes for each device, so that users do not download a huge picture to show a small thumbnail.
  • Combine and minify scripts and styles where this makes sense, to reduce the number and size of files.
  • Use HTTP/2 and HTTP/3, which the load balancer supports, to send many files over one connection.
  • Use byte range requests for large files and video, so that players can jump and resume.

Ways to make misses faster

Misses cannot be avoided entirely, so make them cheap. Place the origin in a region close to most of your users and well connected to Google’s network. Make sure the origin responds quickly, with its own caches and an efficient database. Use serve-stale so that expired copies are refreshed in the background rather than making users wait. Warm the cache before a big event by requesting key files from several regions, so that the first real visitors get hits.

Cache warming and pre-positioning

Before a launch, you may warm the cache by requesting the most important files. Since each edge location has its own cache, warming covers only those you reach, so it helps most in the regions you can test from, and less elsewhere. For very large events, plan capacity assuming that the first requests in each region will be misses.

Large files and video

Large downloads and video put the most load on bandwidth. Cloud CDN supports byte ranges and caches large objects, subject to size limits. For video streaming, splitting the video into small segments, as in common streaming formats, makes caching efficient, because each segment is a small, shared file. For massive media workloads, Google offers Media CDN, which is designed for very high throughput and long-tail media libraries. Compare Cloud CDN and Media CDN against your needs before you decide.

Measuring from the real world

Synthetic tests from a few locations are useful, but real users see more varied conditions. Collect real user measurements, using tools built into browsers or analytics services, and compare regions and devices. Compare pages before and after changes, and watch the slowest group of users, since averages hide the people who suffer most.

A tuning routine

1

Measure the baseline

Record hit ratio, byte hit ratio, time to first byte and origin load, by path.

2

Find the biggest misses

Use logs to find the addresses that cause the most misses or the most origin bytes.

3

Fix one cause at a time

Cache keys, headers, lifetimes or origin speed, one change per step.

4

Measure again

Confirm the improvement and write down what worked.

Analogy

Tuning a CDN is like arranging goods in a convenience store. You put the items most people want on the front shelves (long lifetimes and clean keys), you keep the fridge stocked for rush hour (warming) and you make the back room efficient for the rare special orders (a fast origin).

!
Common Trap

Do not celebrate an overall hit ratio without looking deeper. A site might have a ninety-five percent ratio because of thousands of tiny image requests, while its heavy, slow pages are all misses. Break the numbers down by path and by bytes.

Production example: image-heavy catalog

An online catalog serves each product photo in several sizes. By adding the image size to the file name, giving each file a long lifetime, and cleaning tracking tags from the cache key, the catalog moved most of its image traffic to the cache. Pages loaded faster for shoppers on slow mobile connections, and the origin could be much smaller.

IInvalidation and Keeping Content Fresh

Caching makes things fast, but it risks showing old content. This chapter explains how to keep content fresh without giving up the speed.

Why freshness is a problem

Once a copy is in the cache, the origin no longer controls it until the lifetime ends. If you publish a correction, fix a mistake or remove a sensitive file, the cache may keep serving the old one. You need tools to change this.

Strategy 1: short lifetimes

The simplest approach is to give changeable content short lifetimes, such as minutes. The cost is more trips to the origin, and the benefit is that stale content disappears by itself soon. Combined with serve-stale and revalidation, short lifetimes keep both speed and reasonable freshness.

Strategy 2: versioned addresses

The best approach for static files is to change the address whenever the content changes, by putting a version or a content fingerprint in the file name. The old and new versions are then different cache entries. You never need to invalidate anything, because the page now points to the new address. This is the most reliable method, and it works for browsers as well as the CDN.

Strategy 3: invalidation

Cache invalidation is the command to remove cached copies. In Cloud CDN, you can invalidate by a path, such as one file, or by a pattern with a wildcard at the end, such as everything under a folder. You can also limit the invalidation to a host. Invalidation is not instant everywhere. It may take some minutes to take effect across the world. There are also limits on how often you may invalidate, so check the current limits.

Analogy

Invalidation is like a recall notice at a store chain. The head office tells every branch to pull a product from the shelf. It works, but it takes time to reach every shop, and it is better to avoid recalls by labeling each batch clearly in the first place, which is what versioned names do.

flowchart TD
  START["Content changed at origin"] --> Q1{"Is the file name versioned?"}
  Q1 -->|"Yes"| NEWURL["Publish new URL and update pages - no invalidation needed"]
  Q1 -->|"No"| Q2{"Can users wait for TTL to expire?"}
  Q2 -->|"Yes"| WAIT["Wait for the short TTL to end"]
  Q2 -->|"No"| INV["Request cache invalidation for the path"]
  INV --> BROW{"Browsers cached it too?"}
  BROW -->|"Yes - long client TTL"| STUCK["Some users still see old copy until browser TTL ends"]
  BROW -->|"No - short client TTL"| DONE["All users see the new content within minutes"]
Figure 4: Choosing how to refresh content. Versioned names avoid the problem, short lifetimes limit it, and invalidation is the tool for urgent cases.

Strategy 4: bypass for special requests

Sometimes you want one person, such as an editor previewing a change, to see the newest version without disturbing everyone else. Preview systems can send requests to a different address or with a special value in the key, which skips the shared cache copy. Design previews so that they are never cached for the public.

Emergency removal

If sensitive or illegal content is published by mistake, remove it from the origin first, then invalidate the path. Remember browsers and other copies outside your control, and consider the lifetimes you set. This is a strong reason to keep lifetimes sensible for content where mistakes are costly, rather than leaving everything cached for a year.

Staleness, on purpose

Some freshness is a choice. A news homepage may accept being a minute old. A stock price should not be. A product description can be an hour old, but a stock count on the checkout page cannot. Decide for each kind of content how old is too old, and set lifetimes to match.

Comparing the strategies

StrategySpeed of updateEffortBest for
Short lifetimesWithin the lifetimeLowPublic pages that change often
Versioned addressesImmediateMedium, needs build toolingScripts, styles, images, downloads
InvalidationMinutesMedium, with limitsUrgent fixes and removals
Serve stale with background refreshSoon after expiryLowPages where small delays are fine
i
Pro Tip

Give the HTML page itself a short lifetime and the files it points to a very long one. Then a new release only needs the page to be refreshed, which happens within minutes, while the heavy files are fetched once from new addresses and then cached for a long time.

!
Common Trap

Do not rely on invalidation as your normal way of releasing changes. It is slow to spread, it has limits, and it cannot clear browser copies. Teams that invalidate everything at every release often suffer from stale pages for some users and a sudden spike of origin load from the empty cache.

Production example: release without purging

A software company releases a new version of its web app several times a day. Its build tool gives every script and style a new fingerprint, and the main page has a lifetime of one minute. Each release needs no invalidation at all, and users get new versions within a minute, while old files stay cached harmlessly for people who are still on the old page.

SSecurity: Protecting Content and Origins

A CDN stands at the front of your system, so it is a natural place for security. It also introduces special risks that you must understand.

The shared responsibility model

Google secures its global network, its edge locations and the load balancing service. You are responsible for deciding what is cached, who may reach private content, how your origin is protected, and how your applications handle data. A mistake in cache settings can expose private data, even on a perfectly secure platform.

HTTPS everywhere

Use HTTPS for all traffic. The load balancer ends the secure connection at the edge, using a certificate. Google can create and renew a managed certificate for you. Redirect plain HTTP requests to HTTPS and choose modern protocol versions. You should also use encrypted connections between the load balancer and your origin where possible.

Never cache private data in a shared cache

The most serious CDN mistake is caching a response meant for one person and serving it to another. Prevent this in layers. Keep private content on separate backends with caching off. Mark private responses with the private or no-store directive. Avoid the force-cache mode on any backend that might return personal data. Test by logging in as two different users and checking that each sees only their own data.

Signed URLs and signed cookies

Sometimes content must be limited to certain people, such as paying customers or members, but you still want it served from the CDN for speed. Signed URLs and signed cookies solve this. Your application decides that a user may have the content, then creates a link or a cookie containing an expiry time and a signature made with a secret key. The edge checks the signature. If it is valid and not expired, the content is served from the cache. If not, the request is refused. The origin is not even asked.

sequenceDiagram
  participant U as Paying Customer
  participant A as Your Application
  participant E as Cloud CDN Edge
  participant O as Origin Bucket
  U->>A: Log in and request video
  A->>A: Check subscription
  A-->>U: Signed URL with expiry and signature
  U->>E: Request video using signed URL
  E->>E: Verify signature and expiry
  E->>E: Check cache
  E->>O: Fetch only if not cached
  O-->>E: Video content
  E-->>U: Video delivered
  U->>E: Request again after expiry
  E-->>U: Access denied
Figure 5: Signed URL flow. The application grants access, the edge checks the signature and expiry, and expired or forged links are refused.

What signed URLs protect, and what they do not

A signed URL proves that the application issued the link, until it expires. Anyone holding the link can use it, so it can be shared by the original user. Use short expiry times for valuable content, and use signed cookies or other controls for sessions where sharing is a concern. Keep the signing keys secret, store them in a safe place such as Secret Manager, rotate them regularly, and do not put them in source code.

Protecting the origin

If your origin can be reached directly from the internet, attackers can bypass the CDN and its protections, and hit the origin with floods or exploit weaknesses. Reduce this risk.

  • For Google Cloud origins, use firewall rules so that only the load balancer and its health checks can reach the servers.
  • For Cloud Storage origins, use the access options provided for backend buckets, rather than leaving a bucket fully open when it holds anything sensitive.
  • For external origins, allow only Google’s front-end addresses where practical, or use a secret header added by the load balancer, which the origin checks, so that requests not sent by your CDN are refused.
  • Do not publish the true address of your origin in public places such as DNS records.

Cloud Armor

Cloud Armor is Google’s web application firewall and protection service for attacks. It works at the same front door. It can block traffic from certain countries or addresses, apply rules against common web attacks and limit request rates. Some of its policies can also be applied at the edge, in front of the cache, so that blocked requests never use cache or origin resources. Check the current features and editions for what is available.

Protection from floods

Google’s front-end network is built to absorb large attacks, and a cache helps further, because a flood of requests for cached files is answered at the edge. Attacks that use random addresses to force cache misses are harder, because each is a unique request that goes to the origin. Rate limits, Cloud Armor rules and careful cache keys all help.

Hotlinking and abuse

Hotlinking is when another website embeds your pictures or files, and your CDN pays for the traffic. You can limit it using signed URLs, by checking where requests came from, or with Cloud Armor rules. Also be careful about hosting user-uploaded content on the same domain as your application, because uploaded files can contain harmful scripts. Use a separate domain for user content.

Security headers

You can add response headers that tell browsers to behave safely, for example to refuse to be shown inside other sites’ frames, or to always use HTTPS for your domain. These are set as custom response headers at the backend, or by the origin.

1

Encrypt

HTTPS everywhere, managed certificates and modern protocol settings.

2

Separate

Private content on backends with caching off, public content on cached backends.

3

Authorize

Signed URLs or cookies for protected content, with short expiry and safe key storage.

4

Shield the origin

Firewall rules, bucket access controls and secret headers, so the CDN is the only way in.

5

Filter and watch

Cloud Armor policies, rate limits, logging and alerts.

Analogy

A signed URL is like a theater ticket with a printed time and a hologram. The doorman does not need to phone the box office. He checks the hologram and the time, and lets you in or turns you away. If you give the ticket to a friend, the friend can use it too, so you keep the time window short for expensive shows.

!
Common Trap

Leaving the origin open to the whole internet is a common weakness. Attackers can find origin addresses through old DNS records or scans, and then bypass every protection at the CDN. Always lock the origin so that only the CDN path is allowed.

Production example: paid video and downloads

Subscription services and online courses serve large video files to paying members. They issue signed URLs with a short expiry after the member logs in, so videos are delivered from the CDN at full speed, but links stop working soon after they are copied or leaked.

HHigh Availability and Reliability

A CDN stands in front of everything. It must stay up, and it can also help your origin stay up.

What availability means

Availability is the share of time a service works. It is often written in “nines”. Ninety-nine point nine percent allows under nine hours of downtime a year, and ninety-nine point ninety-nine percent allows under an hour. Google publishes service level agreements, called SLAs, for its load balancing and Cloud CDN services. Read the current text for exact numbers and conditions.

Built-in resilience of the edge

Cloud CDN runs on Google’s global load balancing infrastructure, which is spread across many locations and does not depend on a single machine or a single site. If one location has trouble, traffic is routed to other nearby ones. You do not run or patch edge servers, and you do not manage failover between edge locations.

The CDN as a shield for the origin

The cache protects the origin in several ways. Most requests never reach it. Request collapsing prevents stampedes. And serve-stale lets the CDN continue to provide content for a limited time even if the origin is down or returns errors. For static content, this can turn an origin outage into a minor event, because users continue to receive cached files.

Analogy

If the central warehouse has a power cut, the local shops can keep selling from their shelves for a while. Customers may not even notice. The longer the shelves hold, the more time the warehouse has to recover.

Making the origin reliable too

The CDN cannot serve what it has never cached, and it cannot fix a permanently broken origin. Run the origin across several zones, using instance groups with health checks and autoscaling. For Cloud Storage origins, choose a location type, such as a multi-region or dual-region, that matches the durability and availability you need. For backend services, the load balancer can distribute traffic across several regions and fail over when a region is unhealthy.

Multi-region origins and failover

The global load balancer can route to backends in several regions. It sends users to the closest healthy one and shifts traffic away automatically if a region fails, subject to your capacity settings. With Cloud CDN on top, the cache fills from whichever backend is chosen, so the entire system benefits from regional redundancy.

Planning for a cold cache

Caches can be emptied by a large invalidation, a configuration change that alters cache keys, or a launch in a new region. A cold cache means every request is briefly a miss, and the origin must handle the full load. Plan capacity for this case, avoid big invalidations at busy times, and warm the cache before major events.

Handling errors well

Decide what users should see when the origin fails and nothing is cached. A friendly static error page, served from a bucket, is better than a raw error. You can configure the load balancer or the application to return such a page. Also, cache error responses for a very short time, to protect a struggling origin from being hammered by retries.

Design habits for reliable delivery

Habit 1

Enable serve-stale

Let the CDN serve slightly old content during origin problems.

Habit 2

Spread the origin

Use several zones or regions and health checks.

Habit 3

Plan for cold caches

Size the origin for the worst-case miss traffic and warm the cache before big events.

Habit 4

Prepare a fallback page

Have a simple static page ready for the day the origin is down.

Habit 5

Test failure

Practice taking the origin down in a test setup and watch what users see.

Habit 6

Alert on symptoms

Watch error rates and latency at the load balancer, not only machine health.

Production example: surviving an origin outage

A media site’s database fails for twenty minutes during a busy afternoon. Because its articles and images are cached and serve-stale is on, readers keep seeing pages, and only logins and new comments fail. The team repairs the database without the front page ever going dark.

MMonitoring, Logging and Metrics

You cannot improve what you cannot see. Monitoring turns a mysterious slow site into a clear picture.

The three kinds of signals

Metrics are numbers over time, such as requests per second. Logs are written records of events, such as each request and its result. Alerts are messages sent when something needs attention. Together they answer: Is something wrong? What went wrong? Who needs to act?

Request logs

The load balancer’s request logs, stored in Cloud Logging, record each request or a sample of requests. For Cloud CDN, they include whether the cache was consulted and whether the request was a hit, and information such as the response size, status code, latency, the address requested and the client’s region. These logs are the best tool for finding out why something is a miss.

Metrics in Cloud Monitoring

The load balancer and Cloud CDN report metrics, including request counts, bytes sent, response codes, latency and, for caching, counts and bytes of hits and misses. From these you can build charts of the cache hit ratio and the byte hit ratio, and compare them with origin traffic. Names can change, so use the metric list in the console.

What to watch

Caching

Hit ratio and byte hit ratio

Watch both overall and by path. Falling ratios often point to a change in headers or keys.

Origin

Origin requests and bytes

A sudden rise shows a cold cache, a bad deployment or an attack that forces misses.

Errors

Error codes

Watch the rates of client errors and server errors, and which paths cause them.

Speed

Latency

Compare latency for hits and misses, and by region.

Traffic

Requests and bandwidth

Detect spikes, drops and unusual patterns early.

Security

Blocked requests

Watch Cloud Armor results, denied signed URLs and unusual sources.

Using logs to find problems

  1. Filter for requests that were misses and sort by how often each address appears.
  2. Look for addresses that appear with many different query strings. This points to cache key problems.
  3. Look for popular addresses with short lifetimes, and ask whether they can safely be longer.
  4. Look for responses whose headers forbid caching, and ask whether that is correct.
  5. Look at large responses that are often misses, because they cost the most.

Exporting logs for analysis

For deeper analysis, you can send logs to BigQuery, Google’s data warehouse, and ask questions with SQL, such as “Which ten addresses caused the most origin bytes last week?”. This is powerful for cost and performance tuning, and for security investigations.

Alerts that help

Alert on things that matter to users and that a person can act on: a sharp fall in the hit ratio, a sudden rise of server errors, an increase in latency, or a sharp rise in origin traffic. Avoid alerts that fire constantly for small variations. Attach a short runbook to each alert, listing the first checks and the people to call.

Dashboards

Build a dashboard per site, with hit ratios, origin traffic, error rates, latency and bandwidth side by side. During a launch or an incident, everyone should look at the same picture.

Analogy

Monitoring a CDN is like watching a chain of shops through their sales reports. You see which shelves are always empty (misses), which items sell fastest (popular paths), where deliveries are late (slow origins) and which branches have odd activity (attacks). Without reports you only learn about trouble from angry customers.

Production example: spotting a bad release

After a release, a team sees the hit ratio fall from ninety percent to forty percent within minutes, and origin traffic triples. Logs show that the new version added a unique timestamp to every image address. They roll back, fix the code to use stable addresses, and the ratio recovers within the hour.

PPricing and Cost Control

A CDN can lower your bill or raise it, depending on how it is used. Understanding the pricing parts is the first step to controlling it.

Per GB
data served from the cache to users is billed by volume and region
Per request
cache lookups are billed per number of requests
Per GB fill
data pulled from the origin into the cache is billed too

What you pay for

  • Cache egress: data delivered from the cache to users, charged per gigabyte. The price depends on the region where the user is, and tends to be lower with higher volume.
  • Cache fill: data moved from the origin into the cache on misses, charged per gigabyte, often depending on the distance between origin and cache.
  • Cache lookup requests: a small charge per number of requests that check the cache, usually priced per ten thousand requests.
  • Invalidation requests: after a free allowance, each invalidation may carry a charge.
  • Load balancer costs: the forwarding rules and the data processed by the load balancer.
  • Origin costs: compute, storage and the egress of data from the origin for misses, and for traffic that never enters the cache.
  • Security and logging: Cloud Armor, logging and monitoring have their own prices.

Prices change and differ by region and volume. Always read the current Cloud CDN and load balancing pricing pages, and use the pricing calculator with your own traffic numbers.

How a CDN can reduce the bill

Without a CDN, all data leaves your origin, and you pay origin egress for every byte. With a CDN, most bytes are served from the cache, and only the smaller cache fill traffic comes from the origin. The price per gigabyte for cache egress can be lower than the normal internet egress price from a virtual machine or a bucket, and the origin itself can be smaller. For content that is requested many times, the saving can be large.

How a CDN can raise the bill

Risk 1

Low hit ratio

You pay for lookups and fills, and still pay for the origin when most requests are misses.

Risk 2

Caching rarely requested content

Large, rarely repeated files cost fill traffic without ever paying back through hits.

Risk 3

Frequent invalidations

Invalidating everything often empties the cache and causes both charges and a cold-cache spike.

Risk 4

Attack or abuse traffic

Floods, scrapers and hotlinking can drive up request and egress charges.

Ways to save money

  1. Raise the hit ratio with clean cache keys and good lifetimes. This reduces fills and origin costs.
  2. Compress text content and use efficient image and video formats to cut bytes.
  3. Use versioned addresses instead of frequent invalidation.
  4. Place the origin wisely, in a region that is close to your caches and users, to reduce fill costs.
  5. Block abuse with Cloud Armor, signed URLs and rate limits.
  6. Control log volume by sampling, since logging every request on a high-traffic site can cost a great deal.
  7. Review the content mix. Large files that nobody requests twice might be better served directly.
  8. Set budgets and alerts on the project so unusual traffic is noticed early.
  9. Compare options such as Media CDN for very heavy media delivery, or committed spending agreements when traffic is steady and large.

A simple cost thought experiment

Suppose a site serves one hundred terabytes a month, and ninety percent of the bytes are cache hits. Only ten terabytes are filled from the origin. The origin sends ten terabytes instead of one hundred, and needs far less compute and bandwidth. If the hit ratio falls to fifty percent, the origin sends fifty terabytes, five times more, and the bill and the load grow accordingly. A few points of hit ratio change the bill a lot, which is why tuning pays for itself.

Analogy

A CDN is like a delivery contract with local drivers. You pay each driver per parcel, and you pay the factory only for restocking the local depots. If most parcels are already in the depot, you save a great deal of long-distance shipping. If nearly every parcel must be shipped from the factory anyway, you pay both the depot and the factory.

i
Pro Tip

Do not guess at the cost. Send a sample of your real traffic through a test setup for a week, read the bill by category, and extend the numbers to full traffic. The mix of small files, big files and region matters more than any rule of thumb.

Production example: trimming the bill by fixing keys

A website notices that its CDN bill is much higher than expected. The logs show that image requests carry a random value at the end of each address, so almost none are hits. After removing that value from the cache key and fixing the code that added it, the hit ratio jumps, the origin traffic drops and the monthly bill falls significantly.

DDesign Patterns and Anti-patterns

A pattern is a proven way to solve a common problem. An anti-pattern looks reasonable but causes pain later.

Patterns that work

Pattern

Static site on a bucket

Files live in Cloud Storage, a load balancer with Cloud CDN serves them worldwide, and no servers need patching.

Pattern

Immutable, fingerprinted assets

File names change when content changes, so they can be cached for a year and never need invalidation.

Pattern

Short page, long assets

The HTML page has a short lifetime and points to long-lived files, so releases appear in minutes.

Pattern

Micro-caching

Busy public pages are cached for a few seconds, which removes most of the origin load with almost no staleness.

Pattern

Separate backends by behavior

Static, public-dynamic and private paths are routed to different backends with different cache rules.

Pattern

Signed access for protected media

The application issues short-lived signed URLs, so paid content is delivered from the edge at full speed.

Pattern

Serve stale for resilience

Allowing slightly old content during refresh and origin trouble keeps sites available.

Pattern

Shielded origin

The origin accepts traffic only from the load balancer, so the CDN is the single, protected way in.

Analogy

Fingerprinted assets are like printing the edition number on every textbook. A new edition has a new number, so nobody confuses it with the old, and schools can keep old books in stock without worry. There is no need to run around collecting old copies when a new one comes out.

Anti-patterns to avoid

ANTI-PATTERN 01Avoid
What it looks like

The team turns on the force-cache-all mode for the whole site, including pages that show account details and shopping carts.

Why it hurts

Personal pages can be cached and then shown to other users. This is a serious privacy breach, and it can happen silently.

What to do instead

Keep private content on separate backends with caching off, mark private responses clearly and use forced caching only for backends that hold purely public content.

ANTI-PATTERN 02Avoid
What it looks like

Static files have fixed names and a one-year lifetime, and the team releases changes by hoping users will refresh.

Why it hurts

Browsers keep old copies for a year, so many users see broken or outdated pages after a release, and nobody can reach into their devices to fix it.

What to do instead

Put a version or fingerprint in the file name, or use short browser lifetimes for files that must keep their names.

ANTI-PATTERN 03Avoid
What it looks like

Every deployment ends with a full invalidation of the whole site.

Why it hurts

The cache is emptied, so the next minutes see all traffic hit the origin, which can slow or crash it. Invalidation also takes time to spread and may be rate limited.

What to do instead

Use versioned addresses and short page lifetimes, and keep invalidation for emergencies and for specific paths.

ANTI-PATTERN 04Avoid
What it looks like

The cache key includes the complete query string, all cookies and the full user-agent string.

Why it hurts

Nearly every request creates a unique key. The hit ratio is close to zero, so you pay for the CDN and still hit the origin for everything.

What to do instead

Include only values that truly change the content, and reduce noisy values to a few clean categories.

ANTI-PATTERN 05Avoid
What it looks like

The origin is directly reachable from the internet, and its address appears in old DNS records.

Why it hurts

Attackers and scrapers can skip the CDN and its security rules, and flood or probe the origin directly.

What to do instead

Allow only the load balancer to reach the origin, use secret headers or access controls, and remove old public records.

ANTI-PATTERN 06Avoid
What it looks like

User-uploaded files are served from the same domain as the main application, with the CDN in front and caching forced on.

Why it hurts

Harmful uploaded files can run in the context of your site. Wrong cache settings may also leak files meant for one user.

What to do instead

Use a separate domain for user content, validate and scan uploads, and use signed URLs for private uploads.

BBest Practices and Common Mistakes

This chapter gathers the habits of teams that run CDNs well, and the mistakes of those who learned the hard way.

Best practices: planning

  • List your content by behavior: never changes, changes slowly, changes often, personal. Decide lifetimes for each group before you start.
  • Check which load balancer types, origins and features Cloud CDN supports today, and confirm limits such as object sizes and invalidation rates.
  • Use a separate domain or path for static content, so rules are simple and cookies do not leak onto static files.
  • Choose the origin region near your largest audience.
  • Define the load balancer, backends and CDN settings as code, and keep them in version control.

Best practices: caching

  • Set explicit Cache-Control headers at the origin, with public, a lifetime and, for shared caches, s-maxage.
  • Use fingerprinted names for static files and very long lifetimes.
  • Give changeable pages short lifetimes and enable serve-stale.
  • Clean the cache key of tracking tags and session values.
  • Do not send cookies on static content.
  • Keep private content on backends with caching off.

Best practices: security

  • Use HTTPS everywhere with managed certificates.
  • Use signed URLs or cookies for protected content, with short expiry, and keep keys in Secret Manager.
  • Lock the origin so only the load balancer can reach it.
  • Use Cloud Armor for filtering and rate limiting at the front door.
  • Serve user-uploaded content from a separate domain.

Best practices: operations

  • Turn on logging from the start, and review the top misses weekly.
  • Alert on hit ratio drops, error spikes and origin traffic jumps.
  • Warm caches before big events, and size the origin for cold-cache traffic.
  • Test with a second user account to prove that private data is not shared.
  • Review cost by category every month, and set budgets and alerts.

Common mistakes

MistakeWhat goes wrongFix
Assuming Cloud CDN works without a load balancerNothing to enable, confusion at setupCreate an external Application Load Balancer first
Forcing cache on mixed contentPrivate pages shown to the wrong userSeparate backends, never force on private data
Cookies and private headers on static filesNothing gets cachedFix framework settings for static paths
Random values in addressesEvery request is a missRemove them from addresses or from the cache key
Long browser lifetime on fixed namesUsers stuck with old filesFingerprint names or shorten client lifetimes
Invalidating everything on every releaseCold cache, origin overloadVersioned addresses, targeted invalidation
Testing once from one locationFalse conclusions, because first requests are missesRepeat tests from several places
Open originAttackers bypass the CDNAllow only the load balancer
Ignoring logsHidden problems, wasted costReview misses and costs regularly
Caching huge, rarely reused filesFill costs without hitsMeasure byte hit ratio, adjust what is cached
i
Pro Tip

Before launching, ask four questions. What happens if the origin goes down for ten minutes? What happens if a private page is cached by mistake? How will a wrong file be removed quickly? What will the bill be at ten times the traffic? If you cannot answer all four, you are not ready.

Cache what is the same for everyone, protect what is not, and always know how to take back what you published.

AAdopting Cloud CDN and Moving from Another CDN

Most teams do not begin with a blank slate. They have a site that already runs, sometimes behind another CDN. This chapter explains a calm way to adopt Cloud CDN.

Starting from no CDN

If your site currently serves everything from its own servers, adopting Cloud CDN is mostly a matter of putting a load balancer in front and enabling caching for the safest content first. The steps in the setup chapter apply. The key habit is to begin with static files, learn from the logs and extend step by step.

Starting from another CDN

Many companies use another CDN, for example Amazon CloudFront, Akamai, Cloudflare, Fastly or Azure Front Door, and consider Cloud CDN because they have moved to Google Cloud, want one bill, or want to use Google’s load balancing. Moving requires care, because the new service differs in details such as how cache keys, headers and rules are configured.

A safe migration path

1

Inventory the current behavior

Write down every rule in the current CDN: lifetimes, cache keys, redirects, header changes, security rules, signed URL schemes and special paths.

2

Map each rule to Cloud CDN and the load balancer

Decide which settings become cache modes, lifetimes, cache keys, URL map rules, custom headers or Cloud Armor policies. Note any features that have no exact match.

3

Build a parallel setup

Create the load balancer, backends and Cloud CDN settings on a test domain name, without touching live traffic.

4

Compare behavior

Request the same addresses through both CDNs and compare headers, status codes, lifetimes and content. Test signed URLs, redirects and error pages.

5

Shift a small share of traffic

Use DNS controls to send a small percentage of users to the new setup. Watch errors, latency, hit ratio and origin load.

6

Increase gradually

Raise the share in steps, such as ten, thirty, sixty and a hundred percent, pausing at each step to review.

7

Keep the old path for a while

Leave the old CDN configured for a few weeks as a fallback. Lower DNS lifetimes beforehand, so you can switch back quickly.

Analogy

Changing CDNs is like changing the delivery company for a busy shop. You first learn all the special instructions the old company followed, such as which customers need a signature and which parcels are fragile. You then test the new company with a few deliveries, and only when everything is right do you hand over the full route.

Things that surprise teams

  • Cold caches. The new CDN starts empty. When traffic moves, the origin must handle a burst of misses. Shift traffic gradually and warm important files.
  • Header differences. Each CDN adds and removes headers differently. Applications that depend on special headers, such as the client’s address or country, must be checked.
  • Cache key differences. Defaults differ. Test that query strings, cookies and headers are handled the way you expect.
  • Signed URL formats. Different providers use different signing schemes. Links already shared may stop working, so plan a period when both are accepted, or issue new links.
  • Certificates and DNS. Provision certificates before the switch, and lower the DNS lifetime in advance.
  • Edge logic. If you used code running at the edge of the old CDN, you will need to move that logic to the origin, the load balancer rules or another service.
  • Cost differences. Compare pricing structures using real traffic, because per-request and per-gigabyte charges differ.

Testing before and after

Keep a list of important addresses, including home pages, popular articles, large downloads, protected content and error cases. Run the list through the old and the new setup, and compare status codes, headers, sizes and timings. Repeat after each stage of the migration. Add checks for cache behavior, such as whether the second request is a hit.

After the move

Review the hit ratio, latency and origin load at the end of the first week. Compare the bill with the forecast. Tune cache keys and lifetimes. Retire the old CDN configuration only when you are sure the new one is stable, and write down the lessons learned.

i
Pro Tip

Make the switching mechanism the first thing you test. If the only way to go back is a long DNS change, you are not really safe. Reduce DNS lifetimes in advance and practice moving a small amount of traffic back and forth.

Production example: moving in stages

A company moving its web platform to Google Cloud starts with its image and script domain, which has simple rules, and shifts it to Cloud CDN first. After a month of stable results, it moves the main site’s public pages, then finally the paid video library, which needs a signed URL scheme and the longest testing.

RReal-World and Industry Examples

Let us look at the kinds of work that content delivery networks carry every day. Companies seldom publish detailed designs, so these examples describe typical patterns in each industry.

E-commerce and retail

Online shops serve product photos in many sizes, style sheets, scripts and public catalog pages to shoppers worldwide. They cache pictures and assets for a long time, cache category and product pages for short periods, and keep carts, checkout and accounts uncached. On big sale days, the CDN absorbs most of the traffic and the checkout system is left with the work only it can do.

News and media publishing

Publishers face sharp spikes when a story breaks. A front page with a lifetime of seconds or minutes, plus serve-stale, lets millions of readers share a few cached copies. Images and videos are cached for long periods, and the editorial system behind them stays calm.

Video and audio streaming

Streaming services split video into small segments, which the CDN caches and serves from nearby locations. Popular titles stay in caches and rarely reach the origin. Paid libraries use signed URLs or cookies, so only subscribers can fetch segments. Very large catalogs may consider Media CDN for the heaviest workloads.

Gaming and software distribution

Game studios and software makers release large patches and installers that millions of people download in a short time. Request collapsing and caching mean the origin sends each file to the caches only a few times. Players get fast downloads that resume if interrupted, using byte ranges.

Software as a service

Business web applications serve a large bundle of scripts, styles and images that is the same for every customer, while the data is private. They cache the bundle at the edge with fingerprinted names, so even a customer on the other side of the world loads the interface quickly, and only the small data requests reach the servers.

Education and online courses

Course platforms serve lecture videos, slides and documents. The material is large and often repeated, so it fits a CDN. Members receive signed links after login, which expire soon, and popular courses are served mostly from caches during exam seasons.

Public sector and information sites

Government and information sites face unpredictable surges during emergencies and announcements. A CDN with a static, cached version of key pages protects the origin, keeps important information available and keeps costs steady during surges.

What these stories have in common

Every example shares the same habits. Content that is the same for everyone is cached close to users, with lifetimes matched to how fast it changes. Files get versioned names, so updates are clean. Private content is kept separate or protected with signed access. The origin is shielded and sized for the misses. Logs and dashboards show hit ratios and costs. The industries differ, but the design habits are the same.

i
Note

These examples describe common industry patterns rather than specific company designs. Your own design should always start from your own content, your own audience and your own tolerance for risk.

FFrequently Asked Questions

Short, direct answers to questions that beginners ask most often.

Q1What is Cloud CDN in one sentence?
Cloud CDN is Google Cloud’s content delivery network, which caches your content at Google’s edge locations around the world so users receive it from a nearby place, faster and with less load on your servers.
Q2Do I need a load balancer to use Cloud CDN?
Yes. Cloud CDN is enabled on the backends of Google’s external Application Load Balancer. You first create the load balancer, then enable Cloud CDN on the backend service or backend bucket. Check the documentation for the load balancer types currently supported.
Q3What can I use as an origin?
Cloud Storage buckets, groups of Compute Engine virtual machines, Kubernetes services, serverless services such as Cloud Run through serverless NEGs, and external servers through internet NEGs. Check current documentation for details and limits.
Q4What are the cache modes?
One mode follows the origin’s caching headers. Another caches common static file types automatically while still respecting headers that forbid caching. The strongest mode caches nearly all successful responses regardless of headers, and should be used only for content that is truly public.
Q5What is a cache hit ratio and what is a good value?
It is the share of requests answered from the cache. A good value depends on the content. Mostly static sites can reach ninety percent or more, while sites with lots of dynamic content will be lower. Watch the ratio by path, and by bytes as well as requests.
Q6Why is nothing being cached?
Common reasons are that the origin sends private, no-store or no-cache headers, or sets cookies on every response, that the cache mode is set to follow headers and none are present, that the request is not a simple read, or that the cache key contains values that make every request unique. Check the actual response headers and the logs.
Q7How do I update a file that is already cached?
The best way is to change its address with a version or fingerprint. You can also wait for the lifetime to end, or request an invalidation of the path. Remember that browsers may keep their own copies according to the client lifetime.
Q8How long does invalidation take?
It is not instant everywhere and can take some minutes to spread across the network, and there are limits on how often you may invalidate. Avoid relying on invalidation for regular releases.
Q9Can Cloud CDN protect private or paid content?
Yes, using signed URLs or signed cookies. Your application issues a link or cookie with a signature and expiry time, and the edge verifies it before serving content, which can still come from the cache. Keep the signing keys secret and the expiry short.
Q10Can personal pages be cached?
Not in a shared cache. Pages that differ for each person must not be cached for everyone. A common pattern is to cache the shared part of a page and load the personal part with a separate request that bypasses the cache.
Q11What is serve stale?
It lets Cloud CDN serve an expired copy while it refreshes the content in the background, and keep serving old copies for a limited time if the origin is failing. It improves speed and resilience, at the cost of occasionally showing slightly old content.
Q12Does Cloud CDN support large files and video?
Yes, including byte range requests, subject to size limits that you should check in the documentation. For very large media delivery, compare Cloud CDN with Media CDN, which is designed for such workloads.
Q13How is Cloud CDN priced?
Mainly by data served from the cache, by data filled from the origin into the cache, and by the number of cache lookup requests, plus the load balancer and origin costs. Prices vary by region and volume, so use the current pricing pages and calculator with your own traffic.
Q14Will Cloud CDN make my site faster even for uncached content?
Often yes, a little. The connection to the user ends at a nearby edge, which shortens setup, modern protocols such as HTTP/2 and HTTP/3 are supported, and traffic travels to the origin over Google’s backbone. The biggest gains still come from cache hits.
Q15How do I know if caching is working?
Request the same file twice and look at the headers and timing. An Age header and a faster second response point to a hit. Load balancer logs record whether each request was a cache hit, and Cloud Monitoring shows hit ratios over time.
Q16How is Cloud CDN similar to Amazon CloudFront or Azure Front Door?
All are content delivery networks that cache content near users and integrate with their cloud’s load balancing and security. The ideas of origins, cache keys, lifetimes, invalidation and signed access carry across, though names, features, limits and pricing differ.

SSummary and Key Takeaways

You have now seen Cloud CDN from the outside and from the inside. Here is the whole story in one place.

Cloud CDN keeps copies of your content at Google’s edge locations around the world and works through Google’s external Application Load Balancer. A user’s request reaches a nearby edge, the cache is checked with a key, and a fresh copy is returned at once, while a miss goes to your origin, fills the cache and serves the next person faster. You decide what is cached, for how long and for whom, and you protect private content, shield your origin and watch the hit ratio, the errors and the bill.

Key Takeaways

  • Cache what is the same for everyone. Static files and slowly changing public pages benefit most. Personal and real-time content should stay out of shared caches.
  • Know the front door. Cloud CDN is switched on at the external Application Load Balancer, for backend services and backend buckets, with origins on Google Cloud or outside it.
  • Control the cache. Choose the right cache mode, set lifetimes by content type, clean the cache key and let the origin send clear Cache-Control headers.
  • Update without pain. Use versioned file names and short page lifetimes, keep invalidation for emergencies, and remember browsers have their own copies.
  • Protect content and origin. Use HTTPS, signed URLs or cookies for protected media, Cloud Armor at the front door, and an origin that accepts traffic only from the load balancer.
  • Stay available. Enable serve-stale, spread the origin across zones or regions, plan for a cold cache and prepare a fallback page.
  • Measure and tune. Watch hit ratio and byte hit ratio by path, review logs for the top misses, control the cost with good keys and lifetimes, and test with repeated requests from several places.