diggersworld
diggersworld

Reputation: 13080

Using Last-Modified and If-Modified-Since on a RESTful API

I've been reading a few articles regarding setting headers for Last-Modified when a response is sent from a server. I understand the purpose for it, and how to set it, etc.

I also understand the incoming If-Modified-Since header and that it's asking has anything changed since this time. I understand how to retrieve the header and convert it to a timestamp, etc.

The aspect I'm struggling to get my head around is what I compare the modified since timestamp with. My understanding is that by using last modified I don't need my API to keep retrieving masses of data if it's still the same.

So, am I supposed to make a super lightweight call to the API's cache/database and just check for the last modification to whatever dataset is being requested?

Upvotes: 2

Views: 3308

Answers (2)

Paul Draper
Paul Draper

Reputation: 83245

So, am I supposed to make a super lightweight call to the API's cache/database and just check for the last modification to whatever dataset is being requested?

Last-Modified/If-Modified-Since enables two optimizations:

  1. Conditionally skipping data retrieval on the server. Examples:
  • Query a PostgreSQL database for the timestamp. If necessary, perform additional queries to retrieve the data.

  • Query a Redis cache. If necessary, query the MySQL database to retrieve the data.

  • Propagate the value upstream to a S3 bucket, which will skip sending the object using the same criteria.

  1. Conditional skipping data transfer to the client. I.e. 304 Not Modified.

(1) is heavily dependent on your architecture. (2) is available almost always.

Upvotes: 0

Jonathan W
Jonathan W

Reputation: 3799

It's going to depend on the nature of the resource being requested, but I would think that you would want to take advantage of the web server's caching mechanism itself wherever possible. If you're using Apache, for instance, mod_cache should be the starting point for your HTTP caching needs. I'd try and avoid manually implementing a full cache header implementation because you're likely to miss something, such as inadvertently introducing security risks to your application.

Upvotes: 2

Related Questions