Skip to the page

JPA and Hibernate · senior

Optimistic locking and Hibernate caches

A @Version column stops lost updates. The second-level cache is per JVM unless clustered. For stock, use one atomic UPDATE.

The notes

What you must know

  • Lost update: two admins save the same product, the last save wins and one change disappears without an error.
  • @Version long version makes Hibernate add where id=? and version=? and bump the version. If 0 rows change, it throws OptimisticLockException.
  • The version must go to the client and come back (in the DTO, or as ETag and If-Match) and be compared on the server. Otherwise the check does nothing.
  • Retry automatically only for changes that can be re-applied (a computed increment), never for a person's edit.
  • Pessimistic: @Lock(PESSIMISTIC_WRITE) (SELECT ... FOR UPDATE) inside a transaction, with a lock timeout, for hot rows.
  • For stock decrements use one atomic statement: update product set stock = stock - :q where id = :id and stock >= :q, and check the row count.
  • First-level cache: the persistence context. Always on. The same id twice in a transaction means one SELECT.
  • Second-level cache: shared across sessions in one JVM, through a provider (JCache, Ehcache, Caffeine). With six pods and local caches, each pod has its own copy and others stay stale until expiry. Good fit for the second level: read-mostly reference data. Spring's @Cacheable with Redis is shared by all pods and often simpler for API results.

The red pen

Common traps: mistake → fix

  • Mistake: Last save wins is acceptable

    Fix: it silently loses a person's work.

  • Mistake: Second-level cache is shared between pods

    Fix: not with a local provider.

  • Mistake: A version column works without the client sending it back

    Fix: the server must compare the client's version.

Easy to hard

Questions interviewers ask, easy to hard

  1. Two admins edit the same product. What ends up in the database? How do you make the second save fail?
  2. Optimistic or pessimistic locking?
  3. What is the first-level cache? The second-level?
  4. Would you enable the second-level cache for six pods?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview