Before we start, we recommend reading these two articles, for those who are not familiar with ETags or CQRS.
In this article we will describe how we used ETags on top of the CQRS pattern implemented into the Demo Reservation Application, so check Using CQRS in Demo Reservation Application if you haven't already done so.
Why we decided to use ETags/The motivation of using ETags
Here is the overview of reservations described, upon clicking the button a table with the last 50 reservations created is shown. But what happens if someone else creates a new reservation or cancels one of the shown on your table? The answer is simple, nothing. You would have to click on the button again and refresh the data. We decided that we don't want to leave the freshness of the data up to the user whether the user clicks on the button or not, so we implemented polling. Polling is a mechanism that automatically sends a request after some time interval. Perfect, it is easy to implement and the data are refreshed every 5 seconds. But with polling comes an unnecessary transfer of the data, because sometimes no changes were made, therefore the refresh was unnecessary. This is the moment when ETags come in handy.
When the state of the data is changed (create or cancel reservation) a new hash is generated and stored along with the data in redis cache.
After the first request to get the overview of the reservations, the api component sends the data also with the ETag. Next time the request is sent with the ETag
so that the api component can compare the received ETag with the one stored in the redis cache. The data are then sent only if the two values don't match,
response with the status code
304 Not Modified is sent otherwise.
You can see an example of use described with the following sequence diagram.