Video in progress
If two clients change the same resource at the same time, how do you prevent a "lost update" in a service API? How do ETag and `If-Match` help?
I return the resource version in the ETag header, and the client sends it back with If-Match when changing the resource. If the version doesn't match, the service returns 412 Precondition Failed. Internally this ties into optimistic locking with JPA @Version.
📖 Answer
The situation: operator A and operator B opened the same order (version 5). A changed the address and saved; B added a comment on top of the old data and saved, so A's address was lost. Nobody saw an error.
HTTP has a standard solution for this:
GET /orders/812 -> 200, ETag: "5"
PUT /orders/812, If-Match: "5" -> 200, ETag: "6" (A)
PUT /orders/812, If-Match: "5" -> 412 Precondition Failed (B)
On the server side:
@PutMapping("/orders/{id}")
ResponseEntity<OrderDto> update(@PathVariable long id,
@RequestHeader("If-Match") String ifMatch,
@RequestBody UpdateOrder body) {
long expected = Long.parseLong(ifMatch.replace("\"", ""));
Order saved = orderService.update(id, expected, body);
return ResponseEntity.ok()
.eTag(String.valueOf(saved.getVersion()))
.body(OrderDto.from(saved));
}
@Transactional
public Order update(long id, long expectedVersion, UpdateOrder body) {
Order order = repo.findById(id).orElseThrow();
if (order.getVersion() != expectedVersion) {
throw new PreconditionFailedException(); // mapped to 412
}
order.apply(body);
return order; // @Version is checked again at flush time
}
There are two checks here. The first detects that the client saw old data. The second (@Version) catches a parallel write within those very milliseconds and throws ObjectOptimisticLockingFailureException; turn that into a 409 or 412 too.
When the client gets a 412, it re-reads the resource and shows the user the difference. If you want to make If-Match mandatory, return 428 Precondition Required when it's missing.
Sign up to mark studied questions and save your progress.