What is an ETag Header:- An ETag or entity tag is is an HTTP header used for web cache validation. It provides a mechanism to cache unchanged resources and hence reduce the network bandwidth.
The value of an ETag is an identifier which represents a specific version of the resource.
Here’s an example ETag header:
Generating ETag value: Specification of ETag does not order how to generate ETag values. That’s entirely up to the application to generate it as it wants. It can be created and updated manually or can be auto generated. Common methods of its auto-generation include using hash of the resource’s content or just hash of the last modification timestamp.
Note: The generated hash should be collision free. Hash-Collision is the situation when two or more inputs to a hash function give the same output.
ETag value validation: Validation of ETag value is nothing but comparing the two values (the one which received in request header ‘If-None-match’ and the one which is currently representing the resource). There are two validation approaches.
How it works?
Followings are the general steps
1. Server receives a normal HTTP request for a particular resource.
2. The server prepares the response and includes the header ‘ETag’ with it’s value in the response:
for ex: ETag: “response_version1”
3. Server sends the response with above header with the status code 200. Then the application renders the resource and at the same time caches the resource copy along with header information.
4. Later the same application makes another request for the same resource with following conditional request header:
5. On receiving the request for the resource along with ‘If-None-Match’ header, the server side logic checks whether a new copy of the resource by comparing the current value of the ETag identifier on the server side and the one which is received in the request header.
If request’s If-None-Match is same as currently generated/assigned value of ETag on the server, then status code 304 (Not Modified) with the empty body is sent back and the application uses cached copy of the resource.
If request’s If-None-Match value doesn’t match the currently generated/assigned value of ETag (say “response_version2”) for the same resource then server sends back the new content in the body along with status code 200. The ‘ETag’ header with the new value is also included in the response. The application uses the new resource and updates its cache with the new data.
Hope it will be helpful for you and if you have any doubt then comment below.