Full answer
sql
CREATE TABLE jobs (id int PRIMARY KEY, status text NOT NULL, created int NOT NULL);
CREATE INDEX jobs_pending ON jobs(created) WHERE status = 'pending';
INSERT INTO jobs VALUES (1, 'pending', 1), (2, 'pending', 2), (3, 'done', 0);
SELECT id, status FROM jobs ORDER BY id;| id | status |
|---|---|
| 1 | pending |
| 2 | pending |
| 3 | done |
One worker's claim, as a single statement with a CTE:
sql
WITH next AS (
SELECT id FROM jobs WHERE status = 'pending'
ORDER BY created LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE jobs SET status = 'running' FROM next WHERE jobs.id = next.id
RETURNING jobs.id, jobs.status;| id | status |
|---|---|
| 1 | running |
Job 1 is claimed and returned. A second worker running the same statement at the same moment would skip job 1, because it is locked, and claim job 2 (the concurrent part is from the documentation; only one session ran here).
Details that matter in production:
- Order by priority or creation time so old jobs are not starved.
- Record
locked_atand requeue jobs whose worker died, by resetting jobs stuck in 'running' too long. - Keep the claim transaction short; do the actual work after committing the status change.
SQLite has no FOR UPDATE; with a single writer, an UPDATE ... WHERE id = (SELECT ... LIMIT 1) RETURNING id in a BEGIN IMMEDIATE transaction gives the same effect.
Key points
- FOR UPDATE locks the selected rows
- SKIP LOCKED skips rows other workers hold
- Claim in a short transaction, work after commit
- Requeue jobs whose workers die
- A partial index on pending rows keeps it fast
Common mistakes
- Selecting a job without locking and marking it later
- Doing long work inside the claim transaction
Follow-ups
- How would you add retries with backoff?
- What changes if jobs have priorities?
Tips
- Mention crash recovery for claimed jobs