Caching REST APIs

Caching refers to storing rest endpoints response, to reduce the number of roundtrips to the server.
This improves the latency and increases the performance of the API.

Caches can be anywhere in the request path. They can be in the API’s server, content delivery networks (CDNs), or the client side.
HTTP provides a built-in caching framework through cache headers. These headers need to pass with requests.

HTTP Cache Headers

Cache-Control Headers

Cache-control is an HTTP header used to specify browser caching policy for client requests and server responses. These header specifies how, where & how long resource should be cached.

The cache-control header is broken up into directives, the most common of which are detailed below:

Cache-Control: Max-Age

The max-age=N response directive indicates that the response remains fresh until N seconds after the response is generated.

Cache-Control: No-Cache

No-Cache directive indicates that a browser may cache a response, but must first submit a validation request to an origin server.

Cache-Control: No-Store

No-Store directive indicates that browsers aren’t allowed to cache a response and must pull it from the server each time it’s requested.

Cache-Control: Public

Public directive indicates that the response may be cached by any cache, even if it would normally be non-cacheable or cacheable only within a non- shared cache.

Cache-Control: Private

This indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache.

Expires

The Expires entity-header field gives the date/time after which the response is considered stale.
Expires: Thu, 01 Dec 2022 16:00:00 GMT this indicates that cached resource expires at Thu, 01 Dec 2022 16:00:00 GMT
Note: If a response includes a Cache-Control field with the max-age directive, that directive overrides the Expires field

Etag or Entity tag

An ETag value is an hash string token computed from the response body, that a server associates with a resource to uniquely identify the resource.