Skip to content
ADE
API Design EssentialsBETA

[ADE-361] HTTP Caching ​

Overview ​

This document outlines the guidelines and best practices for implementing HTTP caching in RESTful APIs to improve performance, reduce latency, and decrease server load.

Background Knowledge ​

HTTP Caching Headers ​

HTTP caching is controlled through specific headers in HTTP requests and responses. The primary headers used for caching are:

  • Cache-Control
  • ETag
  • Last-Modified
  • Expires

Implementation Details ​

Server-Side Implementation ​

  1. Generate ETags: Ensure that each resource has a unique ETag and include it in the response header.
  2. Set Cache-Control Directives: Determine the appropriate caching policy for each endpoint and include the Cache-Control header.
  3. Include Last-Modified: Set the Last-Modified header to the last modification date of the resource.
  4. Handle Conditional Requests: Implement logic to handle If-None-Match and If-Modified-Since headers and return 304 Not Modified status if the resource has not changed.

Client-Side Implementation ​

  1. Store Cache Headers: Store ETag, Last-Modified, and other relevant headers along with the cached response.
  2. Include Conditional Headers: When making a request, include If-None-Match and If-Modified-Since headers to validate the cache.
  3. Handle 304 Responses: Update the cache if a 304 Not Modified status is received, maintaining the same response data.

Example Endpoint ​

http
GET /resource/123 HTTP/1.1
Host: example.com
If-None-Match: "abc123"
If-Modified-Since: Tue, 20 Jul 2021 19:30:00 GMT

HTTP/1.1 200 OK
Cache-Control: public, max-age=3600, must-revalidate
ETag: "abc123"
Last-Modified: Tue, 20 Jul 2021 19:30:00 GMT
Expires: Wed, 21 Jul 2021 19:30:00 GMT
Content-Type: application/json

{
  "id": 123,
  "name": "Resource Name",
  "updatedAt": "2021-07-20T19:30:00Z"
}

Guidance ​

  • MUST implement caching mechanisms for all GET requests that return static or semi-static data.
  • SHOULD use ETags for all resources that may change over time.
  • SHOULD set appropriate Cache-Control headers based on the resource's volatility and access patterns.
  • MAY use different caching strategies for different types of resources or endpoints.
  • SHOULD document caching behavior in API documentation.

References ​

Changelog ​

  • 2024.09.24 Remove unwanted /api path in the samples
  • 2024.10.01 Add reference topic