Video in progress
When several workers take tasks from one table, how do you use `PESSIMISTIC_WRITE` with `SKIP LOCKED`?
Each worker takes rows with select ... for update skip locked limit N: rows locked by other workers aren't waited for, just skipped. In Hibernate you do this with PESSIMISTIC_WRITE plus a lock timeout of -2 (LockOptions.SKIP_LOCKED).
📖 Answer
With a plain for update, 5 workers all try to take the same first row: one gets it and the other four wait in line. There's no parallelism.
With SKIP LOCKED, each one takes free rows:
@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "-2"))
@Query("select j from Job j where j.status = 'PENDING' order by j.id")
List<Job> pickBatch(Pageable limit);
In Hibernate -2 means SKIP_LOCKED. For PostgreSQL the result is roughly:
select ... from job where status = 'PENDING' order by id
fetch first ? rows only for no key update skip locked
The processing flow:
@Transactional
public List<Long> claim() {
List<Job> jobs = repo.pickBatch(PageRequest.of(0, 10));
jobs.forEach(j -> j.markRunning(workerId));
return jobs.stream().map(Job::getId).toList();
} // commit: the lock is released, status is RUNNING
Don't execute the task itself while holding the lock, because the transaction gets long. First mark it "RUNNING" and commit, then do the work, and finally mark it "DONE".
Other things to think through in prod: if a worker dies, RUNNING rows hang, so you need to take them back with a timeout based on started_at. Without an index on status + id, the query scans even the rows it's skipping. SKIP LOCKED exists in PostgreSQL 9.5+, MySQL 8+ and Oracle; in tests on H2 the behavior may differ.
Sign up to mark studied questions and save your progress.