Quick revision
The short answer
Each worker claims due jobs with SELECT ... WHERE status = 'PENDING' AND run_at <= now() ORDER BY run_at LIMIT n FOR UPDATE SKIP LOCKED, so rows locked by one worker are simply skipped by the others. In the same short transaction it marks them RUNNING with its worker id and a lease expiry, commits, and only then does the work, marking each job DONE or scheduling a retry. A sweeper resets RUNNING jobs whose lease expired, and because that means a job can occasionally run twice, every job must be idempotent.
What to remember
In this answer, we saw how four pods polling the same table pick up the same job, fixed it by claiming rows with FOR UPDATE SKIP LOCKED and marking them RUNNING with a worker id and lease in the same short transaction, processed the work outside any transaction and finished with a guarded update, added a sweeper that releases expired leases, and made jobs idempotent because a job can still run twice.
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 claims due jobs with SELECT ... WHERE status = 'PENDING' AND run_at <= now() ORDER BY run_at LIMIT n FOR UPDATE SKIP LOCKED, so rows locked by one worker are simply skipped by the others. In the same short transaction it marks them RUNNING with its worker id and a lease expiry, commits, and only then does the work, marking each job DONE or scheduling a retry. A sweeper resets RUNNING jobs whose lease expired, and because that means a job can occasionally run twice, every job must be idempotent.
Why this question is asked
Many Spring Boot applications need background jobs: send this email at 9:00, retry that payment in five minutes. A jobs table in PostgreSQL is often the simplest and most reliable way to do it, because the jobs live in the same database as the data and survive restarts. The tricky part appears as soon as we run more than one pod: without care, two pods pick up the same job and the customer gets two emails. Interviewers ask this to check that we know how to share work safely through the database. In this answer, we will see the race, fix it with FOR UPDATE SKIP LOCKED, add a lease, process outside the transaction, recover from crashed workers, and see why jobs must still be idempotent.
1The Race With Four Worker Pods
Our jobs table has one row per job: an id, a type, a payload, a status such as PENDING, RUNNING or DONE, and run_at, the time the job becomes due. Each of the four pods runs a loop that asks: which jobs are due? A naive loop selects due PENDING jobs and processes them.
The problem is that all four pods run the same query at about the same time. They all see job 42 as PENDING, they all process it, and the email goes out four times. Updating the status after the select does not help, because the other pods have already read the row before the update commits. We need the act of choosing a job to be exclusive.
2Claiming Jobs With FOR UPDATE SKIP LOCKED
PostgreSQL gives us exactly the tool we need. FOR UPDATE takes a row lock on every row the query returns, a lock that blocks other transactions trying to lock the same row until we commit. SKIP LOCKED changes what other transactions do when they meet such a row: instead of waiting, they skip it and look at the next one. So four workers running the same query at the same time each get different jobs, and nobody waits.
6 messages in order. Play them, or step through them one at a time.
Neither worker waits for the other, and no job is returned twice.
Notice that the claim and the status change are one statement, so they happen in one transaction. The inner select locks up to 10 due rows that nobody else holds, the update marks them RUNNING with this worker's id and a lease expiry five minutes ahead, and RETURNING gives us the rows to process. When the statement commits, the locks are released, but the rows are now RUNNING, so no other worker's WHERE status = 'PENDING' matches them. An index on (status, run_at) keeps the inner query fast as the table grows.
3Processing Outside the Claiming Transaction
It is tempting to claim the jobs and process them inside the same transaction, keeping the rows locked until the work is done. That is a mistake. A job that calls an email provider might take 30 seconds, and during that time the transaction holds a database connection, keeps row locks, and prevents PostgreSQL from cleaning up old row versions. With many jobs, the connection pool runs dry.
So the claim commits quickly, and the work happens afterwards with no transaction open. When a job finishes, a second short update marks it DONE, or, on failure, puts it back to PENDING with a later run_at for a retry with backoff. The WHERE worker_id condition makes sure a worker only finishes jobs it still owns.
The claim method lives in a separate bean on purpose. Spring's @Transactional works through a proxy, a wrapper object around the bean, and a call from one method to another inside the same class skips the proxy, so the transaction would silently not start.
4The Sweeper for Crashed Workers
What happens if a pod is killed while it holds RUNNING jobs? Nobody will ever mark them DONE, and they would stay stuck forever. The lease solves this. A small sweeper, which can run in every pod because the statement is safe to run concurrently, resets jobs whose lease has expired.
The lease length must be longer than a normal job takes, five minutes for jobs that usually take seconds, otherwise the sweeper would reset jobs that are still running. Long jobs can extend their lease periodically by updating lease_until, like a heartbeat.
5Why Every Job Must Be Idempotent
This design gives at-least-once execution, not exactly-once. A job can run twice in two ways. A worker can finish the work and crash before it marks the job DONE, so the sweeper resets it and another worker repeats it. Or a worker can stall, for example in a long garbage collection pause, beyond its lease; the sweeper hands the job to another worker while the first one wakes up and carries on.
So each job must be idempotent, meaning that running it twice has the same effect as running it once. The usual technique is to use the job id as an idempotency key: the email handler records the job id in a sent_messages table with a unique constraint and skips the send if the id is already there, and calls to a payment provider pass the job id as the provider's idempotency key.
6Follow-up questions
Why not use a distributed lock such as Redis or ShedLock?
ShedLock makes sure only one instance runs a scheduled method at a time, which is good for a single housekeeping task but would make one pod do all the work. SKIP LOCKED lets all four pods share the jobs in parallel using the database we already have, with no extra infrastructure.
Does SKIP LOCKED work in MySQL too?
Yes, MySQL 8.0 and later support FOR UPDATE SKIP LOCKED with InnoDB. The UPDATE with a subquery on the same table is not allowed in MySQL, so there we select the ids with FOR UPDATE SKIP LOCKED inside a transaction and update them before committing.
How many jobs should one claim take?
Enough to keep the worker busy without hoarding. If jobs take a second each and the lease is five minutes, ten at a time is reasonable. Claiming hundreds would let one pod hold work that others could be doing, and they would all expire together if it crashed.
7Conclusion
In this answer, we saw how four pods polling the same table pick up the same job, fixed it by claiming rows with FOR UPDATE SKIP LOCKED and marking them RUNNING with a worker id and lease in the same short transaction, processed the work outside any transaction and finished with a guarded update, added a sweeper that releases expired leases, and made jobs idempotent because a job can still run twice.
Open with
I would claim jobs in a single short transaction using FOR UPDATE SKIP LOCKED. The query selects PENDING jobs whose run_at is due, ordered by run_at, with a limit like ten, and FOR UPDATE SKIP LOCKED means that rows another worker has locked are skipped instead of waited for, so four pods running it at the same time each get different jobs.
Then, if they want more
In the same statement I update those rows to RUNNING, with the worker's id and a lease_until about five minutes ahead, and commit. Then I process the jobs outside any transaction, because holding locks and a connection during a 30-second email call would exhaust the pool.
When a job succeeds I mark it DONE, guarded by worker_id, and on failure I put it back to PENDING with a later run_at for backoff. If a pod crashes, its jobs stay RUNNING, so a sweeper resets RUNNING jobs whose lease has expired.
That gives at-least-once execution: a job can run twice if a worker crashes after doing the work or stalls beyond its lease. So every job must be idempotent, typically using the job id as an idempotency key, for example a unique sent_messages row or the payment provider's idempotency key.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8.0
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
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 "You are writing the worker loop of a simple job scheduler backed by a PostgreSQL jobs...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/94fc8bf137/