Quick revision
The short answer
Each worker runs one statement: an UPDATE that marks up to 10 jobs RUNNING, where the ids come from a subquery that selects PENDING, due jobs ordered by run_at with LIMIT 10 FOR UPDATE SKIP LOCKED, and RETURNING gives back the claimed ids and payloads. FOR UPDATE stops two workers taking the same row, and SKIP LOCKED makes each worker pass over rows another worker has locked instead of waiting. A partial index on pending jobs keeps the claim fast, and the claim commits immediately, before processing.
What to remember
In this answer, we saw that a naive claim either hands a job to two workers or, with plain FOR UPDATE, makes workers queue behind each other. An UPDATE over a subquery with ORDER BY run_at LIMIT 10 FOR UPDATE SKIP LOCKED claims distinct jobs for every worker without waiting, RETURNING fetches them in the same round trip, and a partial index on pending jobs keeps it fast. The claim commits at once, processing happens outside it, and a lease on locked_at recovers jobs from crashed workers.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Each worker runs one statement: an UPDATE that marks up to 10 jobs RUNNING, where the ids come from a subquery that selects PENDING, due jobs ordered by run_at with LIMIT 10 FOR UPDATE SKIP LOCKED, and RETURNING gives back the claimed ids and payloads. FOR UPDATE stops two workers taking the same row, and SKIP LOCKED makes each worker pass over rows another worker has locked instead of waiting. A partial index on pending jobs keeps the claim fast, and the claim commits immediately, before processing.
Why this question is asked
Database-backed job queues are everywhere in Spring applications, from email sending to report generation, and the claim query is the heart of them. Interviewers ask for it because a naive version either hands the same job to two workers or makes workers wait in line behind each other. In this answer, we will see what goes wrong with the naive claim, write the SKIP LOCKED version and explain each part, add the index that keeps it cheap, call it from Spring, and then deal with processing outside the claim and recovering jobs from crashed workers.
1Why the Naive Claim Fails
The first attempt usually reads the next pending jobs and then updates them. Between the read and the update, another worker can read the same rows, so both workers process job 17. Adding FOR UPDATE to the read fixes the duplicates but creates a new problem: worker B's FOR UPDATE reaches job 17, finds it locked by worker A, and waits until A commits. With eight workers, seven of them spend their time waiting for the first one, and throughput is that of a single worker.
2The Claim Query With SKIP LOCKED
SKIP LOCKED changes the meaning of a locked row from wait for it to pretend it is not there. Worker B scans past jobs 17 to 26 that A has locked and takes the next ten free ones. Wrapping the locking subquery in an UPDATE with RETURNING lets us claim and fetch in one round trip, inside one short statement.
7 messages in order. Play them, or step through them one at a time.
Neither worker waits, and no job is claimed twice.
Let's read it from the inside. The subquery picks due pending jobs, oldest first, and locks up to ten of them, skipping any already locked by another transaction. The outer UPDATE marks exactly those ids RUNNING with the worker's name and time. RETURNING sends the claimed rows back. Because the status change commits with the statement, the jobs stay claimed after the row locks are released, which is what lets the processing happen later without any lock.
3The Index That Keeps the Claim Cheap
The claim runs thousands of times a minute, so it must touch only pending rows. A partial index contains only rows matching its WHERE clause, so an index on run_at for PENDING rows stays small, a few hundred entries, even when the table has millions of finished jobs. The planner uses it for the subquery and reads the oldest due entries directly.
4Calling It From Spring and Processing Outside the Claim
The claim should be its own short transaction. If we claimed and processed inside one transaction, the locks would last as long as the slowest job, and a crash would roll back the claim but also any progress. So the worker claims, commits, processes each job with no transaction open (or with its own short transactions for its own writes), and then records the result.
The jobs table in the question has no attempts column, but in practice we usually add one, so a failed job can be retried with a later run_at instead of going straight to FAILED. MySQL 8 supports the same idea: inside a transaction, SELECT id FROM jobs WHERE ... ORDER BY run_at LIMIT 10 FOR UPDATE SKIP LOCKED, then an UPDATE of those ids and a commit, because MySQL does not allow the locked subquery inside an UPDATE of the same table in this form and has no RETURNING.
5Follow-up questions
How do you recover jobs taken by a worker that crashed?
A crashed worker leaves its jobs in RUNNING forever, because the claim already committed. We treat locked_at as a lease: a reaper job, run every minute, resets jobs that have been RUNNING longer than the maximum expected processing time, for example UPDATE jobs SET status = 'PENDING', locked_by = NULL WHERE status = 'RUNNING' AND locked_at < now() - interval '15 minutes'. Long jobs renew locked_at as a heartbeat so they are not reaped while alive. Since a reaped job may have been partly processed, handlers must be idempotent.
Does SKIP LOCKED give a consistent view of the queue?
No, and it is not meant to. It deliberately returns an inconsistent view, the rows that happen to be free right now, which is perfect for distributing work but wrong for reports or sums. Use it only for claiming.
Why ORDER BY run_at if workers skip rows anyway?
Ordering gives roughly first-due, first-served behaviour and lets the partial index answer the query by reading the first entries. Without it, the database may return any pending rows, and old jobs can wait much longer than new ones.
6Conclusion
In this answer, we saw that a naive claim either hands a job to two workers or, with plain FOR UPDATE, makes workers queue behind each other. An UPDATE over a subquery with ORDER BY run_at LIMIT 10 FOR UPDATE SKIP LOCKED claims distinct jobs for every worker without waiting, RETURNING fetches them in the same round trip, and a partial index on pending jobs keeps it fast. The claim commits at once, processing happens outside it, and a lease on locked_at recovers jobs from crashed workers.
Open with
I'd claim with a single UPDATE. It sets status to RUNNING, locked_by to the worker and locked_at to now, for ids from a subquery that selects jobs where status is PENDING and run_at is due, ordered by run_at, LIMIT 10, FOR UPDATE SKIP LOCKED, and it ends with RETURNING id and payload.
Then, if they want more
FOR UPDATE makes sure two workers can't lock the same row, and SKIP LOCKED makes a worker pass over rows another worker has locked instead of waiting for them, so eight workers really work in parallel. Because the status change commits, the job stays claimed after the locks go away.
I'd add a partial index on run_at where status is PENDING, so the claim only touches a few hundred pending entries even with millions of finished rows. In Spring I'd run the claim in its own short transaction with TransactionTemplate, commit, process the jobs with no transaction open, and then mark each DONE or FAILED.
For crashes I'd treat locked_at as a lease and have a reaper put stale RUNNING jobs back to PENDING, so handlers have to be idempotent. MySQL 8 supports FOR UPDATE SKIP LOCKED too, as a select then update in one transaction.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write the SQL a worker uses to take up to 10 pending jobs from a jobs(id, status...": https://scrivio-interview-library.netlify.app/databases/database-locking/e1dcaecc82/