Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, você encontra informações sobre como exibir conteúdo desatualizado e expirado com o
Cloud CDN. A exibição de conteúdo desatualizado permite que o cache global do Google continue exibindo
o conteúdo quando o servidor de origem estiver inacessível ou retornando erros para o
Cloud CDN.
Os motivos para fazer isso são os seguintes:
você prefere exibir conteúdo desatualizado para os usuários em vez de retornar erros aos
usuários.
A exibição de conteúdo desatualizado evita latência quando o cache recebe uma solicitação de conteúdo
que acabou de expirar. Em vez de ter que esperar por uma revalidação
síncrona para o back-end, o cache exibe o conteúdo desatualizado que acabou
de expirar, enquanto aciona uma revalidação separada.
Para ativar esse comportamento, o back-end pode especificar a diretiva
stale-while-revalidate no cabeçalho Cache-Control de resposta. O Cloud CDN
então veiculará esse conteúdo pelo cache (se disponível) pelo número especificado de segundos
após o prazo de validade da entrada no cache. De maneira assíncrona, o Cloud CDN
revalidará o conteúdo com a origem.
O Cloud CDN permitirá isso em seu nome com a
configuração cdnPolicy.serveWhileStale. Essa configuração determina quanto tempo, após a expiração da
resposta, o Cloud CDN pode continuar exibindo uma versão
desatualizada. Se não for especificado de outra forma na resposta, será 86400s (1 dia).
O Cloud CDN não é compatível com a diretiva stale-if-error. Essa diretiva instrui o cache a evitar a exibição de conteúdo desatualizado, a menos que a revalidação síncrona com o back-end tenha falhado com códigos de status de erro específicos.
Os valores padrão, mínimo e máximo são os seguintes:
Padrão: 86.400 segundos (um dia)
Mínimo: 0 segundo (desativa o recurso)
Máximo: 604.800 segundos (uma semana)
O conteúdo desatualizado é exibido até o limite especificado após o prazo de validade da entrada
em cache, que é definido pelos cabeçalhos
max-age, s-maxage ou Expires. Para mais informações, consulte Prazos de validade e solicitações de
validação.
Se um armazenamento em cache próximo dos usuários finais do Cloud CDN não tiver uma cópia armazenada em cache do objeto para
exibir o desatualizado ou se o objeto tiver atingido o TTL máximo desatualizado, o Cloud CDN
revalidará o conteúdo de maneira síncrona com a origem. Se a origem retornar
um erro naquele momento, o Cloud CDN retornará o erro de origem.
Logging e user agent
As solicitações assíncronas feitas pelo Cloud CDN aparecem para seu servidor
de origem exatamente como as solicitações de revalidação normais que ocorrem quando o conteúdo
obsoleto não é veiculado. A exceção é que elas são marcadas com um cabeçalho User-Agent
contendo Cloud-CDN-Google.
As solicitações assíncronas também são registradas separadamente no Cloud Logging. Portanto, uma solicitação
de usuário desatualizada gera duas entradas de registro: a primeira para o
conteúdo realmente veiculado ao usuário e a segunda para a solicitação de revalidação
à origem. Assim como as revalidações síncronas, o Cloud CDN pode enviar uma
solicitação condicional em algumas circunstâncias
ou apenas solicitar novamente o conteúdo incondicionalmente. Em ambos os casos, o código de
resposta registrado no Cloud Logging corresponde à solicitação original para o
Cloud CDN. Por exemplo, um 200 OK para uma solicitação não condicional ou um
304 Not Modified se a resposta original do usuário for condicional.
Diretiva de solicitação max-stale do cliente
Os clientes podem solicitar um tempo de serviço desatualizado mais curto especificando uma diretiva de
controle de cache max-stale. Se especificado, esta diretiva controla o tempo de
inatividade que o cliente tolera.
Se o conteúdo em cache for mais antigo do que o valor de max-stale do cliente,
o Cloud CDN revalidará o conteúdo antes da exibição.
O cliente não pode solicitar um valor de max-stale maior que o valor
configurado com a opção de configuração serve-while-stale e a
diretiva de controle de cache stale-while-revalidate da origem.
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendBuckets
PUT https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendBuckets/BACKEND_BUCKET
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices
PUT https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE
Adicione o seguinte snippet ao corpo da solicitação JSON:
"cdnPolicy": {
"serveWhileStale": SECONDS
}
Desativar a veiculação de conteúdo desatualizado
Console
No Google Cloud console, acesse a página Balanceamento de carga.
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendBuckets
PUT https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendBuckets/BACKEND_BUCKET
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices
PUT https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE
Adicione o snippet a seguir ao corpo da solicitação JSON:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-01 UTC."],[[["\u003cp\u003eCloud CDN can serve stale content, allowing continued delivery even when the origin server is unreachable or returns errors, preventing users from encountering errors.\u003c/p\u003e\n"],["\u003cp\u003eServing stale content avoids latency by delivering cached content immediately after expiration, triggering a revalidation in the background.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003ecdnPolicy.serveWhileStale\u003c/code\u003e setting determines how long Cloud CDN can serve stale content after expiration, with a default of one day (86,400 seconds), and can be configured from 0 seconds to one week (604,800 seconds).\u003c/p\u003e\n"],["\u003cp\u003eAsynchronous requests for stale content revalidation are logged separately and tagged with a \u003ccode\u003eUser-Agent\u003c/code\u003e header containing \u003ccode\u003eCloud-CDN-Google\u003c/code\u003e, appearing to the origin server like normal revalidation requests.\u003c/p\u003e\n"],["\u003cp\u003eClients can request to have content served stale by setting the \u003ccode\u003emax-stale\u003c/code\u003e cache control directive, limiting the amount of staleness they will accept.\u003c/p\u003e\n"]]],[],null,["# Serve stale content\n\nThis page provides information about serving stale, expired content with\nCloud CDN. Serving stale content lets Google's global cache continue to serve\ncontent when your origin server is unreachable or is returning errors to\nCloud CDN.\n\nThe reasons to do this are as follows:\n\n- You prefer to serve stale content to users rather than returning errors to users.\n- Serving stale content avoids latency when the cache gets a request for content that has just expired. Rather than having to wait for a synchronous revalidation to the backend, the cache serves the stale content that has just expired, while triggering a separate revalidation.\n\nTo enable this behavior, your backend can specify the `stale-while-revalidate`\ndirective in the response `Cache-Control` header. Cloud CDN will then\nserve that content from cache (if available) for the specified number of seconds\npast the cache entry expiration time. Asynchronously, Cloud CDN\nwill revalidate content with the origin.\n\nCloud CDN enables this on your behalf with the\n`cdnPolicy.serveWhileStale` setting. This setting dictates how long, after the\nresponse has expired, that Cloud CDN can continue serving a stale\nversion. If not otherwise specified in the response, this is `86400s` (1 day).\n\nCloud CDN does not support the `stale-if-error` directive. This\ndirective instructs the cache to avoid serving stale content unless synchronous\nrevalidation with the backend has failed with particular error status codes.\n\nThe default, minimum, and maximum values are as follows:\n\n- Default: 86,400 seconds (one day)\n- Minimum: 0 seconds (disables the feature)\n- Maximum: 604,800 seconds (one week)\n\nStale content is served up to the specified limit past the cache entry\nexpiration time, which is defined by the `max-age`, `s-maxage`, or `Expires`\nheaders. For more information, see [Expiration times and validation\nrequests](/cdn/docs/caching#expiration).\n\nIf a Cloud CDN edge cache does not have a cached copy of the object to\nserve stale, or the object has reached the maximum stale TTL, Cloud CDN\nsynchronously revalidates the content with the origin. If the origin returns\nan error at that time, Cloud CDN returns the origin error.\n\nLogging and User Agent\n----------------------\n\nThe asynchronous requests made by Cloud CDN appear to your origin\nserver exactly like the normal revalidation requests that occur when not serving\nstale content. The exception is that they are tagged with a `User-Agent` header\ncontaining `Cloud-CDN-Google`.\n\nAsynchronous requests are also separately logged to Cloud Logging, so a user\nrequest that is served stale generates two log entries: the first for the\ncontent actually served to the user, and the second for the revalidation request\nto the origin. Like synchronous revalidations, Cloud CDN may send a\n[conditional request](/cdn/docs/caching#response-headers-validate) in some circumstances,\nor just re-request the content unconditionally. In either case, the response\ncode logged to Cloud Logging corresponds to the original request to\nCloud CDN; for example, a `200 OK` for an unconditional request, or a\n`304 Not Modified` if the user's original response was conditional.\n\nClient `max-stale` request directive\n------------------------------------\n\nClients can request a shorter stale service time by specifying a `max-stale`\ncache-control directive. If specified, this directive controls the amount of\nstaleness the client tolerates.\n\nIf the cached content is more stale than the client's `max-stale` value,\nCloud CDN revalidates the content before serving.\n\nThe client cannot request a `max-stale` value greater than the value\nconfigured with the `serve-while-stale` configuration option and the\n`stale-while-revalidate` cache-control directive from the origin.\n\nBefore you begin\n----------------\n\n- Read about [cache modes and static content](/cdn/docs/caching#cache-modes).\n\n- Ensure that Cloud CDN is enabled; for instructions, see\n [Using Cloud CDN](/cdn/docs/using-cdn).\n\n- If necessary, update to the latest version of the Google Cloud CLI:\n\n ```\n gcloud components update\n ```\n | **Note:** Make sure that you're using gcloud CLI version `322.0.0` or later.\n\nServe stale content while revalidating\n--------------------------------------\n\n### Console\n\n1. In the Google Cloud console, go to the **Load balancing** page.\n\n [Go to Load balancing](https://console.cloud.google.com/networking/loadbalancing/list)\n2. Click the name of your external Application Load Balancer.\n3. Click edit**Edit**.\n4. For **Backend configuration** , select a backend, and then click edit**Edit**.\n5. Make sure that **Enable Cloud CDN** is selected.\n6. At the bottom of the window, click **Advanced configurations**.\n7. For **Additional CDN options** , select one of the following options for **Serve while stale** :\n - 1 minute\n - 5 minutes\n - 10 minutes\n - 30 minutes\n - 1 day (recommended)\n - 7 days\n8. Click **Update**.\n9. Click **Update** again.\n\n### gcloud\n\nFor backend buckets, use the [`gcloud compute backend-buckets\ncreate` command](/sdk/gcloud/reference/compute/backend-buckets/create) or\nthe [`gcloud compute backend-buckets\nupdate` command](/sdk/gcloud/reference/compute/backend-buckets/update)\nwith the `--serve-while-stale` flag.\n\nFor backend services, use the [`gcloud compute backend-services\ncreate` command](/sdk/gcloud/reference/compute/backend-services/create) or\nthe [`gcloud compute backend-services\nupdate` command](/sdk/gcloud/reference/compute/backend-services/update) command\nwith the `--serve-while-stale` flag. \n\n```\ngcloud compute backend-buckets (create | update) BACKEND_BUCKET_NAME\n --serve-while-stale=SECONDS\n``` \n\n```\ngcloud compute backend-services (create | update) BACKEND_SERVICE_NAME\n --serve-while-stale=SECONDS\n```\n\nFor example: \n\n```\ngcloud compute backend-services update my-backend-service\n --serve-while-stale=180s\n```\n\n### API\n\nFor backend buckets, use the\n[`Method: backendBuckets.insert`](/compute/docs/reference/rest/v1/backendBuckets/insert) or\n[`Method: backendBuckets.update`](/compute/docs/reference/rest/v1/backendBuckets/update)\nAPI call.\n\nFor backend services, use the\n[`Method: backendServices.insert`](/compute/docs/reference/rest/v1/backendServices/insert) or\n[`Method: backendServices.update`](/compute/docs/reference/rest/v1/backendServices/update)\nAPI call.\n\nUse one of the following API calls: \n\n```\nPOST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendBuckets\nPUT https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendBuckets/BACKEND_BUCKET\nPOST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices\nPUT https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE\n```\n\nAdd the following snippet to the JSON request body: \n\n```\n\"cdnPolicy\": {\n \"serveWhileStale\": SECONDS\n}\n```\n\nDisable serving stale content\n-----------------------------\n\n### Console\n\n1. In the Google Cloud console, go to the **Load balancing** page.\n\n [Go to Load balancing](https://console.cloud.google.com/networking/loadbalancing/list)\n2. Click the name of your external Application Load Balancer.\n3. Click edit**Edit**.\n4. For **Backend configuration** , select a backend, and then click edit**Edit**.\n5. Make sure that **Enable Cloud CDN** isn't selected.\n6. At the bottom of the window, click **Advanced configurations**.\n7. For **Additional CDN options** \\\u003e **Serve while stale** , select **Disable serve while stale**.\n8. Click **Update**.\n9. Click **Update** again.\n\n### gcloud\n\nFor backend buckets, use the [`gcloud compute backend-buckets\ncreate`](/sdk/gcloud/reference/compute/backend-buckets/create) or\n[`gcloud compute backend-buckets\nupdate`](/sdk/gcloud/reference/compute/backend-buckets/update) command\nwith the `--serve-while-stale` flag value set to `0`.\n\nFor backend services, use the [`gcloud compute backend-services\ncreate` command](/sdk/gcloud/reference/compute/backend-services/create) or\nthe [`gcloud compute backend-services\nupdate` command](/sdk/gcloud/reference/compute/backend-services/update) command\nwith the `--serve-while-stale` flag value set to `0`. \n\n```\ngcloud compute backend-services (create | update) (BACKEND_SERVICE_NAME | BACKEND_BUCKET_NAME)\n --serve-while-stale=0\n```\n\n### API\n\nFor backend buckets, use the\n[`Method: backendBuckets.insert`](/compute/docs/reference/rest/v1/backendBuckets/insert) or\n[`Method: backendBuckets.update`](/compute/docs/reference/rest/v1/backendBuckets/update)\nAPI call.\n\nFor backend services, use the\n[`Method: backendServices.insert`](/compute/docs/reference/rest/v1/backendServices/insert) or\n[`Method: backendServices.update`](/compute/docs/reference/rest/v1/backendServices/update)\nAPI call.\n\nUse one of the following API calls: \n\n```\nPOST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendBuckets\nPUT https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendBuckets/BACKEND_BUCKET\nPOST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices\nPUT https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/BACKEND_SERVICE\n```\n\nAdd the following snippet to the JSON request body: \n\n```\n\"cdnPolicy\": {\n \"serveWhileStale\": 0\n}\n```"]]