ETag Conditional Request Spring Support for REST APIs
Add ETags to a Spring REST API: ShallowEtagHeaderFilter, strong ETags from a version, If-None-Match for 304 responses and If-Match for lost update protection.

Conditional requests let a client and a server agree on which version of a resource they are both talking about. They give two things for little code: cheaper reads, because an unchanged resource needs no body, and safer writes, because an update based on stale data is refused. Both rely on the same header, the ETag, an opaque tag that changes whenever the representation changes. The examples use Spring Boot 4 and a JPA entity with a version column.
The exchange
GET /orders/42
200 OK
ETag: "7"
...
GET /orders/42
If-None-Match: "7"
304 Not ModifiedThe client stores the response with its tag. The next time it needs the order it asks again, sending the tag in If-None-Match. If the tag is still current the server answers 304 with no body, and the client uses its stored copy. For writes the direction reverses:
PUT /orders/42
If-Match: "7"If the order has changed since version 7, the server answers 412 Precondition Failed and does not apply the update. This stops two editors from silently overwriting each other, and it is the HTTP form of optimistic locking. The two headers are not symmetrical. If-None-Match is about caching reads and may use weak tags. If-Match guards writes and requires a strong match.
Use the version column
If the entity has a version column, it is already the right tag. It changes on every update, it costs nothing to compute, and it is exactly what the database uses for optimistic locking.
@GetMapping("/{id}")
ResponseEntity<OrderView> get(@PathVariable long id, WebRequest request) {
Order order = orders.find(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
String etag = "\"" + order.version() + "\"";
if (request.checkNotModified(etag)) {
return null;
}
return ResponseEntity.ok().eTag(etag).body(OrderView.from(order));
}checkNotModified compares the tag with the request's If-None-Match header and, on a match, sets the 304 status on the response. Returning null tells Spring the response is already complete. The order is loaded to read its version, which is a primary key lookup. If even that matters, a query that selects only the version column is cheaper, and the full entity is loaded only when the tags differ.
Conditional writes
@PutMapping("/{id}")
ResponseEntity<OrderView> replace(@PathVariable long id,
@RequestHeader(HttpHeaders.IF_MATCH) String ifMatch,
@Valid @RequestBody OrderUpdate body) {
long expected = parseVersion(ifMatch);
try {
Order saved = orders.update(id, expected, body);
return ResponseEntity.ok().eTag("\"" + saved.version() + "\"").body(OrderView.from(saved));
} catch (OptimisticLockingFailureException e) {
throw new ResponseStatusException(HttpStatus.PRECONDITION_FAILED, "order changed");
}
}With @RequestHeader the header is required, and a missing one yields 400. The more precise answer for a missing precondition is 428 Precondition Required, which tells the client the server insists on If-Match. The update method should run update orders set ..., version = version + 1 where id = ? and version = ? and treat zero affected rows as a conflict. Mapping that to 412 gives every client a standard signal to refetch and ask the user what to do. Shape the body of the error as described in problem details.
Return the new tag in the response to the write. A client that gets the updated resource and its new tag can make a second edit without another GET.
When there is no version: the shallow filter
@Bean
FilterRegistrationBean<ShallowEtagHeaderFilter> etagFilter() {
var bean = new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
bean.addUrlPatterns("/api/*");
return bean;
}The filter renders the response, hashes the body to form a tag, and answers 304 if it matches If-None-Match. The saving is bandwidth only, because the controller still runs and builds the whole response, and the filter buffers the body in memory to hash it. It is a quick way to get conditional reads on endpoints you cannot change, and it does nothing for writes.
Weak and strong tags
"7" is a strong tag: the representations are byte for byte identical. W/"7" is weak: they mean the same thing but may differ in bytes, for example after a compression change. Range requests and If-Match need strong tags. For a resource version, use a strong one.
Things that go wrong
The tag must change whenever the representation changes, and that includes variants. If the same URL returns English or French depending on Accept-Language, or JSON or XML depending on Accept, a tag based only on the version is wrong for one of them. Either fold a hash of the variant into the tag or send a Vary header. Always quote the value: an unquoted tag is invalid and some clients drop it. Compression layers can rewrite tags; some servers append a suffix such as -gzip, which breaks a strict comparison against your version number if you parse it. And behind a CDN, confirm it forwards If-None-Match and ETag unchanged.
Which kind of tag to use
| Source of the tag | Cost to compute | Correct when |
|---|---|---|
| A version column | Free, already loaded | Every change goes through the entity and bumps the version |
| A hash of the rendered body | Render the full response | You cannot change the data model, and only bandwidth matters |
| A timestamp of last update | Free | Updates are less frequent than one per second; otherwise two edits share a tag |
| A hash of several sources | Several lookups | The representation combines rows from more than one table |
The last row is the one that bites. A page that shows an order together with its customer's name is not changed by an order update alone. If the customer is renamed, the order's version is the same and a client holding the old representation is told 304, which is wrong. Either fold the customer's version into the tag, for example "7-3", or accept staleness and say so with a short max-age. Do not skip this thought: stale 304 responses are hard to debug, because the server logs show a perfectly normal conditional request.
Last-Modified and If-Modified-Since are the older pair, with one-second resolution. An ETag is more precise, and when a response carries both, clients and caches prefer the ETag. Send both only if some old client needs the date.
Test it
@Test
void unchangedOrderGets304() throws Exception {
mvc.perform(get("/orders/42").header("If-None-Match", "\"7\""))
.andExpect(status().isNotModified());
}
@Test
void staleUpdateGets412() throws Exception {
mvc.perform(put("/orders/42")
.header("If-Match", "\"6\"")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"status\":\"PAID\"}"))
.andExpect(status().isPreconditionFailed());
}Seed the order at version 7 in the test setup, and add a third test that sends the right tag and expects 200 with a new tag in the response. Together the three cover the whole contract, and they fail loudly if someone later changes how versions are numbered.
What it will not do
For data that changes on every read, If-None-Match saves nothing, although If-Match still protects updates and is worth having alone. Caching headers are the other half of the story, covered in cache headers. The write side of safe retries is in idempotency keys. The authority for the semantics is RFC 9110 on conditional requests, and the Spring HTTP caching documentation describes the API used above.


