Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Add ETag support so that clients get 304 Not Modified for unchanged orders. Show two approaches.

The quick approach is ShallowEtagHeaderFilter, which hashes the finished response body into an ETag and answers 304 when the client's If-None-Match matches; it saves bandwidth but the server still does all the work. The better approach computes the ETag from the order's version field, either by returning ResponseEntity.ok().eTag(...) or by calling webRequest.checkNotModified(etag) to stop early with 304. The same ETag, sent back in If-Match on updates, lets us reject lost updates with 412.

Why this question is asked

Clients often poll the same resource: a mobile app refreshing an order screen, a dashboard reloading every ten seconds. Most of those responses are identical to the last one. HTTP has a built-in way to say nothing changed, and using it well cuts bandwidth and, done right, database work too. Interviewers ask for two approaches to see whether we know the difference between a cheap generic filter and a version-aware design. In this answer, we will recap how ETags and conditional requests work, build the filter approach, build the version-based approach in two styles, and reuse the ETag to protect updates.

1A Quick Recap of ETags and Conditional Requests

An ETag, short for entity tag, is a short string the server sends in a response header to identify one version of a resource, such as ETag: "7". The quotes are part of the value. The client stores it and, on the next GET, sends it back in If-None-Match: "7". This is called a conditional request: the client is saying send me the body only if it is not this version.

If the resource is unchanged, the server answers 304 Not Modified with no body, and the client reuses its cached copy. If it changed, the server answers 200 with the new body and a new ETag. For updates the direction is reversed: the client sends If-Match: "7" with a PUT, meaning apply this only if the resource is still version 7, and the server answers 412 Precondition Failed if someone else changed it first.

Step throughA conditional GET
ClientAPI
GET /orders/1
200, ETag: "7", body
GET /orders/1, If-None-Match: "7"
304 Not Modified, no body
PUT /orders/1, If-Match: "7"
200, ETag: "8"

6 messages in order. Play them, or step through them one at a time.

2Approach 1: ShallowEtagHeaderFilter

Spring ships a servlet filter that adds ETags to every response without touching the controllers. We register it for the paths we care about.

Java
@Bean
FilterRegistrationBean<ShallowEtagHeaderFilter> etagFilter() {
var reg = new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
reg.addUrlPatterns("/orders/*");
return reg;
}
// GET /orders/1 -> 200, ETag: "0a1b2c...", body (a hash of the body bytes)
// GET /orders/1 If-None-Match: "0a1b2c..." -> 304, no body

The filter buffers the whole response body, computes an MD5 hash of it, and uses that as the ETag. If the request's If-None-Match equals the hash, it throws the body away and sends 304 instead. Notice what that means: the controller still ran, the database was still queried and the JSON was still serialized. Only the network transfer was saved. It is a good fit when bandwidth is the problem, for example large responses to mobile clients, and a poor fit when server load is. It also cannot help with If-Match on updates, because it only sees bodies after the fact.

3Approach 2: An ETag From the Version Field

If the entity has a version column, for example a JPA @Version field that Hibernate increments on every update, that number already identifies the state of the order. We can use it directly as the ETag.

Java
@GetMapping("/orders/{id}")
ResponseEntity<OrderDto> get(@PathVariable long id) {
Order order = repository.findById(id).orElseThrow();
return ResponseEntity.ok()
.eTag(Long.toString(order.getVersion())) // ETag: "7" (Spring adds the quotes)
.body(OrderDto.from(order));
}
// GET /orders/1 -> 200, ETag: "7"
// GET /orders/1 If-None-Match: "7" -> 304, Spring compares the ETag of the ResponseEntity

When a ResponseEntity carries an ETag and the request is a GET or HEAD, Spring's handling of the return value compares it with If-None-Match and turns the response into a 304 by itself. This is already better than the filter because there is no hashing and the ETag changes exactly when the data changes. But the order was still loaded and mapped to a DTO before we knew the answer.

4Stopping Early With checkNotModified

To save the server work too, we find the version cheaply first and let Spring decide before we build the body. WebRequest.checkNotModified(etag) compares the ETag with If-None-Match, sets the 304 status and the ETag header when they match, and returns true.

