デフォルトでHTTPレスポンスがキャッシュされるのはどんな場合か

HTTP APIのキャッシュ戦略を考えながら、ふとcache-controlなどを指定しなかったとき、デフォルトのキャッシュ戦略はどのように定義されているのか気になったので調べた。

Storing Responses in Caches

RFC7234のStoring Responses in Cachesにレスポンスをキャッシュしてもよい条件が述べられている。

A cache MUST NOT store a response to any request, unless:

  • The request method is understood by the cache and defined as being cacheable, and the response status code is understood by the cache, and
  • the "no-store" cache directive (see Section 5.2) does not appear in request or response header fields, and
  • the "private" response directive (see Section 5.2.2.6) does not appear in the response, if the cache is shared, and
  • the Authorization header field (see Section 4.2 of RFC7235) does not appear in the request, if the cache is shared, unless the response explicitly allows it (see Section 3.2), and
  • the response either:
    • contains an Expires header field (see Section 5.3), or
    • contains a max-age response directive (see Section 5.2.2.8), or
    • contains a s-maxage response directive (see Section 5.2.2.9) and the cache is shared, or
    • contains a Cache Control Extension (see Section 5.2.3) that allows it to be cached, or
    • has a status code that is defined as cacheable by default (see Section 4.2.2), or
    • contains a public response directive (see Section 5.2.2.5).
RFC 7234 - Hypertext Transfer Protocol (HTTP/1.1): Caching

(マークアップは筆者による)

Cacheable Methods

まず1つ目でHTTPメソッドがcacheableであるかとある。特に言及はないけどRFC7231で定義されている。

this specification defines GET, HEAD, and POST as cacheable, although the overwhelming majority of cache implementations only support GET and HEAD.

RFC 7231 - Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content

注意したいのはPOSTもcacheableである点。「ほとんどの実装は対応していないけどね」と但し書きされているが、明示しておくに越したことはなさそう。

a status code that is defined as cacheable by default

巡り巡ってRFC7231のSection 6.1で定義されている。

Responses with status codes that are defined as cacheable by default (e.g., 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501 in this specification

RFC 7231 - Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content

501 Not Implementedはキャッシュ可能と定義されているので、5xxがキャッシュされないという認識でいると注意が必要かもしれない。

その他

range付きリクエストのレスポンスのキャッシュ戦略については別途述べられているが、必要としなかったので読んでいない。

結論

  • HTTPメソッドがGET, HEADもしくはPOSTの場合で、かつ特定のステータスコードの場合はキャッシュ可能と定義されている

まずどんなcache-controlが付けられそうか考えるだけでも、HTTP APIの特徴を掴めそうなのでこれからもやっていきたい。