# Cloud CDN and Traffic Management

> Chapter 8 of the Courseiva GOOGLE-PCNE curriculum — https://courseiva.com/learn/google-pcne/cloud-cdn-and-traffic-management

**Official objective:** 5.2 — Configure Cloud CDN and manage traffic routing

## Introduction

Exam objective 5.2 — Configure Cloud CDN and manage traffic routing — is about making your cloud applications fast and reliable for users all over the world, not just the ones next door. For the PCNE exam, you must understand that a Cloud CDN is not about building a faster server; it is about strategically placing thousands of tiny, temporary copies of your content closer to your users. This chapter will transform you from someone who thinks 'fast website = big server' to someone who thinks 'fast website = smart caching and routing'.

## The 24-Hour Bakery and the Local Fresh-Cookie Stand Analogy

Have you ever ordered a fresh, hot cookie from a delivery app, waited an hour, and then bitten into a cold, slightly stale disappointment? That is the problem of network distance and server load. Imagine a central 24-hour bakery in a city centre, the 'origin server', that bakes every single cookie for the entire city. This bakery is phenomenal, but it is only one building. Every time someone orders a cookie, the delivery driver has to travel from wherever they are, all the way to the city centre bakery, and then drive all the way back. This is slow for everyone, and on a busy day, the bakery gets swamped with orders, causing huge delays and some orders to be dropped entirely. 

 Now, imagine the bakery decides to solve this by setting up small, local fresh-cookie stands in every neighbourhood. These stands don't bake cookies from scratch. Instead, every morning, the central bakery bakes a huge batch of its most popular cookies and delivers them to each local stand. When you want a cookie, you walk to your neighbourhood stand. The cookie is already there, fresh from that morning's delivery. You get it instantly, and the central bakery never gets overwhelmed by a single queue of orders from everyone in the city. This is exactly the relationship between a cloud 'origin server' and 'Cloud CDN caches'. The local stand is the 'edge cache', the stock of cookies is 'cached content', and the system of stands is the 'Content Delivery Network' or CDN. The central bakery still bakes new recipes and handles special orders (uncached requests), but the vast majority of popular cookies are served locally, making the entire system fast and resilient.

## Core explanation