Java
@GetMapping("/orders/{id}")
OrderDto get(@PathVariable long id, WebRequest request) {
long version = repository.findVersionById(id).orElseThrow(); // SELECT version FROM orders WHERE id = ?
if (request.checkNotModified(Long.toString(version))) {
return null; // 304 already prepared, no body
}
return OrderDto.from(repository.findById(id).orElseThrow()); // only when something changed
}
// GET /orders/1 If-None-Match: "7" (version is 7) -> 304, one tiny query
// GET /orders/1 If-None-Match: "6" (version is 7) -> 200, ETag: "7", full body
Step throughVersion-based ETag with an early return
  1. Read If-None-Match"7"
  2. Load only the versionSELECT version ... = 7
  3. Does the ETag match?
    YesReturn 304, no bodyNoLoad the order and build the DTO
  4. Send 200 with ETag: "7"

4 steps in order. Play them, or step through them one at a time.

Notice the order of the steps. We ask the database for one number, which an index on the primary key answers almost instantly, and only load the full order with its lines when the client's copy is out of date. For a polling client that sees the same version most of the time, this turns most requests into a single cheap query and an empty response.

5Using the Same ETag to Prevent Lost Updates

A lost update happens when two clients read version 7, both edit it, and the second save silently overwrites the first. If clients send the ETag they read in If-Match, we can refuse stale updates.

Java
@PutMapping("/orders/{id}")
ResponseEntity<OrderDto> update(@PathVariable long id,
@RequestHeader(HttpHeaders.IF_MATCH) String ifMatch,
@RequestBody @Valid OrderUpdate body) {
Order order = repository.findById(id).orElseThrow();
String current = "\"" + order.getVersion() + "\"";
if (!current.equals(ifMatch)) {
return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED).build(); // 412
}
order.apply(body);
Order saved = repository.saveAndFlush(order); // @Version still guards the race at commit time
return ResponseEntity.ok().eTag(Long.toString(saved.getVersion())).body(OrderDto.from(saved));
}

The check in the controller handles the common case with a clear 412. There is still a tiny window between reading and saving, and the JPA @Version column closes it: if another transaction committed in between, Hibernate's update affects no row and throws an optimistic locking exception, which we can also map to 412. Recent Spring versions can also evaluate If-Match inside checkNotModified for unsafe methods, so check your version before writing it by hand. Making If-Match required on PUT and PATCH, answering 428 Precondition Required when it is missing, is a common rule for APIs with concurrent editors.

6Follow-up questions

What is the difference between a strong and a weak ETag?

A strong ETag, like "7", promises the bytes are identical. A weak one, written W/"7", only promises the content is equivalent, for example the same data with different whitespace or compression. ShallowEtagHeaderFilter produces strong ETags by default and can be configured to write weak ones; If-Match comparisons need strong ETags.

Why not use Last-Modified instead of an ETag?

Last-Modified works with If-Modified-Since and is fine for files, but it has one-second resolution and depends on clocks, so two updates in the same second look identical. A version number or hash has neither problem. Spring supports both, and checkNotModified has an overload that takes both an ETag and a timestamp.

Does the ETag have to include the representation?

If the same order can be returned as JSON or XML, or in different shapes per API version, the ETag should differ per representation, for example by adding the version of the API to it, and the response should carry Vary: Accept. Otherwise a cache could serve a 304 for a representation the client never received.

7Conclusion

In this answer, we saw two ways to get 304 Not Modified. ShallowEtagHeaderFilter hashes the response body, which saves bandwidth but not server work. A version-based ETag, returned with ResponseEntity.ok().eTag(...) or checked early with webRequest.checkNotModified(etag), saves both when we read the version cheaply first. Finally, the same ETag in If-Match on PUT lets us answer 412 to stale updates, backed by the JPA @Version column.

What to say in the interviewAbout 70 seconds aloud

Open with

There are two approaches. The first is ShallowEtagHeaderFilter, which I register for the paths I care about. It buffers the response, takes an MD5 of the body as the ETag, and if the request's If-None-Match matches, it sends 304 with no body.

Then, if they want more

It is zero code in the controllers, but the controller, the query and the serialization all still run, so it saves bandwidth and not server work. The second approach uses the entity's version field, the JPA @Version column, as the ETag. The simple form returns ResponseEntity.ok().eTag(version).body(dto), and Spring turns it into a 304 when If-None-Match matches.

The stronger form loads only the version with a small query and calls webRequest.checkNotModified(etag); if it returns true, I return null and Spring sends the 304, so the full order is never loaded for a client that already has it.

I would also use the same ETag for updates: the client sends If-Match with a PUT, I compare it with the current version and answer 412 Precondition Failed if it changed, and the @Version check at commit covers the remaining race. That prevents lost updates between concurrent editors.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Add ETag support so that clients get 304 Not Modified for unchanged orders. Show two...": https://scrivio-interview-library.netlify.app/spring-boot/rest-controllers/53b992bdad/