Video in progress

This code runs at the READ COMMITTED isolation level. What happens if two doctors go off duty at the same time, and how do you fix it?

@Transactional
public void goOffDuty(long doctorId, long shiftId) {
    long onDuty = doctors.countByShiftIdAndOnDutyTrue(shiftId);
    if (onDuty < 2) throw new IllegalStateException("Kamida bitta shifokor qolishi kerak");
    Doctor d = doctors.findById(doctorId).orElseThrow();
    d.setOnDuty(false);
}

This is write skew: both transactions read "there are 2 people on duty" and each changes a different row, so nobody is left. An optimistic lock doesn't help, because the same row is not being changed. The fix is to lock a shared row, use SERIALIZABLE isolation, or a database constraint.

📖 Answer

The timeline: A and B run count in parallel, and both see 2. A sets its own row to on_duty = false, and B sets its own row. Each row was changed by only one transaction: no collision, and @Version stays silent too. The result is zero people on duty.

This is classic write skew. Neither READ COMMITTED nor PostgreSQL's REPEATABLE READ (snapshot isolation) stops it.

The persistence context also gives a false sense of safety here: an entity loaded once stays unchanged until the end of the transaction, and this feels like "repeatable read", but it is only an in-memory cache, not a database-level guarantee.

Fix options:

Lock a shared parent row, because the invariant actually belongs to the shift:

Shift shift = em.find(Shift.class, shiftId, LockModeType.PESSIMISTIC_WRITE);
long onDuty = doctors.countByShiftIdAndOnDutyTrue(shiftId);

Now operations on this shift run one at a time. Locking the aggregate root is the most understandable solution.

The optimistic variant: bump the Shift version with OPTIMISTIC_FORCE_INCREMENT: the second transaction fails at commit and retries.

SERIALIZABLE (PostgreSQL SSI). It detects write skew without changing the code, but retries for serialization failures are mandatory, and errors increase under load. Good for narrow, critical operations.

Constraint. The database can guarantee some invariants itself (unique, exclusion constraints). Not directly in this case, so I choose to lock the parent row.