Cloud CDN and Traffic Management is a set of tools and techniques designed to solve a fundamental problem of the internet: distance and congestion. When a user in London requests data from a web server hosted in Sydney, that request must travel across oceans and through dozens of routers. This is called 'latency' — the time delay between a request being sent and a response being received. High latency makes websites feel sluggish. 

 A 'Cloud CDN' (Content Delivery Network) is a global network of servers, called 'edge points of presence' or 'edge locations'. These are not full application servers; they are special caching servers. Think of them as local libraries that hold copies of the most popular books (your website's images, videos, CSS files, and static HTML). When you enable Cloud CDN on a 'backend service' (your application or a storage bucket), Google Cloud automatically copies your content to its global network of over 100 edge locations. 

 Here is how it works step-by-step: 

 - A user types a URL into their browser. The browser performs a 'DNS lookup' (Domain Name System lookup) to find the server address. Cloud CDN uses an 'Anycast IP' address — a single IP address that routes the user to the nearest edge location automatically. 
 - The user's request hits the nearest edge location. This is the 'cache lookup' process. The edge server checks if it has a fresh copy of the requested content. 
 - 'Cache hit': The edge server has a fresh copy of the content. It immediately sends the data back to the user. This takes milliseconds. The user gets a fast experience. 
 - 'Cache miss': The edge server does not have the content, or the copy is stale (older than a set 'time-to-live' or TTL). The edge server then acts as a proxy, sending the request onward to your 'origin server' (your main application or Cloud Storage bucket). The origin server sends the response back to the edge server, which caches it for future requests and simultaneously delivers it to the user. 
 
 The 'cache key' is what determines if a cached copy is used. By default, the cache key is the full URL (including query parameters like ?id=123). You can configure the 'cache mode' to decide which content is cacheable (e.g., only static images, or also dynamic HTML for a few seconds). 

 'Traffic Management' refers to how you route user requests to your backend services. This is primarily done through 'Cloud Load Balancing' (CLB). CLB is the entry point. It is a fully distributed, software-defined service that distributes incoming traffic across multiple backends (virtual machine instances, container clusters, or Cloud Run services) in one or more regions. It is not a single hardware device but a global routing system. There are several types: 

 - 'Global External HTTP(S) Load Balancing': For web traffic. It terminates HTTP or HTTPS connections at the edge, close to the user, reducing latency. It supports 'content-based routing', where it can send requests for /images to one backend and /api to another. 
 - 'Regional External Load Balancing': For TCP or UDP traffic (non-HTTP) that needs to be in a specific region. 
 - 'Internal Load Balancing': For traffic within your Virtual Private Cloud (VPC) network, between your own services. 
 
 The key to Cloud CDN is that it sits behind your external HTTPS Load Balancer. You do not configure Cloud CDN directly on a VM; you configure it on a 'backend service' that is attached to a load balancer. The load balancer handles the routing and health checks, while Cloud CDN handles the caching. 

 Why does this exist? Before cloud and CDNs, every company either ran their own servers in a single data centre (slow for everyone far away) or paid a third-party CDN provider (complex and expensive for small businesses). Google Cloud CDN and CLB are 'managed services' — Google runs the infrastructure, and you pay only for the data you serve. This replaces the need for buying dedicated load balancer hardware or contracting expensive CDN contracts. For the PCNE exam, you must remember that Cloud CDN is a 'global cache' enabled on a 'backend service' of a 'global load balancer'.

## Real-world context

Imagine you work for a global e-commerce company called 'ShopSphere'. You manage a site that sells shoes to customers in the USA, Europe, and Asia. Your application servers are running in Google Cloud, in the us-central1 region (Iowa, USA). Initially, you have no CDN and no load balancing. Your single server handles everything. Customers in Tokyo experience 200 milliseconds of latency. The server is also overloaded during a flash sale. 

 Your task is to fix this using Cloud CDN and Traffic Management. Here is what you actually do, step by step: 

 1. Set up a managed instance group (MIG) in us-central1. This is a group of identical virtual machines that host your website. You need at least one group so the load balancer has something to send traffic to. 
 2. Configure a 'Global External HTTP(S) Load Balancer'. In the Google Cloud Console, you create a new load balancer. You configure a 'backend service' that references your MIG. This backend service is where you will eventually enable Cloud CDN. You also configure a 'frontend' which is the IP address and port (e.g., 443 for HTTPS) that users will connect to. 
 3. Enable Cloud CDN on the backend service. You navigate to the Cloud CDN section and enable it for the backend service. You set a default 'time-to-live' (TTL) of 1 hour for content. This means cached content can be served for up to an hour before the edge check for a new version. 
 4. Configure 'cache keys' and 'cache modes'. You look at your website. Product images (e.g., shoe-picture.jpg) never change. You configure the backend to cache all static objects with a 'force-cache' mode. Your product catalogue page is dynamic (prices change). You set a 'cache-hit' mode with a low TTL of 60 seconds. This means the first 60 seconds after a price change, some users might see the old price, but the load on your origin server drops dramatically. 
 5. Test with 'Cache Invalidation'. A product is recalled and you must remove its image from all edge caches immediately. You use the Google Cloud Console to 'invalidate' the cache by entering the specific URL path (e.g., /images/recalled-shoe.png). This tells all edge locations to delete that specific cached object on their next scheduled check. 
 6. Monitor with 'Cloud Monitoring' dashboards. You set up a dashboard to watch 'Cache Hit Ratio' (the percentage of requests served from cache). A healthy ratio is 80-95%. If it drops, you know your TTLs are too short or your cache keys are too specific, causing too many cache misses. 
 
 The result: Customers in Tokyo now hit an edge location in Tokyo. The product image is served in 5ms. The load on your origin server drops by 80%, as the MIG only handles page generation and user account data (which is not cacheable). The flash sale runs without crashes. You have successfully configured Cloud CDN and Traffic Management to solve a real business performance problem.

## Exam focus

The PCNE exam will test your ability to configure and troubleshoot Cloud CDN and Traffic Management. This is a heavily scenario-based section. You will not be asked to click through the UI; you will be asked to interpret a problem and choose the correct configuration. 

 Here are the exact concepts and traps you must memorise: 

 - 'Cache Hit vs Cache Miss' is fundamental. A question might describe a user getting a slow response even though Cloud CDN is enabled. The trap is assuming a cache miss is always a fault. It is not. A miss is normal for a first request. The correct answer is often about 'cache key' or 'cache mode' configuration. For example, if a user gets old content, the TTL is too long. If they get new content but it is slow, the cache key might be too specific (e.g., including a session ID in the cache key, which makes every request unique and uncacheable). 
 - 'Cache invalidation' is a hot topic. They will test that manual invalidation is an option but not for real-time updates. It is a tool for emergencies (e.g., removing an outdated price). The exam might ask: 'You need to immediately remove a malicious image from caches. What do you do?' Answer: Use `gcloud compute url-maps invalidate-cdn-cache` or the console 'Invalidate Cache' button. They will also test that you cannot set a TTL to zero to instantly expire everything — you invalidate specific paths. 
 - 'Signed URLs and Signed Cookies' are used to serve private content via CDN. A signed URL is a special URL with an expiration time and a cryptographic signature. Only users with that URL can access the content. The exam tests the difference: Signed URLs are for content linked directly (like a video in an email). Signed cookies are for content accessed within a website where many requests happen (e.g., a user browsing a premium PDF library). 
 - 'Load Balancer Types' are frequently confused. The key distinction for the exam: 'Global External HTTP(S) LB' is for web traffic and is the only one that supports Cloud CDN and 'Serverless NEGs' (connecting to Cloud Run). 'Regional External LB' is for non-HTTP TCP/UDP traffic. Do not pick a regional load balancer when you need Cloud CDN. 
 - 'Backend Service vs Target Proxy vs URL Map'. The URL Map is the routing rule (if path starts with /video, go to Backend A). The Target Proxy is the object that terminates HTTPS. The Backend Service defines the cache settings and the actual servers. The exam loves to ask: 'Which configuration object is associated with Cloud CDN settings?' Answer: The Backend Service. 
 - 'Google Cloud Armor' integration. Cloud Armor is a Web Application Firewall (WAF) and DDoS protection service. It can be attached to a load balancer. The exam might ask: 'How do you block traffic from a specific country?' Answer: Use Google Cloud Armor security policies on the load balancer. It does not block at the CDN level. 
 - 'Origin selection' for Cloud CDN. Cloud CDN can serve from Compute Engine instance groups, Cloud Storage buckets, or Cloud Run/App Engine via Serverless NEGs. The trap is that Cloud CDN does not support regional load balancers; it only works with global external HTTP(S) load balancers. 

 Memorise the difference between a 'cache hit' (fast) and 'cache hit ratio' (percentage). The exam will test the optimisation path: high latency + low hit ratio = adjust cache key or increase TTL; high latency + high hit ratio = origin server is the bottleneck (maybe need more instance group capacity).

## Step by step

1. **Create a Backend Service** — Start by defining a backend service in the Google Cloud Console or via the `gcloud compute backend-services create` command. This object holds references to your backend instances (like an Instance Group) and is where you will later enable Cloud CDN. Without this, there is nothing to cache traffic from.
2. **Create a Global External HTTP(S) Load Balancer** — Configure a load balancer with a URL map that directs traffic to your backend service. You must use the 'Global External HTTP(S)' type because Cloud CDN only works with global load balancers, not regional ones. This step creates the entry point for all user traffic.
3. **Enable Cloud CDN on the Backend Service** — Navigate to the Cloud CDN section in the console or use `gcloud compute backend-services update` with the `--enable-cdn` flag. Choose a 'Cache Mode' (e.g., 'Force Cache All Static Content' or 'Use Origin Headers'). This step activates the caching network at the edge locations.
4. **Configure Cache Keys and TTL** — Define how the CDN identifies and stores cached content. Set 'Cache Keys' to exclude query parameters that do not affect content (e.g., session IDs). Set a 'Default TTL' or let headers determine it. This step prevents cache fragmentation and ensures a high cache hit ratio.
5. **Test and Invalidate Cache (If Needed)** — After enabling, test from multiple geographical locations. Use `curl` or a browser to verify fast responses. If you need to remove stale content, use the 'Invalidate Cache' button in the console or the `gcloud compute url-maps invalidate-cdn-cache` command. This step is critical for maintaining content freshness.
6. **Monitor Cache Hit Ratio and Tune** — Use Cloud Monitoring dashboards to track 'Cache Hit Ratio'. If it is below 80%, adjust cache keys (remove unnecessary query parameters), increase TTLs, or verify that your origin sends proper Cache-Control headers. This ongoing step optimises performance and cost.

## Comparisons

### Global External HTTP(S) Load Balancer vs Regional External Load Balancer

**Global External HTTP(S) Load Balancer:**
- Supports Cloud CDN, allowing content caching at edge locations worldwide.
- Terminates HTTP/HTTPS traffic at the edge location closest to the user, reducing latency.
- Supports URL map-based content routing (e.g., /video to backend A, /api to backend B).

**Regional External Load Balancer:**
- Does not support Cloud CDN; it only routes TCP/UDP traffic to backends in a single region.
- Terminates traffic at a regional forwarding rule; user requests travel directly to the chosen region.
- Used for non-HTTP protocols like load balanced database connections or gaming servers.

### Signed URL vs Signed Cookie

**Signed URL:**
- A single URL with an embedded cryptographic signature and expiration time.
- Used for direct links to a single resource (e.g., a download link in an email).
- Configured on the backend service's CDN settings, generating URLs with `Cloud-CDN-Cookie` or query parameters.

**Signed Cookie:**
- A cookie set by the application that grants access to multiple protected resources within a domain.
- Used for browsing a website with many protected pages or files (e.g., a premium video library).
- Configured on the load balancer or backend service, allowing the browser to send the cookie with each request.

### Cache Hit vs Cache Miss

**Cache Hit:**
- The user's request is satisfied by an edge location without contacting the origin server.
- Results in very low latency (milliseconds) and zero load on the origin server.
- The cache hit ratio is a primary metric for CDN performance; higher is better.

**Cache Miss:**
- The edge location does not have a fresh copy of the content and must fetch it from the origin server.
- Results in higher latency (round-trip to origin) and increases load on the origin server.
- Cache misses are normal for first-time or uncached requests; a high miss ratio indicates poor configuration.

### Cloud CDN (Cache Configuration) vs Cache Invalidation

**Cloud CDN (Cache Configuration):**
- Ongoing configuration that controls which content is cached, for how long, and using which cache keys.
- Set once and automatically enforced; content expires based on TTL.
- Does not remove content immediately; it waits for the TTL to expire.

**Cache Invalidation:**
- An emergency manual action that immediately purges specific URL paths from all edge caches.
- Used when content must be removed before its TTL expires (e.g., a recalled product image).
- Can only invalidate specific paths (e.g., /images/recalled.jpg), not the entire cache.

### Backend Service with Cloud CDN vs Backend Service without Cloud CDN

**Backend Service with Cloud CDN:**
- Redirects traffic from the load balancer to the edge cache for static content before hitting the origin.
- Requires configuration of cache keys, TTL, and cache mode.
- Reduces origin server load and improves latency for global users.

**Backend Service without Cloud CDN:**
- Every request goes directly to the origin server, regardless of the content type.
- Simpler to configure (no cache settings), but slower and more expensive at scale.
- No support for signed URLs or signed cookies for CDN-based access control.

## Diagram

_Flow of a user request through a Global Load Balancer, showing the two possible paths: a cache hit (fast response from the edge) or a cache miss (request forwarded to the origin server)._

```mermaid
graph LR
    A[User Browser] --> B[Global External HTTP(S) Load Balancer]
    B --> C[Edge Location (Cache Hit)]
    B --> D[Edge Location (Cache Miss)]
    C --> E[Serves Cached Content]
    D --> F[Backend Service (Origin Server)]
    F --> B
    B --> A
```

## Common misconceptions

- **Misconception:** Cloud CDN speeds up my entire application, including dynamic user-specific data like shopping cart contents. **Reality:** Cloud CDN only caches content that is marked as cacheable (static files like images, CSS, JavaScript). Dynamic content (like a user's shopping cart or login state) is never cached unless you explicitly configure the application to serve it with 'Cache-Control: public' headers, which is rarely done because user-specific data should be private. (People think CDN is a magical 'make everything faster' button, but it is a caching service. Caching dynamic data would break the application (e.g., showing one user's cart to another user).)
- **Misconception:** Cloud CDN is a separate product that you set up independently from the load balancer. **Reality:** Cloud CDN is an optional feature that you enable on a backend service of a Global External HTTP(S) Load Balancer. You cannot create a Cloud CDN 'instance' by itself. It is always tied to a load balancer's backend configuration. (Google Cloud's console has a dedicated 'Cloud CDN' menu, which makes it look like a standalone product. It is actually a configuration toggle, not a separate resource.)
- **Misconception:** Setting a very short TTL (time-to-live) on my cache, like 1 second, will ensure my users always get the freshest content. **Reality:** Using a very short TTL defeats the purpose of a CDN. The edge cache will check the origin server almost every time, causing a cache miss on nearly every request. This increases load on the origin server and latency for the user. The correct approach is to set a moderate TTL (e.g., 1 hour) and use 'cache invalidation' to manually purge content when it changes urgently. (Beginners think 'freshness' is binary (fresh or not), but CDNs are about a trade-off between freshness and performance. They do not realise that invalidation is the tool for emergencies, not short TTLs.)
- **Misconception:** Cloud CDN caches content in a single location that is closest to my origin server (e.g., us-central1). **Reality:** Cloud CDN uses Google's global network of 100+ edge locations. Content is cached at the edge location closest to the user, not the origin. A user in London gets content from a London edge cache, regardless of whether the origin is in the USA or Australia. (People confuse the 'origin server' (where the data lives) with the 'edge cache' (where data is served from). They assume that because the origin is in one place, the cache must be there too.)
- **Misconception:** Enabling Cloud CDN automatically caches all content from my website with no additional configuration. **Reality:** Cloud CDN respects the HTTP 'Cache-Control' headers sent by your origin server (e.g., 'Cache-Control: public, max-age=3600'). If your application does not send these headers, or sends 'Cache-Control: private' or 'no-cache', Cloud CDN will not cache the content. You must also configure 'Cache Keys' and 'Cache Modes' in the backend service settings to control caching behaviour. (This misconception arises from comparing CDN to a simple browser cache. Browser caches are more aggressive. CDNs are designed to be configured by the developer to respect the origin's content policy. Beginners assume it is 'set and forget'.)

## Key takeaways

- Cloud CDN is not a separate product; it is a configuration feature enabled on a backend service of a Global External HTTP(S) Load Balancer.
- A cache hit is fast (content served from the edge), while a cache miss is slower (content fetched from the origin server), and the cache hit ratio is the key metric to monitor CDN effectiveness.
- Signed URLs and Signed Cookies are the two methods for serving private, authenticated content through a CDN without requiring user login.
- Cache invalidation is the tool for urgent content removal (e.g., removing a recalled product image) and is performed on a specific URL path, not on the entire cache.
- Cloud CDN only caches GET and HEAD HTTP methods; it does not cache POST, PUT, DELETE, or PATCH requests, because these are not idempotent read operations.
- The time-to-live (TTL) for cached content is determined by the Cache-Control headers from the origin server, which the CDN respects by default, or by an enforced TTL configured in the backend service.
- Google Cloud Armor security policies are attached to a load balancer to filter traffic before it reaches the CDN or origin backend, blocking malicious requests at the edge.

## FAQ

**Does Cloud CDN work with internal load balancers (within my VPC)?**

No. Cloud CDN only works with Global External HTTP(S) Load Balancers. Internal load balancers are for traffic within your private network and do not benefit from external edge caching.

**How do I make sure my users always see the absolute latest version of a file when using Cloud CDN?**

You cannot guarantee real-time freshness with caching. Instead, use a strategy: set a reasonable TTL (e.g., 1 hour), and when you need to update immediately, manually 'invalidate the cache' for that specific URL path. Alternatively, use versioned URLs (e.g., /image-v2.jpg) to bypass the old cached copy.

**Can I use Cloud CDN to serve content from a Cloud SQL database directly?**

No. Cloud CDN caches static files from a backend service (Compute Engine, Cloud Storage, App Engine, etc.). It does not cache database queries. To reduce database load, you would cache the output of your application (e.g., as a pre-rendered HTML page) and serve that through the CDN.

**What happens if my origin server goes down while Cloud CDN is enabled?**

The CDN will continue to serve cached content for requests that hit the cache. However, any new requests that cause a cache miss will fail because they cannot reach the origin. You must configure health checks on the load balancer to detect the outage and route traffic to a healthy backup backend if one exists.

**How do I enable Cloud CDN for a Cloud Storage bucket?**

You create a Global External HTTP(S) Load Balancer, create a backend service that points to your Cloud Storage bucket (using a Serverless NEG or directly as a backend), and then enable Cloud CDN on that backend service. The bucket must be globally accessible (public or via signed URLs).

**Is Cloud CDN secure? Can someone intercept the cached content?**

Cloud CDN supports HTTPS by using the load balancer's SSL/TLS certificate. Traffic between the user and the edge is encrypted. However, the content cached at the edge is stored in an encrypted form. You can also use 'Signed URLs' to restrict access to authorised users, adding an extra layer of security beyond HTTPS.

## Check your understanding

1. **Which type of Google Cloud Load Balancer is required to enable Cloud CDN?**

   Answer: A Global External HTTP(S) Load Balancer. Cloud CDN is an optional feature enabled on its backend service.

2. **What is the difference between a cache hit and a cache miss in Cloud CDN?**

   Answer: A cache hit means content was served from an edge location; a cache miss means the edge had to fetch the content from the origin server, causing higher latency.

3. **How do you immediately remove a specific cached file (e.g., an outdated product image) from all edge locations?**

   Answer: Use the 'Invalidate Cache' feature in the Cloud Console or the `gcloud compute url-maps invalidate-cdn-cache` command, specifying the URL path of the file.

4. **What caching mechanism should you use to serve private, paid video content through Cloud CDN without requiring users to log in?**

   Answer: Signed URLs or Signed Cookies, which provide time-limited, authenticated access to the cached content.

5. **True or False: Cloud CDN can be enabled directly on a Compute Engine virtual machine instance. Explain your answer.**

   Answer: False. Cloud CDN is enabled on a backend service of a Global External HTTP(S) Load Balancer, not directly on a VM instance.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/google-pcne/cloud-cdn-and-traffic-management
