Consume a FIFO queue
Oldest-first selection plus row locks that skip what other workers already hold.
The task
Several workers poll a jobs table. Each should take the oldest pending jobs and no two workers may take the same job.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
WITH next_jobs AS (
SELECT id
FROM jobs
WHERE status = 'pending'
ORDER BY created_at, id
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE jobs j
SET status = 'processing'
FROM next_jobs n
WHERE j.id = n.id
RETURNING j.id, j.created_at;
工作原理
The CTE sorts pending jobs oldest-first, locks the first ten, and SKIP LOCKED silently skips rows another worker locked a moment ago, so concurrent workers never double-claim. The UPDATE then flips exactly those rows and RETURNING hands them back. Without SKIP LOCKED workers queue behind each other's locks; without FOR UPDATE they race and process the same job twice. SKIP LOCKED needs PostgreSQL 9.5+, MySQL 8.0+ or Oracle; SQL Server gets the same effect from the READPAST hint, and its plain UPDATE TOP (10) would pick arbitrary rows, which is why the variant sorts inside a CTE.
Variations
MySQL 8: SKIP LOCKED inside a joined derived table
MySQLUPDATE jobs j
JOIN (
SELECT id FROM jobs
WHERE status = 'pending'
ORDER BY created_at, id
LIMIT 10
FOR UPDATE SKIP LOCKED
) n ON n.id = j.id
SET j.status = 'processing';
SQL Server: updatable CTE with READPAST
SQL ServerWITH next_jobs AS (
SELECT TOP (10) id, created_at, status
FROM jobs WITH (ROWLOCK, UPDLOCK, READPAST)
WHERE status = 'pending'
ORDER BY created_at, id
)
UPDATE next_jobs
SET status = 'processing'
OUTPUT inserted.id, inserted.created_at;
Questions that come up
Why not just SELECT the oldest rows and update them after?
Between the SELECT and the UPDATE another worker can claim the same rows. The lock must be taken while reading, which is exactly what FOR UPDATE SKIP LOCKED does in one round trip.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.