Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Implement a job queue in PostgreSQL that several worker instances poll without processing the same job twice. What SQL and Spring setup would you use?

Each worker claims jobs in a short transaction with select ... from job where status = 'READY' order by id limit 10 for update skip locked, and in the same transaction marks them RUNNING with its worker id and a timestamp. SKIP LOCKED makes each worker skip rows that another worker has already locked, so no job is claimed twice and workers never wait for each other. Processing happens after that transaction commits, stuck jobs are reclaimed after a timeout, and processing is idempotent because a reclaimed job may run again.

Why this question is asked

Many systems need a background job queue, and when the data already lives in PostgreSQL, a table is often simpler than adding a message broker. The difficulty is concurrency: several instances of the service poll the same table, and a naive query hands the same job to all of them. Interviewers ask this design question because the answer combines row locks, transaction boundaries and failure handling. In this answer, we will see why the naive version fails, build the claim query with SKIP LOCKED, wire it into Spring, and handle crashes and stuck jobs.

1Why the Naive Poll Fails

The simplest worker selects ready jobs and then marks them as running. With two instances, both run the select at the same moment, both get job 101, and both process it. Adding FOR UPDATE stops the double claim, but now the second worker waits on the first worker's locks; with ten workers they queue behind each other and the queue runs no faster than one worker.

SQL
-- worker A and worker B at the same moment, without locks
select id from job where status = 'READY' order by id limit 10; -- A: 101..110
select id from job where status = 'READY' order by id limit 10; -- B: 101..110, the same jobs
-- with FOR UPDATE but without SKIP LOCKED
-- A locks 101..110; B blocks until A commits, then gets 111..120

2The Claim Query With SKIP LOCKED

FOR UPDATE SKIP LOCKED tells PostgreSQL to lock the rows it returns, and to silently skip any row that is already locked by another transaction instead of waiting for it. So worker A locks 101 to 110, and worker B, running at the same moment, skips those and gets 111 to 120. Each job is handed to exactly one worker, and nobody waits.

We claim and mark in one statement, which keeps the locked window tiny. An UPDATE with a subquery selects and locks the ids, sets them to RUNNING, and returns the claimed rows.

SQL
update job
set status = 'RUNNING', worker_id = :worker, claimed_at = now(), attempts = attempts + 1
where id in (
select id from job
where status = 'READY'
order by id
limit 10
for update skip locked
)
returning id, type, payload, attempts;
-- worker A: 101..110 claimed
-- worker B (same moment): 111..120 claimed
-- worker C: 121..130 claimed
Step throughThree workers claim different jobs
Worker AJob tableWorker B
claim 10 READY, skip locked
claim 10 READY, skip locked
101..110 locked and RUNNING
111..120, skipped A's rows
commit, then process outside the transaction
commit, then process outside the transaction

6 messages in order. Play them, or step through them one at a time.

SKIP LOCKED turns contention into parallelism.

Notice that the claim transaction ends as soon as this statement commits. The status column, not the row lock, now records that the job is taken. That is deliberate: we do not want to hold a database lock and a connection for the minutes a job might take to process.

3Wiring It Into Spring

In Spring we run the claim as a native query in its own short transaction, then process each job, then record the result in another short transaction. The processing itself runs without a transaction, or with a transaction of its own per job if it writes to the database.

Java
public interface JobRepository extends JpaRepository<Job, Long> {
@Modifying
@Query(value = """
update job set status = 'RUNNING', worker_id = :worker, claimed_at = now(), attempts = attempts + 1
where id in (select id from job where status = 'READY' order by id limit :n for update skip locked)
returning *""", nativeQuery = true)
List<Job> claim(@Param("worker") String worker, @Param("n") int n);
}
@Component
class JobWorker {
@Scheduled(fixedDelay = 500)
public void poll() {
List<Job> jobs = tx.execute(s -> repo.claim(workerId, 10)); // short claim transaction
for (Job job : jobs) {
try {
handlers.run(job); // no transaction held here
tx.executeWithoutResult(s -> repo.markDone(job.getId()));
} catch (Exception e) {
tx.executeWithoutResult(s -> repo.markFailedOrRetry(job.getId(), e.getMessage()));
}
}
}
}

