wasAsked.

Explain optimistic locking with JPA and how a React client should handle version conflicts.

Razorpay · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, JPA, React

Community answers

Posted by wasAsked editorial collection

Optimistic locking assumes conflicts are rare: instead of locking rows while a user edits, JPA checks at update time that nobody else changed the row. JPA setup @Entity public class Product { @Id private Long id; private BigDecimal price; @Version private long version; // incremented on every update } When Hibernate updates, it includes the version in the WHERE clause: UPDATE product SET price = ?, version = version + 1 WHERE id = ? AND version = ? If no row is updated, another transaction changed it first, and Hibernate throws OptimisticLockException (wrapped by Spring as ObjectOptimisticLockingFailureException). Carrying the version through a REST API - Include the version in the GET response, ideally as an ETag header (ETag: "7") or a field in the DTO. - The client sends it back on update: If-Match: "7" or a version field in the request body. - The service loads the entity, compares the client version with the current version (or sets it before merging), applies changes and saves. - On conflict, return 409 Conflict (or 412 Precondition Failed when using If-Match), with Problem Details including the current server state. @ExceptionHandler(ObjectOptimisticLockingFailureException.class) ResponseEntity<ProblemDetail> conflict() { var pd = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "This record was changed by someone else."); return ResponseEntity.status(HttpStatus.CONFLICT).body(pd); } How the React client should handle conflicts - Keep the user's unsaved input — never discard it silently. - Show a clear message: "Someone else updated this product while you were editing." - Fetch the latest version and show what changed (their value vs your value per field). - Offer choices: reload and discard my changes, keep my changes and overwrite (resubmit with the new version), or merge field by field. - With TanStack Query, invalidate the cached item on conflict and refetch. - For collaborative screens, reduce conflicts with periodic refresh, "being edited by" indicators, or real-time updates. When to prefer pessimistic locking High contention on the same rows (stock counters during a sale) or when retrying is expensive; use @Lock(PESSIMISTIC_WRITE) with short transactions, or atomic SQL updates. For automated retries (not involving user edits), Spring Retry with @Retryable can retry the transaction on optimistic locking failures.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics