Video in progress
How do you bring optimistic locking up to the REST API level (ETag, `If-Match`), and how does it connect to the `version` column in the database?
The @Version value on the entity is returned in the response as an ETag, and the client sends it back in an If-Match header when updating. The server runs UPDATE ... WHERE version = ? with that version; if it doesn't match, it returns 412 Precondition Failed. That way the "last writer wins" problem is closed between users too.
📖 Answer
Having @Version in the database alone isn't enough. Two operators open the same order on screen, edit for 5 minutes, and save. On each save the server loads the entity fresh, so the version is always current and no conflict is detected. The first one's change silently disappears.
The version has to travel to the client and back:
@GetMapping("/orders/{id}")
ResponseEntity<OrderDto> get(@PathVariable long id) {
Order o = service.find(id);
return ResponseEntity.ok().eTag("\"" + o.getVersion() + "\"").body(OrderDto.from(o));
}
@PutMapping("/orders/{id}")
ResponseEntity<OrderDto> update(@PathVariable long id,
@RequestHeader("If-Match") String ifMatch,
@RequestBody OrderUpdate req) {
long expected = Long.parseLong(ifMatch.replace("\"", ""));
Order o = service.update(id, expected, req); // the version check is inside
return ResponseEntity.ok().eTag("\"" + o.getVersion() + "\"").body(OrderDto.from(o));
}
In the service, the loaded entity's version is compared with expected; if they differ, 412. If they're equal, Hibernate sends UPDATE ... SET version = version + 1 WHERE id = ? AND version = ?: if someone changes it between the read and the write, OptimisticLockException → 412 again.
The rules I add to this:
- I reject an update without
If-Match(428 Precondition Required), otherwise clients won't send it. - For mobile clients and external integrations, I return the current state in the error response, so the client can offer a merge.
- A change to child objects inside an aggregate must also bump the root's version (
OPTIMISTIC_FORCE_INCREMENT), otherwise the ETag stays the same.
I write this agreement into the API standard so it's the same for all teams.
Sign up to mark studied questions and save your progress.