An UPDATE ... RETURNING through Spring Data needs a native query; depending on your Spring Data and Hibernate versions, a modifying query that returns rows may need to be run through JdbcTemplate instead, so check your version. With JPQL, Hibernate can produce SKIP LOCKED for a PESSIMISTIC_WRITE query when the lock timeout hint is set to -2, which Hibernate defines as skip locked, on dialects that support it. The native query is the most predictable choice.

4Crashes and Stuck Jobs

Because the lock ends with the claim, a worker that crashes in the middle of a job leaves it in RUNNING forever. A reaper, a scheduled task, puts such jobs back: any job RUNNING for longer than its time limit, say 10 minutes, returns to READY, or to FAILED once attempts reaches a maximum such as 5.

SQL
update job set status = 'READY', worker_id = null
where status = 'RUNNING' and claimed_at < now() - interval '10 minutes' and attempts < 5;
update job set status = 'FAILED'
where status = 'RUNNING' and claimed_at < now() - interval '10 minutes' and attempts >= 5;

A reclaimed job may have been partly or even fully processed before the crash, so it will run again. That makes processing idempotent by design: the job carries a key, and its effects check it, for example by inserting with a unique constraint on the job id, so a second run does nothing harmful. This is at-least-once processing, the same guarantee most brokers give.

5Keeping the Table Healthy

An index on the status and id, or a partial index create index on job (id) where status = 'READY', keeps the claim query fast as the table grows. Finished jobs should be deleted or moved to an archive table in batches, since a large table of dead rows makes every scan and vacuum slower. Metrics on the number of READY jobs, the age of the oldest READY job and the failure rate tell us when to add workers or investigate a handler.

6Follow-up questions

Why not hold the lock while processing instead of using a status column?

It works for very short jobs and gives automatic release on crash, because the database releases the lock when the connection dies. But it holds a transaction and a pooled connection for the whole job, which blocks vacuum and limits workers to the pool size, so for jobs longer than a second the status column is better.

Does SKIP LOCKED preserve the order of jobs?

Roughly, not strictly. Each worker takes the oldest unlocked rows, but jobs run in parallel and finish in different orders. If jobs for one key must run in order, claim by key, for example only the oldest READY job per customer, or use a broker with partitioning.

When would you use a broker instead?

When volume reaches thousands of jobs per second, when many different services consume the work, or when we need fan-out to several consumers. For a few hundred jobs per second inside one service, the table queue is simpler and transactional with the data that creates the jobs.

7Conclusion

In this answer, we built a PostgreSQL job queue that several workers can poll safely. The claim is one short UPDATE whose subquery uses FOR UPDATE SKIP LOCKED, so each worker locks different rows without waiting, and it marks them RUNNING with a worker id and timestamp in the same transaction. Processing happens outside that transaction, a reaper reclaims jobs stuck after a timeout, processing is idempotent, and indexes and cleanup keep the table fast.

What to say in the interviewAbout 90 seconds aloud

Open with

I would use FOR UPDATE SKIP LOCKED. Each worker claims a batch in one short transaction, ideally one statement: update job set status RUNNING, worker_id, claimed_at, attempts plus one, where id in a subquery that selects READY jobs ordered by id, limit 10, for update skip locked, returning the rows.

Then, if they want more

The row locks make sure two workers cannot take the same job, and SKIP LOCKED means a worker skips rows another worker has locked instead of waiting, so ten workers really run in parallel. The claim commits immediately and the status column records ownership, so I never hold a transaction or a connection while a job runs.

In Spring, that is a native query run through TransactionTemplate from a @Scheduled poller, then each job is processed and marked done or failed in its own short transaction. Hibernate can also produce SKIP LOCKED from a lock timeout of minus two on supporting dialects, but I prefer the native query.

For crashes, a reaper returns jobs that are RUNNING longer than a time limit to READY, up to a maximum number of attempts, and because a reclaimed job can run twice, the handlers are idempotent, for example with a unique constraint on the job id. A partial index on READY jobs and regular cleanup keep it fast.

About this answer

Last updated
12 November 2026
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.
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 "Implement a job queue in PostgreSQL that several worker instances poll without...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/a4a6981eb3/