Video in progress

Middle 🌱 Spring

How do you cache responses in Spring MVC with ETag and Cache-Control headers?

For GET responses that rarely change, you set cacheControl(...) and eTag(...) on the ResponseEntity. The next time the client sends If-None-Match; if the version hasn't changed, Spring returns a 304 with no body and saves traffic.

📖 Answer

@GetMapping("/api/products/{id}")
ResponseEntity<ProductDto> get(@PathVariable long id, WebRequest request) {
    Product p = service.find(id);
    String etag = "\"" + p.getVersion() + "\"";

    if (request.checkNotModified(etag)) {
        return null;                       // Spring sends the 304 itself
    }
    return ResponseEntity.ok()
        .eTag(etag)
        .cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePrivate())
        .body(mapper.toDto(p));
}

For the ETag we took the entity's @Version value: it increments on every change, so it's cheap and reliable. In fact, if you set eTag on the ResponseEntity, Spring also checks If-None-Match itself; checkNotModified also saves the work of converting to a DTO.

A quicker way is ShallowEtagHeaderFilter. It computes a hash from the response body and sets the ETag. But there's a catch: the controller still runs in full and hits the database. The savings are only on the network.

Which directive:

  • user-specific data: private, or no-store altogether;
  • a catalog that's the same for everyone: public, max-age=..., and a CDN can cache it too;
  • something that changes fast, like a balance: no-cache, meaning validate with the ETag every time.

Spring Security sets Cache-Control: no-cache, no-store by default, but if the response already has a Cache-Control you set yourself, it doesn't overwrite it.