Recursos · 63

Cache HTTP: proteger respostas personalizadas

Separe caches compartilhados, privados e de aplicativos, inspecione chaves, revalidação e invalidação após alterações de direitos de acesso.

Atualizado · 7 min

Corredor seguro de servidores e redes sem pessoas Ilustração editorial gerada com IA

O que este guia ajuda a alcançar

  • Camadas de inventário
  • Escolher retenção
  • Inspecionar chaves
  • Exercer revalidação e alteração

Verificação rápida

  • A ausência de cache significa que nada é retido?
  • "Vary" protege os direitos de acesso?
  • Toda API deve ser armazenada em cache?

Método passo a passo

  1. 1

    Camadas de inventário

    Listar caches de navegador, CDN, proxy, service worker e aplicativo. Classificar respostas públicas e personalizadas. Uma política HTTP não descreve automaticamente o cache implementado no código.

    Entregável: diagrama de camadas e proprietários.

  2. 2

    Escolher retenção

    A RFC 9111 distingue diretivas: "no-cache" requer validação antes da reutilização, "no-store" proíbe o armazenamento HTTP relevante e "unqualified private" exclui o armazenamento compartilhado. Nenhuma garantia isolada garante a confidencialidade do sistema.

    Entregável: política de retenção por resposta.

  3. 3

    Inspecionar chaves

    Verificar método, URI e dimensões que alteram uma representação. Variar as preocupações com os campos de solicitação; não se trata de autorização. Buscar idioma omitido, negociação de formato e contexto da conta nas camadas de aplicação.

    Entregável: chaves e testes de separação.

  4. 4

    Exercer revalidação e alteração

    Testar respostas novas e antigas, atualizações de dados e direitos revogados. Inspecionar ETag, validação condicional e comportamento de origem indisponível. Uma resposta anteriormente correta pode se tornar sensível após a revogação.

    Entregável: rastreamentos de antes e depois.

  5. 5

    Reprodução com duas contas.

    Usar identidades e marcadores fictícios. Alternar solicitações para o mesmo URI com caches quentes e frios. Verificar logout, links diretos e registro de logs sem gravar tokens reais.

    Entregável: testes negativos e estratégia de invalidação.

Medir a atualidade dos dados da cache

Exemplo fictício: estes dados não descrevem clientes nem resultados observados.

Situação

Duas leituras são rápidas, mas uma ainda mostra disponibilidade antiga depois de a fonte mudar.

Verificar

Comparar valor, versão, local de leitura e tempo desde a alteração. Testar invalidação, expiração e acesso à fonte segundo o contrato do sistema.

Agir

Definir a atualidade aceitável por utilização e vigiar divergências. Menor latência não demonstra coerência dos dados servidos.

Planilha reutilizável

Preencha com suas observações autorizadas. Estes campos são um modelo de trabalho, não resultados observados.

CampoInformações a serem registradas
RespostaPúblico ou personalizado; Dimensões
CamadaCache, proprietário e chave
PolíticaRetenção, atualização e validação
TesteConta fictícia, alteração e observação

Exemplo prático fictício

Situação ilustrativa

Exemplo fictício: uma CDN reutiliza uma resposta de perfil no mesmo URI para duas contas de teste.

Decisão e evidências esperadas

O cenário detecta vazamento, examina a política e as chaves e, em seguida, reproduz após a correção e a revogação do acesso.

Distinguir os mecanismos

MecanismoFinalidadeVerificação ou limitação
no-cachePermitir armazenamento com validação necessáriaNão interprete como ausência de armazenamento
Privado não qualificadoExcluir cache compartilhadoNão interprete como garantia de confidencialidade
no-storeImpedir o armazenamento HTTP relevanteVerificar caches e histórico do aplicativo separadamente

Indicadores de gestão

IndicadorO que medePrimeira ação
Separação de contasSem marcador de outra contaInspecionar corpo, links e metadados
Idade e validaçãoReutilização consistente com a políticaTestar expiração e origem indisponível
Atraso de invalidaçãoTempo até a representação corrigidaNomear cada camada ainda desatualizada

Erros comuns

  • Não interprete como ausência de armazenamento
  • Não interprete como garantia de confidencialidade
  • Verificar caches e histórico do aplicativo separadamente

Perguntas frequentes

A ausência de cache significa que nada é retido?

Não. Requer validação antes da reutilização; não proíbe o armazenamento como no-store.

"Vary" protege os direitos de acesso?

Não. Participa na seleção de representação; a autorização permanece separada.

Toda API deve ser armazenada em cache?

Não. Os benefícios dependem do custo, da atualização e do risco. Respostas sensíveis podem justificar evitar caches compartilhados.

ETag, cache HTTP e alterações concorrentes

As notas detalhadas desta edição estão disponíveis em inglês.

ETag: revalidate responses and prevent lost updates

An ETag is an opaque validator for the selected representation. It compares versions; it is neither authorisation nor an access token, and it need not be a file hash. Personalised responses require separate decisions about access, cache selection and HTTP conditions.

Local teaching model: a representation already exists; at most one conditional field contains a single ETag or *. GET, HEAD and PUT are covered. Tag lists, date validators, ranges, creation, combined conditions and the already-succeeded modification exception are excluded. No network call, storage or state change occurs; this does not test your API.

