0

I'm trying to control the caching of resources from my server and I have verified that putting the following headers on my HTTP responses causes the browser to cache resources as expected.

Cache-Control: must-revalidate, max-age=30
Last-Modified: Mon May 19 11:21:05 GMT 2014
Expires: Mon May 19 11:51:05 GMT 2014

When the resource in the browser cache has expired the next GET on that resource from that particular client contains then a "If-Modified-Since" header is added to the GET request which makes it to the origin server.

Especially in a Java webapp context what is a good way to handle the determination of whether the resource has changed on the server-side when it gets these conditional GET requests so it can decide whether to return a 304 Not Modified or 200 OK response?

I have a few ideas but they are all custom solutions that seem like re-inventing the wheel to me:

  1. Just have some custom query that checks the resource last modified date. (This is the most obvious way to do it)

  2. Have a cache on the server that is independently kept in-sync with the resource update state so that the server can do a very quick check for resource modification, perhaps using a DB table listener from Spring Framework (this would be more efficient than having to do a query for each client each time, however, it is more complex to implement)

whitestryder
  • 451
  • 5
  • 10

1 Answers1

1

If you have a cache layer between the controller and the database, you shouldn't worry about the "If-Modified-Since" header.

  • As long as the resource is not modified, you'll get it really quickly from the cache;
  • After the resource is modified, it will be retrieved from the DB and added to the cache layer.

Checking the modified data, might be slower than getting the resource from the cache, as it hits the database.

Danix
  • 1,947
  • 1
  • 13
  • 18
  • I don't think I want to keep the entire resource in the cache because I do not need to return the resource if it is not modified but I think your answer is reasonable given the question I asked. I think that in this case all I need though is a cache keyed on the resource URL and the value retrieved from the cache for this key could be the "Last Modified" date of the resource. – whitestryder May 19 '14 at 21:36
  • You might consider using an [`ETag`](http://tools.ietf.org/html/rfc2616#section-14.19) instead of, or at last in addition to, a modification date/time. Whenever the resource is changed, simply create a new `ETag` value for it. As long as the resource's `ETag` does not change, you can keep returning `304 Not Modified`. If you include an `ETag` in a reply, the client must include that `ETag` in a `If-Match` or `If-None-Match` header in any conditional GET request. See RFC 2616 Section 13.3.4 for more details. – Remy Lebeau May 20 '14 at 00:15
  • Yep, I've additionally implemented ETag now and it works well. – whitestryder Sep 26 '16 at 17:06