Idempotence, REST and Caching

What is Idempotence and 'safety'?

Idempotence means the result will never be changed, you can keep calling the method, but the response you get back will always be the same. It is possible that something is being changed on the server, but the result not changing is what defined something to be idempotent.

Safety is where the resource on the server is not changed in any way. Things might happen on the server, but the resource itself is not modified. Consequently, the result is never changed either.

The set of safe HTTP methods is a subset of the idempotent methods.

Idempotent HTTP methods

OPTIONS, GET, HEAD, PUT, DELETE

Safe HTTP methods

OPTIONS, GET, HEAD

Browser/Proxy/Gateway Caching

Caching of an HTTP response may occur in a number of different places - it could be within the browser itself, in a proxy server or on a gateway server (also known as a reverse proxy cache).

Caching can only occur for the safe HTTP methods OPTIONS, GET and HEAD. To prevent this (or to have control over it) we need to play with the HTTP response headers.

Cache Expiration (cache-control: max-age=n or expires)

Cache expiration headers will prevent the cache from making the same request until the cached version reaches its expiration time and becomes "stale". If both the cache-control and expires headers are set then on most modern systems the cache-control will take precendence.

Cache Validation (last-modified and etag)

These are called 'cache validator' headers because they are used to validate the freshness of the stored response in the cache, without requiring your backend system to generate or transmit the response body.

A 304 Not Modified will be returned if the currently cached response does not differ from the response values returned by the cache validator.

Combining cache expiration and validation

Cache expiration is checked first, then cache validation occurs if the cache entry has expired. If the cache entry hasn't expired, it will return a 200 OK response. If the cache entry has expired but the request is validated as still being fresh then a 304 Not Modified header is returned, and this 304 response will have updated expiration header info.

Resources
https://www.mnot.net/cache_docs/
http://tomayko.com/writings/things-caches-do
http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/
http://www.peej.co.uk/articles/http-caching.html
https://redbot.org/ - for cache testing