Laboratório de rede fictício sem pessoas, com equipamentos numa bancada escura com luz âmbar. Ilustração editorial gerada com IA
Generated conceptual scene: a fictional empty network laboratory. It shows neither a real facility nor a protocol measurement.

Strong and weak ETag comparison serve different purposes

If-Match requires strong comparison: neither tag may start with W/. If-None-Match uses weak comparison, matching the opaque values regardless of W/. Values remain case-sensitive. The * wildcard checks representation existence here, not a particular version.

Strong and weak ETag comparison serve different purposes
Current tagReceived tagStrong comparisonWeak comparison
"v1""v1"MatchesMatches
"v1"W/"v1"Does not matchMatches
W/"v1"W/"v1"Does not matchMatches
"v1""v2"Does not matchDoes not match
"v1""V1"Does not matchDoes not match

Simulate an HTTP decision without contacting a server

The six parameters yield 432 combinations. Requiring a conditional field and selecting 204 for successful PUT are policies of this fictional scenario. Requiring any condition does not prevent every lost update: If-Match: * compares no version.

Model decision : 304

304: If-None-Match finds a weak match for GET or HEAD. Reuse the stored representation under cache rules with the revalidation metadata.

304 and 204: no response content.

Request excerpt

GET /demo/resource HTTP/1.1
Host: api.example.test
If-None-Match: W/"v1"

Response excerpt

HTTP/1.1 304 Not Modified
Date: Thu, 22 Oct 2026 00:00:00 GMT
ETag: "v1"
Cache-Control: private, no-cache

Fictional HTTP/1.1 excerpts for reading: bodies are omitted even where allowed. api.example.test is an example domain. The date is fixed. This model does not update the ETag after PUT; the separate walkthrough follows successive versions.

Ten reproducible situations

Ten reproducible situations
Fictional situationCondition and expected outcomeInterpretation
Read using a weak tagGET · "v1"
If-None-Match: W/"v1" → 304

Access allowed · Conditional field optional

W/"v1" and "v1" match weakly.
Different client versionGET · "v1"
If-None-Match: "v2" → 200

Access allowed · Conditional field optional

The client needs the selected representation.
HEAD revalidationHEAD · "v1"
If-None-Match: "v1" → 304

Access allowed · Conditional field optional

The status can be 304; the response has no content.
Write based on an old versionPUT · "v2"
If-Match: "v1" → 412

Access allowed · Conditional field optional

Read again and resolve the conflict before retrying.
Weak tag with If-MatchPUT · "v1"
If-Match: W/"v1" → 412

Access allowed · Conditional field optional

Strong comparison rejects a weak tag.
Required condition absent on PUTPUT · "v1"
none → 428

Access allowed · Conditional field required

428 follows the policy announced by this API.
Access denied despite matching tagGET · "v1"
If-None-Match: "v1" → 403

Access denied · Conditional field optional

Authorisation precedes HTTP conditions.
Write on the correct versionPUT · "v1"
If-Match: "v1" → 204

Access allowed · Conditional field required

The model accepts PUT and selects a 204 success.
If-None-Match: * on existing dataPUT · "v1"
If-None-Match: * → 412

Access allowed · Conditional field optional

The wildcard matches any existing representation.
If-Match: * on existing dataPUT · W/"v1"
If-Match: * → 204

Access allowed · Conditional field required

The wildcard passes even with a weak current tag: it does not protect a version.

Four rules for a personalised response

Four rules for a personalised response
Response fieldHTTP effect within this scopeEvidence to retain
Cache-Control: no-cacheUnqualified no-cache permits storage, but any reuse needs successful validation with the origin server.Observe a conditional round trip; do not read no-cache as a storage prohibition.
Cache-Control: no-storeForbids storage by private and shared HTTP caches. It is not a general privacy guarantee.Also review logs, history, screenshots and application storage.
Cache-Control: privateUnqualified private forbids storage by a shared cache; a private cache may store under the other constraints.Distinguish browser, proxy and CDN. A directive does not replace access checks.
VaryAdds the named request fields to selection of a stored response. It does not decide who may access a resource.Test relevant variants. Do not assume a cookie or Authorization automatically prevents all caching.

Useful API acceptance evidence

  • Expected request and status: method, test resource, access rights, conditional field and current ETag. Use fictional data and remove secrets.
  • Observed response: status, ETag, Date, Cache-Control, Vary and no content for HEAD, 204 or 304. A 304 must carry the required metadata that would have accompanied the 200.
  • Concurrency: verify that a stale write fails without changing the resource; retain the conflict-resolution decision. Do not blindly replace the ETag and resend the same write.

Follow the two-client conflict →

Primary references and limits

The standards define HTTP conditions and caching. The ten cases, laboratory and two-client walkthrough are original illustrations. Displayed results are calculated by this local model, not measurements of this site or your infrastructure.

References reviewed

Referências oficiais

As referências apoiam o método. Adapte as verificações ao seu contexto; elas não são uma certificação. Os títulos das referências originais e os documentos de origem podem estar em outro idioma.

Referências consultadas em .