HTTP’s caching mechanism reduces bandwidth and speeds up web performance by avoiding the unnecessary transfer of unchanged resources. Using cached data will become useful for consumers to load configurations and catalogs of information that are not meant to change much over time. When using caching make sure to include Cache-Control information in the headers. This will help users effectively use the caching system.
Let’s review a typical client-server interaction using caching and the 304 Not Modified status, as shown in the following steps:
Initial request:
The client requests a resource, GET /index.html HTTP/1.1, and the server returns a 200 OK response with the resource and caching headers like ETag and Last-Modified, as shown in the following response:
HTTP/1.1 200 OK
Content-Type: text/html
ETag: "686897696a7c876b7e"
Last-Modified: Tue, 21 Oct 2024 07:28:00 GMT
Cache-Control: max-age=3600
The client stores the ETag and Last-Modified values along with the cached version of the resource.
In subsequent requests, the client sends them back to the server to check whether the resource has been modified. The ETag value is typically a hash or a version number that uniquely identifies the resource at that particular state.
Subsequent request:
The client makes another request for the same resource but includes conditional headers to check if the cached version is still valid, as shown in the following request:
GET /index.html HTTP/1.1
If-None-Match: "686897696a7c876b7e"
If-Modified-Since: Tue, 21 Oct 2024 07:28:00 GMT
If-None-Match contains the ETag from the previous response. If-Modified- Since contains the Last-Modified date from the previous response.
304 Not Modified Response:
If the server determines that the resource has not changed, it returns a 304 Not Modified status with relevant headers:
The headers in a 304 response provide information for managing the cache and ensuring that the client can continue to serve fresh content efficiently.