---
title: Purging best practices
summary: null
url: >-
  https://www.fastly.com/documentation/guides/full-site-delivery/purging/purging-best-practices
---

This guide provides best practices for purging with Fastly.

## Select the best purging method for your use cases

Fastly has different [purging methods](https://www.fastly.com/documentation/guides/full-site-delivery/purging/getting-started-with-purging/#methods-and-types-of-purges) that let you precisely purge only the objects you want updated. Familiarize yourself with each method so that you're purging only what you need.

## Use soft purging

[Soft purging](https://www.fastly.com/documentation/guides/full-site-delivery/purging/getting-started-with-purging/#soft-vs-hard-purging) marks objects as stale instead of immediately deleting them. This can help you avoid traffic spikes to your origin and respond to client requests even when your origin servers are down. 

## Understand how purging interacts with shielding

If you plan on enabling [shielding](https://www.fastly.com/documentation/guides/getting-started/hosts/shielding/) on your service, it's 

### Encountering race conditions

Because the order in which caches are purged can't be controlled, it's possible that a request might reach a purged edge POP first, then be forwarded to a shield POP that has not yet been purged. The shield POP will deliver the cached content to the edge POP, which will cache it, resulting in the pre-purge content remaining in Fastly cache.

A solution to this race condition problem is to purge twice. For purge all operations, execute the two purges around 30 seconds apart. For URL and surrogate key purges, execute the two purges around two seconds apart.

You can automate the purge all operations by comparing the cache generation value. Purge all operations cause the cache generation value to change. Add the [`req.vcl.generation`](https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-vcl-generation/) VCL variable or [`FASTLY_CACHE_GENERATION`](https://www.fastly.com/documentation/reference/compute/ecp-env/fastly-cache-generation/) environment variable to a response at a shield POP, and then compare with the local value at the edge POP. If they differ, the edge POP should not cache the response. The following example shows how this can be implemented in VCL:

[Try it in Fastly Fiddle](https://fiddle.fastly.dev/6deeb323)

### Stale content becoming fresh

If you use [soft purging](https://www.fastly.com/documentation/guides/full-site-delivery/purging/getting-started-with-purging/#soft-vs-hard-purging) and your service is configured to [serve stale content](https://www.fastly.com/documentation/guides/full-site-delivery/performance/serving-stale-content/), the shield POP may serve stale content to the edge POP, which then becomes re-cached with a fresh TTL.

A solution to this problem is to disable the use of stale content for asynchronous revalidation when a POP is acting as a shield:

### Cdn Services

You can prevent the inadvertent caching of stale content at the edge [POP](https://www.fastly.com/documentation/guides/getting-started/concepts/using-fastlys-global-pop-network) by disabling the use of stale content for asynchronous revalidation when a POP is acting as a shield:

```vcl context="sub vcl_recv { ... }"
if (fastly.ff.visits_this_service > 0) {
  set req.max_stale_while_revalidate = 0s;
}
```

This code will continue to allow stale content to be used when an origin is sick. To disable that as well, set `req.max_stale_if_error` to `0s`.

### Compute Services

### Rust

```rust compile_fail
// section visible
let shield = match Shield::new("") {
  Ok(v) => v,
  Err(e) => return Ok(Response::from_status(StatusCode::INTERNAL_SERVER_ERROR)
      .with_body(format!("Could not find shield '': {:?}", e))),
};

if !shield.running_on() {
  // If we're not running on the shield POP, look up the encrypted
  // tunnel to that backend, and try to forward it on.
// section-end visible
  let response = match shield.encrypted_backend() {
    Err(e) => Ok(
        Response::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_body(format!(
            "Could not convert shield  into an encrypted backend: {:?}",
            e
        )),
    ),

    Ok(backend) => {
      // We will want to make considerations about caching here.
      match req.send(backend) {
        Err(e) => Ok(Response::from_status(StatusCode::INTERNAL_SERVER_ERROR)
           .with_body(format!("Could not send request to shield: {}", e))),

        Ok(resp) => {
          // If you want to add a header somewhere to mark that you got this
          // from a shield, that can be handy for debugging, and this would
          // be the place to do it.
          Ok(resp)
        }
      }
    }
  };

  return response;
// section visible
}
// if we get here, then we're running on the shield!

let resp = req
    .with_stale_while_revalidate(0) // Set stale-while-revalidate to 0 seconds
    .send(backend)?;
return resp;
// section-end visible
```

### Javascript

```js
// section visible

async function handleRequest(event) {
    const shield = new Shield('');
    if (!shield.runningOn()) {
        // If we're not running on the shield POP, look up the encrypted
        // tunnel to that backend, and try to forward it on.
// section-end visible
        const backend = shield.encryptedBackend();

        // We will want to make considerations about caching here.
        // If you want to add a header somewhere to mark that you got this
        // from a shield, that can be handy for debugging, and this would
        // be the place to do it.
        return await fetch(event.request, { backend });
// section visible
    }
    // if we get here, then we're running on the shield!

    let resp = fetch(event.req, {
            backend
            cacheOverride: new CacheOverride({
                staleWhileRevalidate: 0, // Set stale-while-revalidate to 0 seconds
            }),
        });

    return resp
}
// section-end visible

addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
```

### Go

```go
// section visible
import (
// section-end visible
    "context"
    "fmt"
    "net"

	"github.com/fastly/compute-sdk-go/fsthttp"
// section visible
	"github.com/fastly/compute-sdk-go/shielding"
)
// section-end visible

// section visible
func main() {
    fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
        shield, err := shielding.ShieldFromName("")
        if err != nil {
            w.WriteHeader(fsthttp.StatusInternalServerError)
            fmt.Fprintln(w, err.Error())
            return
        }

        if !shield.IsRunningOn() {
            // If we're not running on the shield POP, look up the encrypted
            // tunnel to that backend, and try to forward it on.
// section-end visible
            backend, err := shield.Backend(nil) // Passing nil uses default BackendOptions
            if err != nil {
                w.WriteHeader(fsthttp.StatusInternalServerError)
                fmt.Fprintln(w, err.Error())
                return
            }

            // We will want to make considerations about caching here.
            resp, err := req.Send(ctx, backend)
            if err != nil {
                w.WriteHeader(fsthttp.StatusInternalServerError)
                fmt.Fprintln(w, err.Error())
                return
            }

            // If you want to add a header somewhere to mark that you got this
            // from a shield, that can be handy for debugging, and this would
            // be the place to do it.
            // resp.Header.Set("X-From-Shield", "true")

            w.Header().Reset(resp.Header)
            w.WriteHeader(resp.StatusCode)
            io.Copy(w, resp.Body)
// section visible
        }
        // if we get here, then we're running on the shield!

        r.CacheOptions.StaleWhileRevalidate = 0 // Set stale-while-revalidate to 0 seconds

        resp, err := r.Send(ctx, backend)
        if err != nil {
            w.WriteHeader(fsthttp.StatusBadGateway)
            fmt.Fprintln(w, err.Error())
            return
        }

        w.Header().Reset(resp.Header)
        w.WriteHeader(resp.StatusCode)
        io.Copy(w, resp.Body)
    })
}
// section-end visible
```

### Cpp

Shielding is not available in this version of the Fastly Compute C++ SDK.

Note that the above code will continue to allow stale content to be used when an origin is sick.

To disable that as well, also set the `stale-if-error` lifetime to `0s`:

### Rust

```rust compile_fail
let shield = match Shield::new("") {
  Ok(v) => v,
  Err(e) => return Ok(Response::from_status(StatusCode::INTERNAL_SERVER_ERROR)
      .with_body(format!("Could not find shield '': {:?}", e))),
};

if !shield.running_on() {
  // If we're not running on the shield POP, look up the encrypted
  // tunnel to that backend, and try to forward it on.
  let response = match shield.encrypted_backend() {
    Err(e) => Ok(
        Response::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_body(format!(
            "Could not convert shield  into an encrypted backend: {:?}",
            e
        )),
    ),

    Ok(backend) => {
      // We will want to make considerations about caching here.
      match req.send(backend) {
        Err(e) => Ok(Response::from_status(StatusCode::INTERNAL_SERVER_ERROR)
           .with_body(format!("Could not send request to shield: {}", e))),

        Ok(resp) => {
          // If you want to add a header somewhere to mark that you got this
          // from a shield, that can be handy for debugging, and this would
          // be the place to do it.
          Ok(resp)
        }
      }
    }
  };

  return response;
}
// if we get here, then we're running on the shield!

// section visible
let resp = req
    .with_stale_while_revalidate(0) // Set stale-while-revalidate to 0 seconds
    .with_stale_if_error(0)         // Set stale-if-error to 0 seconds
    .send(backend)?;
return resp;
// section-end visible
```

### Javascript

```js

async function handleRequest(event) {
    const shield = new Shield('');
    if (!shield.runningOn()) {
        // If we're not running on the shield POP, look up the encrypted
        // tunnel to that backend, and try to forward it on.
        const backend = shield.encryptedBackend();

        // We will want to make considerations about caching here.
        // If you want to add a header somewhere to mark that you got this
        // from a shield, that can be handy for debugging, and this would
        // be the place to do it.
        return await fetch(event.request, { backend });
    }
    // if we get here, then we're running on the shield!

// section visible
    let resp = fetch(event.req, {
            backend
            cacheOverride: new CacheOverride({
                staleWhileRevalidate: 0, // Set stale-while-revalidate to 0 seconds
                staleIfError: 0,         // Set stale-if-error to 0 seconds
            }),
        });

    return resp
// section-end visible
}

addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
```

### Go

```go
import (
    "context"
    "fmt"
    "net"

	"github.com/fastly/compute-sdk-go/fsthttp"
	"github.com/fastly/compute-sdk-go/shielding"
)

func main() {
    fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
        shield, err := shielding.ShieldFromName("")
        if err != nil {
            w.WriteHeader(fsthttp.StatusInternalServerError)
            fmt.Fprintln(w, err.Error())
            return
        }

        if !shield.IsRunningOn() {
            // If we're not running on the shield POP, look up the encrypted
            // tunnel to that backend, and try to forward it on.
            backend, err := shield.Backend(nil) // Passing nil uses default BackendOptions
            if err != nil {
                w.WriteHeader(fsthttp.StatusInternalServerError)
                fmt.Fprintln(w, err.Error())
                return
            }

            // We will want to make considerations about caching here.
            resp, err := req.Send(ctx, backend)
            if err != nil {
                w.WriteHeader(fsthttp.StatusInternalServerError)
                fmt.Fprintln(w, err.Error())
                return
            }

            // If you want to add a header somewhere to mark that you got this
            // from a shield, that can be handy for debugging, and this would
            // be the place to do it.
            // resp.Header.Set("X-From-Shield", "true")

            w.Header().Reset(resp.Header)
            w.WriteHeader(resp.StatusCode)
            io.Copy(w, resp.Body)
        }
        // if we get here, then we're running on the shield!

// section visible
        r.CacheOptions.StaleWhileRevalidate = 0 // Set stale-while-revalidate to 0 seconds
        r.CacheOptions.StaleIfError  = 0        // Set stale-if-error to 0 seconds

        resp, err := r.Send(ctx, backend)
// section-end visible
        if err != nil {
            w.WriteHeader(fsthttp.StatusBadGateway)
            fmt.Fprintln(w, err.Error())
            return
        }

        w.Header().Reset(resp.Header)
        w.WriteHeader(resp.StatusCode)
        io.Copy(w, resp.Body)
    })
}
```

### Cpp

Shielding is not available in this version of the Fastly Compute C++ SDK.

## Understand how the `Vary` header interacts with purging methods

The `Vary` header is used on responses to indicate that the response can only be used for requests with a specific header value. While there are many [use cases for the `Vary` header](https://www.fastly.com/documentation/reference/http/http-headers/Vary/), one option is to cache (and then purge) logged in and logged out variants of a page separately.

To do this, use surrogate keys to purge. Surrogate key purges target objects by the surrogate key, not the cache key, so they will only invalidate variants that have the key. If an object has multiple variants in cache and only some of them match the key you have requested to purge, only those variants will be invalidated.

When using URL purge, the purge targets objects by cache key, so all variants of the object are purged. Purge all invalidates all content in the service, so implicitly all variants of all objects are purged.

## Use versioned URLs for select content types instead of purging

In certain situations, it may be more efficient to deliver updated content by publishing it at a new URL, rather than purging.

While your web pages should maintain URLs to optimize SEO and avoid breaking inbound links, the assets the page loads, such as videos, images, scripts, and stylesheets, are typically linked only from pages you control, so their URLs can change. When you update a page, you can often give every asset it loads a new URL.

With new asset URLs, the Fastly platform sends requests from the updated page to your origin to fetch the new assets, while requests from older versions of the page continue to be served from assets cached at the edge.

Versioned URLs can take many forms. Here are some examples:

- `/script.js?v=2021-01-01T00:00:00`: Using the _time_ when the site was updated is a simple mechanism, but if you don't update the entire site in one atomic operation, you may create cache fragmentation.
- `/script.js?v=12`: Using a _version number_ works well if your site has a single overall version number.
- `/script.195bb21f.js`: Putting a _hash_ of the content in the filename is an effective stateless solution and favored by many web frameworks.

All these URL paths would be considered separate objects by Fastly. Serve these kinds of assets from your origin server with a long cache TTL, and consider setting the `immutable` cache directive:

```http
Cache-Control: max-age=31556952, immutable
```

> **HINT:** When using versioned URLs for assets, avoid performing purge all operations because it will remove all versioned assets.
