Shielding
Under normal conditions, visitor requests reach your Fastly service at points of presence (POPs) in various regions, which in turn independently forward those requests to your origin servers. When Shielding is enabled, visitor requests from across the global network funnel through a single, designated shield POP instead. This ensures that all user traffic converges at a singular entry point before reaching your origin, which can reduce upstream load.
Shielding has significant benefits:
- Reduces origin load: reduces the volume of requests from Fastly to your origin servers
- Improves cache hit ratio (CHR): increases the probability of end user requests resulting in a cache
HIT(albeit potentially not from the first POP which handles the request) - Speeds up connections: reduces connection setup latency for
MISSandPASSrequests that must be served from origin (this feels counter-intuitive, but takes advantage of the fact that all Fastly POPs always have a pool of open connections to all other Fastly POPs, reducing the time required for costly multi-roundtrip handshakes).
Shielding is only applicable to requests that are forwarded to a backend. Shielding is not involved when the request is handled entirely at the edge, e.g., on a synthetic response or a static asset edge hit.
Enabling and disabling shielding
- CDN services
- Compute services
In CDN services, shielding may be enabled when adding or editing an origin server, and may be selected per-origin. If your origin servers are in different locations, it may make sense to choose different shields for each origin server. You can enable shielding via the web interface, or set the shield property of a Backend object when you create or modify it using the API or CLI. For example:
$ fastly backend create --name=app_server --address=192.168.123.123 --shield=amsterdam-nl --service-id=9yqrXWr5kfqroswtmxgQDz --version=latestSUCCESS: Created backend app_server (service 9yqrXWr5kfqroswtmxgQDz version 1)Each POP has a shield identifier. These are listed in the properties returned from the /pops API endpoint. For example, the POP in Amsterdam has the name AMS but a shield identifier of amsterdam-nl.
For more details, refer to choosing a shield location.
In Compute services, shielding is implemented programmatically using your language SDK's Shielding API. You choose a Fastly POP to be the designated shield POP for each origin your service shields—a choice you make based on geographical proximity to your origin servers and other network routing factors. Your application code then uses the API to learn whether it is currently running on that specific POP; if it isn’t, the API provides a secure tunnel to it. This tunnel behaves like a standard Backend, allowing the Compute service to seamlessly issue HTTP requests to the shield and manipulate or cache the resulting responses.
Each POP has a shield identifier. These are listed in the properties returned from the /pops API endpoint. For example, the POP in Amsterdam has the name AMS but a shield identifier of amsterdam-nl.
For more details, refer to choosing a shield location.
When building a resilient architecture, your service should always fail open rather than crashing, to avoid dropping visitor traffic with an unexpected HTTP 500 error. If a shield POP is unavailable due to an error in the shield configuration, a lookup error, or an unlikely temporary lapse in availability, your edge code should gracefully fall back to sending requests directly to your origin servers.
NOTE: Shielding APIs are not supported in Fastly Fiddle.
- Rust
- JavaScript
- Go
- C++
In a Compute service written in Rust, use the fastly::shielding module.
16789101112131415161718192021222324252627282930use fastly::shielding::Shield; // Obtain a reference to the shield POP // (will return None if this fails) let shield = Shield::new("amsterdam-nl") .inspect_err(|e| eprintln!("Unable to obtain reference to shield: {e:?}")) .ok();
// Filter out the shield if we are already running on it, // then extract the secure encrypted tunnel backend // (will return None if this fails) let tunnel = shield .filter(|s| !s.running_on()) .and_then(|s| s.encrypted_backend() .inspect_err(|e| eprintln!("Unable to obtain encrypted backend for shield: {e:?}")) .ok());
if let Some(tunnel) = tunnel { // If we have a tunnel to the shield POP, forward the request to the shield. // We will want to make considerations about caching here. Ok(req.send(tunnel)?) } else { // If we get here, we are either running on the shield POP, or shielding // initialization failed for any reason. // Forward the request directly to your origin. Ok(req.send("origin_backend")?) } In a Compute service written in JavaScript, use the fastly:shielding package.
14567891011121314151617181920212223242526272829303132333435363738394041import { Shield } from "fastly:shielding"; const req = event.request;
// Obtain a reference to the shield POP // (will return null if this fails) let shield = null; try { shield = new Shield('amsterdam-nl'); } catch (e) { // Shield configuration error, shield remains null console.warn('Unable to obtain reference to shield', e); }
// Filter out the shield if we are already running on it, // then extract the secure encrypted tunnel backend // (will return null if this fails) let tunnel = null; try { if (shield && !shield.runningOn()) { tunnel = shield.encryptedBackend(); } } catch (e) { // Encryption or platform error, tunnel remains null console.warn('Unable to obtain encrypted backend for shield', e); }
let response; if (tunnel) { // If we have a tunnel to the shield POP, forward the request to the shield. // We will want to make considerations about caching here. response = await fetch(req, { backend: tunnel }); } else { // If we get here, we are either running on the shield POP, or shielding // initialization failed for any reason. // Forward the request directly to your origin. response = await fetch(req, { backend: 'origin_backend' }); }
return response; In a Compute service written in Go, use the shielding package.
3891314151617181920212223242526272829303132333435363738394041424344454647 import ( "github.com/fastly/compute-sdk-go/shielding") // Obtain a reference to the shield POP var shield *shielding.Shield if s, err := shielding.ShieldFromName("amsterdam-nl"); err != nil { // Shield configuration error, shield remains nil fmt.Fprintln(os.Stderr, "Unable to obtain reference to shield:", err) } else { shield = s }
// Filter out the shield if we are already running on it, // then extract the secure encrypted tunnel backend var tunnel string if shield != nil && !shield.IsRunningOn() { if backendName, err := shield.Backend(nil); err != nil { // Encryption or platform error, tunnel remains empty fmt.Fprintln(os.Stderr, "Unable to obtain encrypted backend for shield:", err) } else { tunnel = backendName } }
var resp *fsthttp.Response var err error
if tunnel != "" { // If we have a tunnel to the shield POP, forward the request to the shield. // We will want to make considerations about caching here. resp, err = r.Send(ctx, tunnel) } else { // If we get here, we are either running on the shield POP, or shielding // initialization failed for any reason. // Forward the request directly to your origin. resp, err = r.Send(ctx, "origin_backend") }
Shielding is not available in this version of the Fastly Compute C++ SDK.
Effects of shielding
Enabling shielding on a Fastly service will create side effects that should be considered carefully.
Double execution
When shielding is enabled, your edge code typically executes twice: once at the edge POP where the visitor initially lands, and a second time at the designated shield POP. However, if the designated shield POP also happens to be the closest regional POP for that visitor, the request lands directly at the shield from the start. In this scenario, your edge code executes once, as the shield POP is the only step between the visitor and the origin servers.
When shielding is enabled, you must carefully choose where to modify your requests and responses. Because your code can run multiple times along a single request path, executing logic without consideration of the execution context can lead to redundant processing, duplicate headers, or issues like cache poisoning (refer to caching implications). To keep your application deterministic, it is best to separate origin-bound operations, which are best handled directly at the shield POP, from client-facing operations, which should execute only at the client-connected POP.
- CDN services
- Compute services
In CDN services, Fastly's infrastructure manages the routing behind the scenes, running your code twice implicitly.
Targeting the request to the origin
req.backend.is_origin and req.backend.is_shield tell you whether a backend request made from the current POP will go to your origin server or to a shield POP, which is usually important when manipulating a request. fastly.ff.visits_this_service tells you whether the current POP is acting as a shield POP or not, which is more often important when manipulating a response.
For example, use req.backend.is_origin to determine whether to modify request headers before forwarding a request to an origin:
if (req.backend.is_origin) { set req.http.host = "example.com";}Targeting the response to the client
But use fastly.ff.visits_this_service to determine whether to modify response headers before delivering a response:
if (fastly.ff.visits_this_service == 0) { set resp.http.Cache-Control = "no-store, private";}In Compute services, your code explicitly triggers double execution by sending a request to the shield POP's encrypted tunnel backend as appropriate.
Targeting the request to the origin
For best results, ensure that any request manipulation intended for your origin servers only happens at the step the request is transitioning from the shield POP to your origin servers.
Calling shield.runningOn() (or your SDK's equivalent) determines the current execution context:
When it returns
false: The code is executing at an edge POP. At this stage, your backend request will target the shield POP.When it returns
true: The code is executing at the shield POP (either forwarded via a shielding tunnel from an edge POP or because the visitor hit the shield POP directly). At this stage, your backend request will target your origin servers.For VCL developers: Modifying the request here is equivalent to checking
req.backend.is_originin VCL to prepare requests right before they leave the Fastly network for your origin servers.
- Rust
- JavaScript
- Go
- C++
891011121314151617181920 let response = if shield.running_on() { // We are on the shield POP (forwarded via shileding from an // edge POP tunnel, or because the visitor hit the shield POP directly)
// Ok to manipulate request meant for origin req.set_header("Host", "example.com"); // Send to origin server req.send("origin_backend")? } else { // We are on an edge POP // Send request to the shield POP's tunnel backend req.send(shield.encrypted_backend().unwrap())? }; 789101112131415161718192021 let response;
if (shield.runningOn()) { // We are on the shield POP (forwarded via shileding from an // edge POP tunnel, or because the visitor hit the shield POP directly)
// Ok to manipulate request meant for origin req.headers.set("Host", "example.com"); // Send to origin server response = await fetch(req, { backend: 'origin_backend' }); } else { // We are on an edge POP // Send request to the shield POP's tunnel backend response = await fetch(req, { backend: shield.encryptedBackend() }); } 1819202122232425262728293035363738 var resp *fsthttp.Response
if shield.IsRunningOn() { // We are on the shield POP (forwarded via shielding from an // edge POP tunnel, or because the visitor hit the shield POP directly)
// Ok to manipulate request meant for origin r.Header.Set("Host", "example.com") // Send to origin server resp, err = r.Send(ctx, "origin_backend") } else { // We are on an edge POP shieldBackendName, err := shield.Backend(nil) // Send request to the shield POP's tunnel backend resp, err = r.Send(ctx, shieldBackendName) }
Shielding is not available in this version of the Fastly Compute C++ SDK.
Targeting the response to the client
For best results, regardless of whether a single- or double-execution occurs, any modifications to the response that are intended for the client should be performed at the edge POP directly connected from the visitor (which can be the shield POP itself if the visitor's request hit the shield POP directly).
You can detect this "client-connected" context by passing a custom tracking header (such as X-From-Edge-POP) containing a shared secret during the internal edge-to-shield hop:
When
shield.runningOn()isfalse(running on a POP other than the shield POP), insert the tracking headerX-From-Edge-POP: SECRET_VALUEright before forwarding the request to the shield POP tunnel.During execution on any POP: If the
X-From-Edge-POPheader value on the incoming request is missing or does not matchSECRET_VALUE, you are guaranteed to be at the POP communicating directly with the client.
IMPORTANT: Use a private, cryptographically secure value for SECRET_VALUE. All instances of your service across the network (shield POP or otherwise) share access to this value (which ideally loaded via a Fastly Secret Store). This makes it impossible for external clients to guess or spoof the token.
For VCL developers: Intercepting the response here has the same effect as using
fastly.ff.visits_this_service == 0in VCL to apply client-facing logic (like Cache-Control headers). Note that the internalFastly-FFheader is not available in Compute services.
- Rust
- JavaScript
- Go
- C++
910111213141516171819202122232425262728293031323334353637383940414243 // Load the shared token securely from the Fastly Secret Store let secret_store = SecretStore::open("shield-configuration")?; let secret_value = secret_store .get("routing-token") .map(|key| key.plaintext()) .ok_or_else(|| { Error::msg("Missing [shield-configuration.routing-token] configuration in Secret Store") })?;
// DETECT: We are "client-connected" if the `X-From-Edge-POP` header value on the // incoming request does not match the secret exactly let is_client_connected = req .get_header("X-From-Edge-POP") .and_then(|v| v.to_str().ok()) .map(|v| v != secret_value) .unwrap_or(true);
let mut response;
if shield.running_on() { // Clean up internal tracking header before hitting origin servers req.remove_header("X-From-Edge-POP"); response = req.send("origin_backend")?; } else { // Mark the request right before sending it through the tunnel req.set_header("X-From-Edge-POP", secret_value.as_ref()); response = req.send(shield.encrypted_backend().unwrap())?; }
// MODIFY RESPONSE: Safely apply client-only logic when "client-connected" if is_client_connected { response.set_header("Cache-Control", "no-store, private"); }
Ok(response) 89101112131415161718192021222324252627282930313233343536373839 // Load the shared token securely from the Fastly Secret Store const secretStore = new SecretStore('shield-configuration'); const secretKey = await secretStore.get('routing-token'); const secretValue = secretKey?.plaintext(); if (!secretValue) { throw new Error("Missing [shield-configuration.routing-token] configuration in Secret Store"); }
// DETECT: We are "client-connected" if the `X-From-Edge-POP` header value on the // incoming request does not match the secret exactly const isClientConnected = req.headers.get("X-From-Edge-POP") !== secretValue;
let response;
if (shield.runningOn()) { // Clean up internal tracking header before hitting origin servers req.headers.delete("X-From-Edge-POP"); response = await fetch(req, { backend: 'origin_backend' }); } else { // Mark the request right before sending it through the tunnel if (secretValue) { req.headers.set("X-From-Edge-POP", secretValue); } response = await fetch(req, { backend: shield.encryptedBackend() }); }
// MODIFY RESPONSE: Safely apply client-only logic when "client-connected" if (isClientConnected) { response.headers.set("Cache-Control", "no-store, private"); }
return response; 20212631323334353637383940414243444546515253545964656667686970 // Load the shared token securely from the Fastly Secret Store secretStore, err := secretstore.Open("shield-configuration") secretKey, err := secretStore.Get("routing-token") secretValue, err := secretKey.Plaintext() if err != nil || secretValue == "" { fsthttp.Error(w, "Missing [shield-configuration.routing-token] configuration in Secret Store", fsthttp.StatusInternalServerError) return }
// DETECT: We are "client-connected" if the `X-From-Edge-POP` header value on the // incoming request does not match the secret exactly isClientConnected := r.Header.Get("X-From-Edge-POP") != secretValue
var resp *fsthttp.Response
if shield.IsRunningOn() { // Clean up internal tracking header before hitting origin servers r.Header.Del("X-From-Edge-POP") resp, err = r.Send(ctx, "origin_backend") } else { // Mark the request right before sending it through the tunnel r.Header.Set("X-From-Edge-POP", secretValue) shieldBackendName, err := shield.Backend(nil) resp, err = r.Send(ctx, shieldBackendName) }
// MODIFY RESPONSE: Safely apply client-only logic when "client-connected" if isClientConnected { resp.Header.Set("Cache-Control", "no-store, private") }
Shielding is not available in this version of the Fastly Compute C++ SDK.
Both of these conditionals will ensure that the associated logic only runs once. Here are some more examples of operations typically associated with one or the other phase:
| Targeting the response to the client | Targeting the request to the origin |
|---|---|
VCL: fastly.ff.visits_this_service == 0 | req.backend.is_origin == true |
Compute: presence of custom tracking header (such as X-From-Edge-POP) | shield.runningOn() (or your SDK's equivalent) |
| Manipulating the request URL Normalizing the request Authentication Security filtering (e.g., WAF or bot detection) Redirects Geolocation A/B testing ESI | Compressing responses Setting backend-specific headers |
HINT: As well as using the above conditional expressions, you can also write your code in a way that is idempotent, that is, it only has effect once, and if you run it again, nothing happens.
For example, static bucket storage origins like AWS S3 or GCS may require a path prefix to be added to the URL. Doing this unconditionally may result in the prefix being added twice, e.g. /bucket-name/bucket-name/path/to/file.
- CDN services
- Compute services
While you could use a variable such as fastly.ff.visits_this_service to avoid this, a better solution is to detect the presence of the prefix:
if (req.url.path !~ "^/bucket-name/") { set req.url = "/bucket-name/" + req.url;}While you could use the Fastly-FF check described above to avoid this, a better solution is to detect the presence of the prefix:
- Rust
- JavaScript
- Go
- C++
12345678910// Clone the request's URL to mutate it safelylet mut url = req.get_url().clone();let path = url.path();
// IDEMPOTENT CHECK: Only add the prefix if it isn't already thereif !path.starts_with("/bucket-name/") { let new_path = format!("/bucket-name{}", path); url.set_path(&new_path); req.set_url(url);}// Parse the incoming request URLconst url = new URL(req.url);
// IDEMPOTENT CHECK: Only add the prefix if it isn't already thereif (!url.pathname.startsWith("/bucket-name/")) { url.pathname = `/bucket-name${url.pathname}`;}// IDEMPOTENT CHECK: Only add the prefix if it isn't already thereif !strings.HasPrefix(r.URL.Path, "/bucket-name/") { r.URL.Path = "/bucket-name" + r.URL.Path}Shielding is not available in this version of the Fastly Compute C++ SDK.
Not available with code-defined backends (Applies to VCL only)
In CDN services, it is possible to define backends using VCL code as well as via the web interface, API or CLI. However, you cannot apply shielding to backends that you define in VCL.
Host header hidden problems
Fastly's platform uses an incoming request's HTTP Host header to identify the service that handles the request. This applies to public traffic as well as internal requests that travel from edge POPs to shield POPs.
If you mutate the Host header on the forwarded request at the outer edge (e.g., changing it from example.com to my-domain.com), the request will land at the shield POP with the changed hostname. Because the Host header used to identify the service has been altered, the shield POP won't recognize the request and will immediately drop it with an HTTP 500 Internal Server Error.
- CDN services
- Compute services
There are two primary ways to avoid this pitfall in CDN services.
Approach 1: Conditionally mutate the header only on the shield POP
If you must mutate the Host header manually in your code, only do so when the request is known to be going to your own origin (see req.backend.is_origin)
Approach 2: Use override_host on the Backend definition (Recommended)
Use the override_host property when creating the backend, and don't modify req.http.host in VCL. This approach is often the most conceptually straightforward and least prone to error.
There are two primary ways to avoid this pitfall in Compute services.
Approach 1: Conditionally mutate the header only on the shield POP
If you must mutate the Host header manually in your code, wrap it in a shield.runningOn() check. This guarantees that the original, recognizable Host header is preserved while the request transits the Fastly network, and is only swapped right before it exits the shield POP to your own origin.
Approach 2: Use override_host on the Backend definition (Recommended)
The recommended method is to use the override_host property when creating the backend, and leave the request's Host header untouched in your code. With this method, Fastly's infrastructure swaps it out automatically on the very last hop.
Client IP inaccuracy
- CDN services
- Compute services
In CDN services, client.ip reflects the IP address of the immediate downstream connection. In a shielding configuration, this means the shield POP will see the edge POP's IP instead of the user's.
To obtain the true client IP address across both edge and shield execution contexts, read the Fastly-Client-IP header.
HINT: The client.identity variable is also influenced by the apparent client IP, so if making use of client directors, client.identity should be reset to Fastly-Client-IP or to an identifier specific to your service.
set client.identity = req.http.Fastly-Client-IP;In Compute services, your SDK's native client IP property (e.g., event.client.address) reflects the IP address of the immediate downstream connection. In a shielding configuration, this means the shield POP will see the edge POP's IP instead of the user's.
To obtain the true client IP address across both edge and shield execution contexts, read the Fastly-Client-IP header.
Cache hit ratio inaccuracy
If a request results in a MISS at an edge POP and is forwarded to a shield POP where it finds a HIT, the user is ultimately served from cache, but we will record both the miss and the hit for the purpose of calculating your cache hit ratio. While 'shield hits' will involve more latency for end users than 'edge hits', the hit will still mean there is no need for an origin request. Equally, a request that does reach your origin server will be counted as two misses, one at the edge, and one at the shield.
This will result in a cache hit ratio (CHR) that may be lower than you expect. Since there are multiple ways of calculating CHR on shielded configurations, you may like to use our historical stats API to get raw numbers and perform your own calculations.
Backend assignment in code (Applies to VCL only)
In CDN services, if you wish to write custom VCL logic for assigning a backend to a request (i.e. set req.backend = backend_name;), and that backend is shielded, see multiple backends, to avoid overriding (or being overridden by) the generated shield routing logic.
Caching implications
When shielding is active, you must take care when modifying responses. A mistake here can accidentally poison your edge caches.
- Modifying at the edge POP: Changes made right before serving the response to the visitor are never stored in that POP's cache. Your code executes these modifications dynamically on every single request—even when a request is served as a local cache hit without fetching anything from the shield or origin.
- Modifying at the shield POP (not recommended): Any changes made here are viewed by downstream edge POPs as part of the official payload from your origin servers. Consequently, these modified responses will be stored in the edge POP's cache.
IMPORTANT: If you want to alter a response just before it hits the browser (such as stripping debugging headers or injecting security headers), always ensure that code executes exclusively at the "client-connected" POP. For details, refer to Targeting the response to the client under Double Execution.
Billing implications
Traffic from one Fastly POP to another will count towards your request count and billable bandwidth. In the most extreme case, if your service is configured to PASS every request, then your request count and delivery bandwidth will almost double, since most requests will be presented to two Fastly POPs, but in more realistic scenarios, shielding will often reduce costs overall. See our guide in documentation for more information.
Advanced shielding scenarios
Shielding can be used in many different configurations and variations. Some of the most common include:
Multiple backends
If you have multiple backends (for example because you are performing load balancing, have origin servers serving different regions, or a microservices architecture), then each backend must have shielding configured independently.
- CDN services
- Compute services
Configure each backend with the shield location that is most appropriate for its origin server, by setting the shield property to your chosen shield identifier. Backends may share the same shield POP or may shield in different locations, unless they have automatic load balancing enabled, in which case all backends must shield in the same location.
With multiple backends your service also requires some configuration to tell Fastly which backend to use. If you do not have custom VCL and use conditions or automatic load balancing to select backends, this happens automatically. However, if you want to use custom VCL to select an origin that is shielded, we recommend combining custom VCL with conditions:
- Declare a custom local boolean variable per backend at the start of
vcl_recv - Add a condition to each backend, which selects that backend if the matching variable is true, e.g.,
var.backend_a == true - Add custom backend selection logic before the
#FASTLYplaceholder in your VCL code (or using a VCL snippet)
For example:
12345678910declare local var.backend_a BOOL;declare local var.backend_b BOOL;
if (req.url.path ~ "^/account(?:/.*)?\z") { set var.backend_a = true;} else { set var.backend_b = true;}
#FASTLY RECVThis way, Fastly is able to perform the backend selection (the code to do this will be generated and will replace the #FASTLY RECV placeholder), and will assign the shield POP or the actual origin server as appropriate, while still ultimately selecting the correct backend for the request based on your own logic.
Designate a shield POP location independently for each backend. For best results, choose the shield POP based on geographical proximity to that specific backend's physical or cloud infrastructure.
When routing requests across multiple shielded backends, your application code dynamically maps each request to its corresponding shield execution path. Once your application selects which backend to target, reference or instantiate the designated shield POP for that specific backend. Call the runningOn() logic to check your execution state: if it returns true, forward the request directly to the target origin backend; if it returns false, route the request through that specific shield POP's encrypted tunnel backend.
- Rust
- JavaScript
- Go
- C++
The following is an example of multi-backend shielded routing, using a scenario where /account routes to backend_a (shielded in Amsterdam) and all other traffic routes to backend_b (shielded in Ashburn).
6789101112131415161718192021222324 let path = req.get_url().path();
// 1. Map the request to a target backend and its corresponding shield POP let (target_backend, shield_location) = if path.starts_with("/account") { ("backend_a", "amsterdam-nl") } else { ("backend_b", "iad-va-us") };
let shield = Shield::new(shield_location).unwrap();
// 2. Fork the routing logic based on the selected shield's execution state if shield.running_on() { // Already on the designated shield POP; forward directly to the origin backend Ok(req.send(target_backend)?) } else { // Executing at an edge POP; route through this specific shield's tunnel Ok(req.send(shield.encrypted_backend().unwrap())?) } The following is an example of multi-backend shielded routing, using a scenario where /account routes to backend_a (shielded in Amsterdam) and all other traffic routes to backend_b (shielded in Ashburn).
78910111213141516171819202122232425262728 let targetBackend; let shieldLocation;
// 1. Map the request to a target backend and its corresponding shield POP if (url.pathname.startsWith("/account")) { targetBackend = "backend_a"; shieldLocation = "amsterdam-nl"; } else { targetBackend = "backend_b"; shieldLocation = "iad-va-us"; }
const shield = new Shield(shieldLocation);
// 2. Fork the routing logic based on the selected shield's execution state if (shield.runningOn()) { // Already on the designated shield POP; forward directly to the origin backend return await fetch(req, { backend: targetBackend }); } else { // Executing at an edge POP; route through this specific shield's tunnel return await fetch(req, { backend: shield.encryptedBackend() }); } The following is an example of multi-backend shielded routing, using a scenario where /account routes to backend_a (shielded in Amsterdam) and all other traffic routes to backend_b (shielded in Ashburn).
1415161718192021222324252632333435434445464753 var targetBackend string var shieldLocation string
// 1. Map the request to a target backend and its corresponding shield POP if strings.HasPrefix(r.URL.Path, "/account") { targetBackend = "backend_a" shieldLocation = "amsterdam-nl" } else { targetBackend = "backend_b" shieldLocation = "iad-va-us" }
shield, err := shielding.ShieldFromName(shieldLocation) // 2. Fork the routing logic based on the selected shield's execution state if shield.IsRunningOn() { // Already on the designated shield POP; forward directly to the origin backend resp, err := r.Send(ctx, targetBackend) return }
// Executing at an edge POP; route through this specific shield's tunnel shieldBackendName, err := shield.Backend(nil) resp, err := r.Send(ctx, shieldBackendName) Shielding is not available in this version of the Fastly Compute C++ SDK.
Service pinning
If your service is pinned, the end user's domain may not be explicitly linked to it. This is because your service responds to any request resolving to your Fastly-assigned dedicated IP space, as long as a TLS configuration exists. When a request moves from an edge POP to a shield POP, the shield may not know which service to invoke.
- CDN services
- Compute services
To resolve this in CDN services, use a custom header (such as req.http.x-orig-host) to carry the true client domain across the internal Fastly network. When executing at the edge POP, save the client's original Host header to the custom header and swap the backend request's Host header to your explicitly associated anchor domain before routing it to the shield. When the request lands at the shield POP, your VCL code reads that custom header and restores it.
12345678#capture the incoming hostname from the clientif (fastly.ff.visits_this_service == 0 && req.restarts == 0) { set req.http.x-orig-host = req.http.host;}#overwrite the anchor hostname at the shield with the original client requested hostnameif (fastly.ff.visits_this_service > 0 && req.http.x-orig-host) { set req.http.host = req.http.x-orig-host;}set bereq.http.host = if ( req.backend.is_shield, "{some-name}.freetls.fastly.net", # A domain explicitly associated with your service, to allow shielding to work req.http.x-orig-host # The hostname to forward to your backend);To resolve this in Compute services, use a custom header (such as X-Orig-Host) to carry the true client domain across the internal Fastly network. When executing at the edge POP, save the client's original Host header to X-Orig-Host and swap the active Host header to your explicitly associated anchor domain before passing the request to the shield tunnel. When that internally forwarded request executes at the shield POP, your code reads that custom header and restores it.
- Rust
- JavaScript
- Go
- C++
89101112131415161718192021222324252627 if shield.running_on() { // Shield POP Execution // Overwrite the anchor hostname at the shield with the original client requested hostname if let Some(orig_host) = req.get_header("X-Orig-Host").cloned() { req.set_header("Host", orig_host); } Ok(req.send("origin_backend")?) } else { // Edge POP Execution // Capture the incoming hostname from the client if let Some(orig_host) = req.get_header("Host").cloned() { req.set_header("X-Orig-Host", orig_host); }
// Set an anchor domain explicitly associated with your service, // allowing shielding to work under a pinned IP setup. req.set_header("Host", "example-service.freetls.fastly.net");
Ok(req.send(shield.encrypted_backend().unwrap())?) } 7891011121314151617181920212223242526 if (shield.runningOn()) { // Shield POP Execution // Overwrite the anchor hostname at the shield with the original client requested hostname const origHost = req.headers.get("X-Orig-Host"); if (origHost) { req.headers.set("Host", origHost); } return await fetch(req, { backend: 'origin_backend' }); } else { // Edge POP Execution // Capture the incoming hostname from the client const origHost = req.headers.get("Host"); req.headers.set("X-Orig-Host", origHost);
// Set an anchor domain explicitly associated with your service, // allowing shielding to work under a pinned IP setup. req.headers.set("Host", "example-service.freetls.fastly.net");
return await fetch(req, { backend: shield.encryptedBackend() }); } 1819202122232425263435363738394041424344454652 if shield.IsRunningOn() { // Shield POP Execution // Overwrite the anchor hostname at the shield with the original client requested hostname origHost := r.Header.Get("X-Orig-Host") if origHost != "" { r.Header.Set("Host", origHost) }
resp, err := r.Send(ctx, "origin_backend") return }
// Edge POP Execution // Capture the incoming hostname from the client origHost := r.Header.Get("Host") r.Header.Set("X-Orig-Host", origHost)
// Set an anchor domain explicitly associated with your service, // allowing shielding to work under a pinned IP setup. r.Header.Set("Host", "example-service.freetls.fastly.net")
shieldBackendName, err := shield.Backend(nil) resp, err := r.Send(ctx, shieldBackendName) Shielding is not available in this version of the Fastly Compute C++ SDK.
Enable or disable shielding for a single request
- CDN services
- Compute services
In CDN services, shielding behavior is part of the backend configuration. If a shielded backend is selected and the current POP is not the designated shield POP, shielding will happen by default if req.restarts == 0 (i.e., the request has not been restarted). You can change this using a "recv" VCL snippet):
set var.fastly_req_do_shield = true;You may want to do this to achieve use cases such as:
- Enable shielding even after a
restart - Disable shielding for certain URL paths which cannot be cached
var.fastly_req_do_shield is a custom VCL variable defined by Fastly's generated VCL. It's defined at the beginning of the #FASTLY RECV macro and affects the shielding decisions made at the end of #FASTLY RECV, so the only way to use it effectively is in a VCL snippet, because snippets are rendered within the #FASTLY RECV macro.
In Compute services, shielding behavior is dictated entirely by your application code. If you need to enable or disable shielding for specific requests, such as for certain URL paths, simply evaluate those conditions in code and perform the fetch via the shield's encrypted tunnel or route directly to your own backend.
Debugging
Shielding increases the number of potential outcomes for a request presented to a Fastly edge. It's possible that the request will be answered directly from the edge POP. If the edge POP doesn't have the object, the request might still result in a cache HIT, but from the shield POP. Observing these effects and understanding how they affect your metrics can be a necessary step in debugging services with shielding enabled.
The X-Served-By, X-Cache-Hits and X-Cache response headers, which normally show only one entry without shielding enabled, will include an entry for each Fastly POP that has processed the request, but bear in mind that if a request is a HIT at the edge, the entry representing the shield POP will be from when the cached object was originally cached. First, start by understanding the possible values of X-Cache:
| X‑Cache | Meaning | CHR implications |
|---|---|---|
MISS, MISS | The object was not in cache at either the edge or the shield. The requested object was fetched from the backend. This will count as two misses as part of the calculation of your headline CHR. | 2 misses |
HIT, MISS | The object was not in cache at the edge, so was forwarded to the shield, where it was found in cache. This outcome will contribute one 'miss' to your headline CHR although ultimately the request is satisfied from within the Fastly network. | 1 hit, 1 miss |
MISS, HIT | The object was found in cache at the edge. When the object was (previously) fetched from the shield, it was a MISS at the shield. The 'MISS' here is a record of a prior event, not something that happened in this request. | 1 hit |
HIT, HIT | The object was found in cache at the edge. When the object was (previously) fetched from the shield, it was a HIT at the shield. The first 'HIT' here is a record of a prior event, not something that happened in this request. | 1 hit |
HIT | The object was found in cache, and the POP that received the request in this case happens to be the designated shield, so the object was originally loaded directly from the backend. | 1 hit |
MISS | The object was not in cache, and the POP that received the request in this case happens to be the designated shield, so the object was fetched directly from the backend and served to the end user. | 1 miss |
So, where the X-Cache header contains two entries and the second one is 'HIT', the first entry in each of the three debugging headers relates to when the object was originally fetched from the shield, not the current status of the object at the shield.
Additionally, the X-Cache-Hits header records the value of the obj.hits VCL variable, which is local to the individual cache node. To optimise and balance load, Fastly may cache objects on multiple machines in a POP, and particularly hot objects may end up cached on every node in the POP (see clustering to learn more). As a result, where the second token of X-Cache is 'HIT', the first token of X-Cache-Hits will refer to the number of hits recorded on the individual cache server at the shield POP at the time that the object was served from the shield to the edge. This can often be confusing.
Example response data
Imagine a request for an object that is not cached by Fastly, on a service with shielding enabled. The response would contain headers that look like this:
X-Cache: MISS, MISSX-Served-By: cache-iad2120-IAD, cache-sjc3120-SJCX-Cache-Hits: 0, 0In this instance, the X-Cache: MISS, MISS shows that the request has transited two Fastly POPs and was not in the cache in either of them. X-Served-By lists the servers acting as the delivery node in each POP, in the order in which they processed the response. In this case, cache-iad2120-IAD (Dulles, Virginia) was the shield POP (closest to the backend), and therefore saw the response first, and cache-sjc3120-SJC (San Jose, California) was the edge POP (closest to the end user).
If the same request is made, moments later, by the same user on a still-open connection, it would be expected to be handled by exactly the same edge server:
X-Cache: MISS, HITX-Served-By: cache-iad2120-IAD, cache-sjc3120-SJCX-Cache-Hits: 0, 1This time, the request was a hit at the edge cache-node (cache-sjc3120-SJC). Because it is a hit at the edge it would not be forwarded to a shield. The MISS listed for cache-iad2120-IAD reflects the state of that node from the first request, and not its current state. The object is now cached in both POPs. Making a third request on the same connection would result in the same response except that X-Cache-Hits would now be 0, 2.
Requesting the object again on a fresh connection will likely result in the request being handled by a different edge cache server:
X-Cache: MISS, HITX-Served-By: cache-iad2120-IAD, cache-sjc3122-SJCX-Cache-Hits: 0, 1This third request is very similar to the second, but in being handled by a different cache node (cache-sjc3122-SJC) at the edge POP, X-Cache-Hits reflects the hit count at the individual server level so still shows only 1 hit on this machine and 0 at the shield POP.
Choosing a shield location
You should choose a shield POP that is physically close to your origin servers. There are a couple of other parameters to consider:
Some Fastly POPs have interconnection points with cloud provider networks. An interconnection point is a location where two networks exchange data or traffic. When a POP uses a private network interconnect (PNI), the POP and cloud provider use the interconnection point instead of the public internet to manage requests. If your origin is hosted with one of these providers, choose a shield location where we have an interconnect for optimal performance and potential cost savings.
Fastly POPs vary dramatically in size and current spare capacity. Choose a POP that offers the largest cache storage for a better cache hit ratio at the shield, and therefore reduced origin traffic.
Understanding PNI cost savings
Depending on your origin's provider, choosing a shield location with an interconnect could provide significant cost savings.
WARNING: Fastly makes no warranty on third-party software. We assume no responsibility for errors or omissions in the third-party software or documentation available. Using such software is done entirely at your own discretion and risk.
| Provider | Cost savings | Availability |
|---|---|---|
| Amazon Web Services | None | Not applicable |
| Backblaze B2 Cloud Storage | Free egress | Any shield location |
| Google Cloud Platform | Discounted egress | All GCP PNIs |
| Microsoft Azure | Free egress | AMS, BFI, CHI, DFW, IAD, and PAO only |
Shield locations
The following POPs are suitable for shielding Fastly services:
| Location | POP | Capacity | Shield code | PNIs | Recommended for | |
|---|---|---|---|---|---|---|
| Amsterdam | AMS | ●●○ | amsterdam-nl | west-europeeurope-west4 | ||
| Ashburn | IAD | ●●● | iad-va-us | east-usus-east-1us-east1us-east4us-east5 | ||
| Atlanta | PDK | ●●● | atlanta-ga-us | |||
| Auckland | AKL | ●○○ | auckland-akl | |||
| Bogota | BOG | ●●○ | bog-bogota-co | |||
| Boston | BOS | ●○○ | bos-ma-us | |||
| Brisbane | BNE | ●○○ | brisbane-au | |||
| Brussels | BRU | ●○○ | bru-brussels-be | |||
| Cape Town | CPT | ●○○ | cpt-capetown-za | af-south-1 | ||
| Chennai | MAA | ●○○ | maa-chennai-in | |||
| Chicago | CHI | ●●● | chi-il-us | ca-central-1us-east-2us-central1 | ||
| Christchurch | CHC | ●○○ | chc-christchurch-nz | |||
| Copenhagen | CPH | ●○○ | cph-copenhagen-dk | |||
| Dallas | DFW | ●●● | dallas-tx-us | us-south1 | ||
| Delhi | DEL | ●○○ | del-delhi-in | asia-south2 | ||
| Denver | DEN | ●●○ | den-co-us | us-west3 | ||
| Dublin | DUB | ●●○ | dub-dublin-ie | eu-west-1 | ||
| Frankfurt | FRA | ●●● | frankfurt-de | eu-central-1eu-central-2europe-central2europe-west3europe-west6europe-west8me-west1 | ||
| Fujairah Al Mahta | FJR | ●○○ | fjr-fujairah-uae | me-central-1me-south-1 | ||
| Helsinki | HEL | ●○○ | hel-helsinki-fi | europe-north1 | ||
| Hong Kong | HKG | ●○○ | hongkong-hk | ap-east-1asia-east2 | ||
| Houston | IAH | ●●● | iah-tx-us | |||
| Hyderabad | HYD | ●○○ | hyd-hyderabad-in | |||
| Johannesburg | JNB | ●○○ | jnb-johannesburg-za | |||
| Kolkata | CCU | ●○○ | ccu-kolkata-in | |||
| Lisbon | LIS | ●○○ | lis-lisbon-pt | |||
| London | LCY | ●●● | london_city-uk | eu-west-2europe-west2 | ||
| London | LHR | ●●○ | london-uk | |||
| London | LON | ●●○ | lon-london-uk | |||
| Los Angeles | BUR | ●●○ | bur-ca-us | west-usus-west2us-west4 | ||
| Madrid | MAD | ●●○ | mad-madrid-es | europe-southwest1 | ||
| Manchester | MAN | ●●○ | man-manchester-uk | |||
| Marseille | MRS | ●●○ | mrs-marseille-fr | |||
| Melbourne | MEL | ●●○ | melbourne-au | australia-southeast2 | ||
| Miami | MIA | ●●○ | miami-fl-us | |||
| Milan | MXP | ●●○ | mxp-milan-it | eu-south-1 | ||
| Minneapolis | MSP | ●●○ | msp-mn-us | |||
| Montreal | YUL | ●●○ | yul-montreal-ca | |||
| Mumbai | BOM | ●●○ | bom-mumbai-in | ap-south-1asia-south1 | ||
| New York City | LGA | ●●○ | lga-ny-us | northamerica-northeast1 | ||
| Newark | EWR | ●●○ | ewr-nj-us | |||
| Osaka | ITM | ●●○ | osaka-jp | ap-northeast-3asia-northeast2 | ||
| Oslo | OSL | ●○○ | osl-oslo-no | |||
| Paris | PAR | ●●● | paris-fr | eu-west-3europe-west1europe-west9 | ||
| Perth | PER | ●○○ | perth-au | |||
| Portland | PDX | ●○○ | pdx-or-us | |||
| Rio de Janeiro | GIG | ●●○ | gig-riodejaneiro-br | southamerica-west1 | ||
| San Jose | SJC | ●●○ | sjc-ca-us | us-west-1 | ||
| Sao Paulo | GRU | ●●○ | gru-saopaulo-br | sa-east-1southamerica-east1 | ||
| Seattle | BFI | ●●● | bfi-wa-us | us-west-2us-west1 | ||
| Seoul | ICN | ●●○ | icn-seoul-kr | ap-northeast-2asia-northeast3 | ||
| Singapore | SIN | ●●● | sin-singapore-sg | ap-southeast-1ap-southeast-3asia-southeast1asia-southeast2 | ||
| Sofia | SOF | ●○○ | sof-sofia-bg | |||
| Stockholm | BMA | ●●○ | stockholm-bma | eu-north-1europe-north1 | ||
| Sydney | SYD | ●●○ | sydney-au | australia-eastap-southeast-2australia-southeast1 | ||
| Sydney | WSI | ●●○ | wsi-australia-au | |||
| Tokyo | NRT | ●●● | nrt-tokyo-jp | ap-northeast-1asia-east1asia-northeast1 | ||
| Toronto | YYZ | ●●○ | yyz-on-ca | northamerica-northeast2 | ||
| Vienna | VIE | ●●○ | vie-vienna-at |
Cloud provider recommendations are powered by jsDelivr's Globalping platform. jsDelivr is a member of our community program, which nurtures and supports projects that share our vision of an open internet that is fast and secure for all.
This is not a complete list of Fastly POPs. For a complete list, see the POPs API, run fastly pops on your terminal, or see our network map.