Understanding ETag and Its Costs

ETag provides lots of benefits to users, but it also has a cost.

Let's consider an ETag generated through Express for a dynamic page.

When a request is received by Node.js or Express, it queries the database and prepares a dynamic page. After that, it also generates an ETag using the data through SHA-1 hashing.

This operation consumes CPU resources.

The catch

Many people think that once an ETag is generated, everything becomes easy and no further work is required by Express.

But there is a catch.

When another request reaches Express, it has to perform the same operations again:

  • Fetch data from the database.
  • Prepare the dynamic page.
  • Serialize the data.
  • Generate a new hash.
  • Compare the newly generated ETag with the If-None-Match header.
  • If both ETags match, return 304 Not Modified; otherwise, return the complete response.

So, what do we actually save from this?

We primarily save network bandwidth.

However, note that Express still performs the database query, serialization, and hashing operations.

What if we use web server or proxy caching?

Now, consider another scenario where we involve web server caching or proxy caching.

In this case, those operations can be handled by the web server or proxy cache.

When a browser sends a request for revalidation, Nginx can use its cached response and compare the stored ETag with the If-None-Match header.

If they match, Nginx can return 304 Not Modified directly.

The request doesn't reach Node.js or Express.

This way, we don't need to perform the database query, serialize the data, or generate another hash for every revalidation request.