Here you will find instructions for providing and configuring a global cache and a default cache for the Spring Cloud Gateway.

Configure HTTP response cache

This feature provides a way to define a HTTP response cache that can be applied at route-level or globally.

According to HTTP specifications, there are some considerations to take into account when activating this feature:

  • It only caches responses when the request is bodiless and has the HTTP method GET.
  • It only caches responses with the following status codes: HTTP 200 (OK), HTTP 206 (Partial Content) and HTTP 301 (Moved Permanently).
  • Response data will not be cached if the Cache-Control header does not allow it (no-store in the request, no-store or private in the response).
  • If the response is already cached and a new request is performed with the no-cache value in the Cache-Control header, it will return a bodiless response with 304 (Not Modified).

The parameter local.timeToLive sets the time to expire a cache entry (expressed in s for seconds, m for minutes, and h for hours) and local.size sets the maximum size of the cache to evict entries for this route (in KB, MB and GB).

activating the cache without specifying any other configuration will activate the local response cache implementation with a default time to live for cached items of 5 minutes.

To set the response cache size to 8MB and a time to live of 10m, use:

{ "response-cache": { "local": { "size": "8MB", "timeToLive": "10m" } } }

The local response cache implementation automatically calculates and sets the max-age value in the HTTP Cache-Control header. Only if max-age is present on the original response will the value be rewritten with the number of seconds set in the timeToLive configuration parameter. In consecutive calls this value will be recalculated and set to the number of seconds left before the cached entry is evicted.

In order to avoid repeating the LocalResponseCache filter in every route, the flag local.global can be set to true and all the routes will cache.

To add a 1MB response cache with a time to live of 50s to every route, use:

{ "response-cache": { "local": { "global": true, "size": "1MB", "timeToLive": "50s" } } }
check-circle-line exclamation-circle-line close-line
Scroll to top icon