httpbrowser-cachecache-controletag

ETag update after resource modification


Let's assume I have the following 2 endpoints, which get and update a resource on my server:

GET /myResource

PUT /myResource

We would now like to implement browser caching to minimize the load on our servers by using the ETag header.

Lets assume the following flow

  1. User gets the /myResource. My server computes the ETag for that current resource, and returns it to the client. For example, this value is $eTag1
  2. The user updates the /myResource. My server computes the new ETag of the updated resource. For example, $eTag2

The Question

When the user tries to fetch the /myResource again, will the browser use the ETag value after the resource update (namely $eTag2), or will it stick to the old ETag value (namely $eTag1)?

My concern is that the browser might treat GET /myResource and PUT /myResource as two different resources. Thus updating the resource with the PUT request will not update the internal browser cache.


Solution

  • Short version: Updating a resource in this way will work fine.

    Long version: You're conflating two separate things: caching, and conditional validation.

    You control caching (see RFC 9111) with the Cache-Control header, which determines how long a cache can serve a resource. During this freshness lifetime the cache will serve the resource without checking with the origin server. The ETag is irrelevant.

    After the resource is no longer fresh the cache can, if the ETag header is present, make a conditional request (see RFC 9110) to the origin server such that the full response will only be returned if the resource has changed.

    So there are two questions here. First, does sending a PUT while the resource is fresh cause the cache to be invalidated? Yes: "Because unsafe request methods... have the potential for changing state on the origin server, intervening caches are required to invalidate stored responses to keep their contents up to date." The next request will be handled by the origin server.

    Second, does sending a PUT to the origin server cause the resulting ETag to change such that a subsequent conditional request will lead to the new resource being returned? Yes, that is fundamental to how conditional requests work.