Skip to content
javahacks.dev
Spring MVC

HTTP Cache Headers Spring Configuration for REST Responses

Set HTTP cache headers in Spring: Cache-Control, max-age, no-store, private versus public, Vary, stale-while-revalidate and static resource caching.

6 min read
Summarize in AI
Flat illustration of an app reading through a fast cache in front of a database, with the Spring, Spring Boot, Redis, NGINX and Hibernate logos.

HTTP caching lets browsers, proxies and CDNs reuse responses without asking your server. A few headers decide what is allowed, and the defaults are cautious. This is the headers side of caching; revalidation with tags is in ETags.

Cache-Control basics

java
@GetMapping("/countries")
ResponseEntity<List<Country>> countries() {
    return ResponseEntity.ok()
            .cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePublic())
            .body(countryService.all());
}

The response has Cache-Control: max-age=3600, public. Clients and shared caches may reuse it for an hour without contacting the server.

DirectiveMeaning
max-age=NFresh for N seconds in any cache
s-maxage=NSame, for shared caches only
publicMay be stored by shared caches
privateOnly the end user's cache
no-cacheStore, but revalidate before use
no-storeDo not store at all
must-revalidateOnce stale, do not serve without checking
stale-while-revalidate=NServe stale for N seconds while refreshing in the background
immutableNever changes while fresh, skip revalidation on reload

A frequent confusion: no-cache does not mean "don't cache", it means "check first". Use no-store for sensitive data.

Choose by data type

java
// Reference data: shared, changes rarely
CacheControl.maxAge(Duration.ofHours(1)).cachePublic().staleWhileRevalidate(Duration.ofMinutes(5))

// Per-user data: browser only
CacheControl.maxAge(Duration.ofSeconds(30)).cachePrivate()

// Must always be fresh but may use a validator
CacheControl.noCache()

// Never stored: tokens, personal documents
CacheControl.noStore()

An API behind authentication should send private or no-store for personal data, so a CDN does not serve one user's response to another. Caching mistakes of that kind are security incidents, which fits the concerns of Java security basics.

Vary

If a response differs by a request header, tell caches:

java
return ResponseEntity.ok()
        .cacheControl(CacheControl.maxAge(Duration.ofMinutes(10)).cachePublic())
        .varyBy("Accept", "Accept-Language")
        .body(content);

Vary: Accept makes the cache store a copy for each distinct Accept. Without it, a JSON client could receive a cached XML response. Avoid Vary: * and Vary: Cookie on public data, which defeat sharing.

Static resources

Spring Boot can set cache headers for static files:

properties
spring.web.resources.cache.cachecontrol.max-age=365d
spring.web.resources.cache.cachecontrol.cache-public=true
spring.web.resources.chain.strategy.content.enabled=true
spring.web.resources.chain.strategy.content.paths=/**

The content strategy adds a hash to the file name (app-3f9a1c.js), so a changed file gets a new URL and you can cache the old URLs for a year. Without versioned URLs, a long max-age leaves users with stale files.

Global defaults

Spring MVC adds Cache-Control: no-cache, no-store, max-age=0, must-revalidate for responses from Spring Security's default headers. That is correct for APIs, and it means public endpoints must set their own headers explicitly, with the security configuration allowing it. Check the actual header:

Shell
curl -I https://api.example.com/countries

Verify with a CDN

CDNs have their own rules for s-maxage, Surrogate-Control and query string handling. Test with the CDN in place, and look for headers such as Age and X-Cache. A cache hit that you did not expect is a bug in Vary or private.

Per-path rules with WebContentInterceptor

Setting headers in each controller works for a few endpoints. For a rule that covers a path prefix, register an interceptor once:

java
@Configuration
class CachingConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebContentInterceptor interceptor = new WebContentInterceptor();
        interceptor.addCacheMapping(CacheControl.maxAge(Duration.ofHours(1)).cachePublic(), "/countries/**");
        interceptor.addCacheMapping(CacheControl.noStore(), "/account/**");
        registry.addInterceptor(interceptor);
    }
}

The mapping applies to the responses of matching handlers that did not set Cache-Control themselves. A controller that sets its own header wins, which keeps the exception local to the code that needs it.

Spring Security overrides what you set

Spring Security adds Cache-Control: no-cache, no-store, max-age=0, must-revalidate, Pragma: no-cache and Expires: 0 to every response by default. A controller that sets max-age=3600 on a secured path loses to those headers or produces two conflicting values, depending on order. For a public endpoint, either exclude it from the security chain or turn the default off for that chain:

java
@Bean
SecurityFilterChain publicApi(HttpSecurity http) throws Exception {
    http.securityMatcher("/countries/**")
        .authorizeHttpRequests(a -> a.anyRequest().permitAll())
        .headers(h -> h.cacheControl(c -> c.disable()));
    return http.build();
}

Keep the default on for every chain that serves user data. Disabling it there is how one user's page ends up in a shared cache.

Static assets with a resource handler

If the application serves its own files, a handler can set the policy for the folder:

java
registry.addResourceHandler("/assets/**")
        .addResourceLocations("classpath:/static/assets/")
        .setCacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic().immutable());

A year of immutable caching is safe only for files whose names change when their content does. Pair it with the content hash strategy from the previous section, and keep HTML pages on no-cache, since they are what refers to the hashed names.

Reading the headers a client actually receives

Verify with curl -i and read three things: the final Cache-Control, whether Vary is present and correct, and whether Age or a CDN's hit header shows a shared cache in use. A repeated request with If-None-Match should return 304 Not Modified with no body when an ETag is in play:

Shell
curl -i https://api.example.com/countries
curl -i -H 'If-None-Match: "0a1b2c"' https://api.example.com/countries

Browser behaviour worth knowing

Chrome and Firefox treat a reload as permission to revalidate, so a page reload sends conditional requests even for fresh resources, unless the resource is marked immutable. A navigation by link or the address bar can use the cache without any request. Test with both, since a long max-age that seems to be ignored is often a reload.

Header combinationBrowser result
max-age=3600No request for an hour on a normal navigation
no-cache and an ETagA request every time, a 304 when unchanged
no-storeA full request and response every time
No Cache-Control and a Last-ModifiedHeuristic freshness, about a tenth of the file's age

That last row catches people out. With no explicit policy, a cache may keep a response for a period it chose itself. State the policy on every cacheable response, and the heuristic never applies.

Choosing lifetimes from how data changes

A lifetime is a statement about how stale a response may be, so it should come from the data and not from habit. A table of countries changes a few times a year, and a day or a week is safe. A product price changes during the day, and a few minutes is acceptable if a price shown a little late is not a defect. A stock level or an account balance changes constantly, and caching it in a shared cache is wrong unless the business accepts the lag.

Ask the owner of the data how stale is acceptable, write the answer into the code as a named constant, and review it with the same care as a timeout. When invalidation matters, prefer a short max-age with stale-while-revalidate over a long one with a purge process that someone has to run.

Where this does not apply

POST, PUT and DELETE responses are not cached in practice. Data that must be consistent immediately after a write needs no-cache or short lifetimes and careful invalidation. The headers sit in a controller like the ones in writing a REST controller and using ResponseEntity. The reference is RFC 9111 on HTTP caching, and the MDN guide to caching is a practical read.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.