Drive a Scrape Queue With Postgres SKIP LOCKED
Build a scrape job queue in Postgres: workers claim URL rows with SKIP LOCKED, fetch pages, and load results without duplicate work.
On this page
Where Homegrown Scrape Queues Fall Apart
Every scraping pipeline I’ve built past the toy stage has needed the same three things: a list of URLs, some workers to fetch them, and a way to make sure two workers never fetch the same URL at the same time. The first two are easy. The third is where most homegrown queues fall apart.
The usual story goes like this: you stuff URLs into a Postgres table, spawn four worker processes, and each one runs SELECT ... WHERE status = 'pending' LIMIT 10, then updates those rows to running and fetches them. It works fine with one worker. The moment you run two, you start seeing duplicate fetches in your logs — same URL, two different workers, seconds apart. Wasted requests, wasted proxy bandwidth, and duplicate rows in your results table unless you dedupe downstream.
Postgres has had the fix built in for years: SELECT ... FOR UPDATE SKIP LOCKED. It turns a regular table into a proper work queue where workers claim disjoint batches atomically, never block each other, and never double-fetch. No Redis, no SQS, no Celery broker. Just the database you already have. This post builds that queue end to end.
Model the Scrape Queue as a Single jobs Table
One table holds all the queue state. No separate locks table, no worker registry. The status column is the queue position, attempts tracks retries, and claimed_at doubles as the visibility timeout.
CREATE TABLE scrape_jobs (
id BIGSERIAL PRIMARY KEY,
url TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'running', 'done', 'failed')),
attempts INT NOT NULL DEFAULT 0,
next_run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
claimed_at TIMESTAMPTZ,
fetched_at TIMESTAMPTZ,
http_status INT,
fetched_body TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- The claim query only ever touches pending rows.
-- A partial index keeps that scan tiny even when the table has millions of rows.
CREATE INDEX idx_scrape_jobs_pending
ON scrape_jobs (id)
WHERE status = 'pending';
The partial index is the part people skip. Without it, every claim query scans past all your done and failed rows to find the pending ones. With it, the claim is an index scan over a handful of rows. On a table with 5 million finished jobs and 200 pending ones, that difference is the whole ballgame.
Seed it with a few rows so we have something to claim:
INSERT INTO scrape_jobs (url) VALUES
('https://example.com/products/1'),
('https://example.com/products/2'),
('https://example.com/products/3'),
('https://example.com/products/4'),
('https://example.com/products/5');
That’s the entire queue infrastructure. Everything else in this post is queries against this one table.
Why SELECT-then-UPDATE Lets Two Workers Fetch the Same URL
Before the fix, understand the bug. Here’s the naive claim pattern under default READ COMMITTED isolation, with two workers running concurrently against the five rows we just seeded:
-- Worker A, t=0ms
BEGIN;
SELECT id FROM scrape_jobs WHERE status = 'pending' LIMIT 10;
-- returns ids 1..5
-- Worker B, t=2ms
BEGIN;
SELECT id FROM scrape_jobs WHERE status = 'pending' LIMIT 10;
-- ALSO returns ids 1..5 (Worker A hasn't committed anything yet)
-- Worker A, t=5ms
UPDATE scrape_jobs SET status = 'running' WHERE id IN (1, ..., 5);
COMMIT; -- now fetches products/1..5
-- Worker B, t=6ms
UPDATE scrape_jobs SET status = 'running' WHERE id IN (1, ..., 5);
COMMIT; -- also fetches products/1..5
Both workers saw the same rows in the pending state because neither had written anything yet. The SELECT takes no locks, and the UPDATE only conflicts after the fact — by which point both workers have already been handed the same URLs.
Here’s how the three claim strategies compare:
| Strategy | Duplicate fetches | Worker blocking | Workers skip ahead |
|---|---|---|---|
Plain SELECT then UPDATE | Yes, under concurrency | None | No — same rows returned to everyone |
SELECT ... FOR UPDATE | No | Yes — second worker blocks until first commits | No — blocked worker waits, then re-reads |
FOR UPDATE SKIP LOCKED | No | None — locked rows are skipped instantly | Yes — worker grabs the next unclaimed batch |
FOR UPDATE alone fixes correctness but wrecks throughput: your workers form a conga line, each waiting on the previous one’s transaction. SKIP LOCKED is the missing half — it says “if another worker already holds a lock on a row, don’t wait, don’t take it, just move down the list.”
Claim a Batch of URLs Atomically with FOR UPDATE SKIP LOCKED
Here is the entire claim mechanism, one statement:
WITH next_jobs AS (
SELECT id
FROM scrape_jobs
WHERE status = 'pending'
AND next_run_at <= now()
ORDER BY id
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE scrape_jobs
SET status = 'running',
claimed_at = now()
WHERE id IN (SELECT id FROM next_jobs)
RETURNING id, url;
Clause by clause, because every piece is doing specific work:
WHERE status = 'pending' AND next_run_at <= now()— only rows that are actually claimable. Thenext_run_atfilter is what makes retries with backoff work later; a row scheduled for two minutes from now is invisible to claimers until then.ORDER BY id LIMIT 10— batch sizing. Ten URLs per claim keeps claim frequency low while still giving the worker a unit of work worth having.FOR UPDATE SKIP LOCKED— the whole trick. Rows another worker has locked in an uncommitted transaction are skipped, not waited on. Two workers running this simultaneously each get disjoint batches, instantly.RETURNING id, url— hands the claimed URLs straight to the worker in the same round trip.
Write a Worker Loop That Claims, Fetches, and Reports Back
The worker is about 30 lines of Python with psycopg. Claim in one transaction, fetch outside it, then report success or failure in a second transaction. Never hold the claim transaction open while a fetch is in flight — that’s how you turn a queue into a bottleneck.
import time
import requests
import psycopg
DB = "postgres://scraper:pw@example.com:5432/scrape"
CLAIM = """
WITH next_jobs AS (
SELECT id FROM scrape_jobs
WHERE status = 'pending' AND next_run_at <= now()
ORDER BY id LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE scrape_jobs
SET status = 'running', claimed_at = now()
WHERE id IN (SELECT id FROM next_jobs)
RETURNING id, url
"""
def fetch(url):
r = requests.get(url, timeout=30)
r.raise_for_status()
return r.text
def run_worker():
with psycopg.connect(DB) as conn:
while True:
with conn.transaction():
batch = conn.execute(CLAIM).fetchall()
if not batch:
time.sleep(1)
continue
for job_id, url in batch:
try:
body = fetch(url)
report_success(conn, job_id, body)
except Exception:
report_failure(conn, job_id)
The queue logic is identical whether fetch is a plain requests.get, a headless browser, or a hosted scrape API — the queue only cares that fetching is slow and failure-prone, which it always is. If you’re weighing whether workers should block on fetches at all, I wrote about the sync vs async scraping tradeoffs in more depth.
Load Results and Failures with Attempts and Exponential Backoff
Success is a plain UPDATE:
UPDATE scrape_jobs
SET status = 'done',
fetched_at = now(),
http_status = 200,
fetched_body = %s
WHERE id = %s;
Failure is where the design earns its keep. Instead of deleting the row or leaving it stranded in running, flip it back to pending with a backoff schedule — or to failed once it has burned its attempts:
UPDATE scrape_jobs
SET status = CASE WHEN attempts + 1 >= 3 THEN 'failed' ELSE 'pending' END,
attempts = attempts + 1,
next_run_at = now() + (interval '5 seconds' * pow(2, attempts)),
claimed_at = NULL
WHERE id = %s;
The next_run_at bump means the row sits invisible to claimers for 10 seconds, then 20, then 40 — and after three strikes it’s parked in failed as a permanent record of what didn’t work. Because failed rows keep their full history, re-driving only the failures later is a simple UPDATE ... WHERE status = 'failed' away.
One decision worth flagging: this schema stores the raw HTML in fetched_body. If you’re building a real pipeline, see parse at fetch time vs store raw HTML — the trade-offs between storing bodies and storing parsed fields are nontrivial, and they get expensive to reverse later.
Requeue Stale Claims So a Crashed Worker Doesn’t Strand Jobs
SKIP LOCKED has one sharp edge: if a worker dies mid-fetch — process killed, laptop closed, spot instance reclaimed — its rows stay running forever, because the lock died with the connection but the status update never happened. The fix is a visibility timeout, requeueing anything that has been running too long:
UPDATE scrape_jobs
SET status = 'pending',
claimed_at = NULL,
next_run_at = now()
WHERE status = 'running'
AND claimed_at < now() - interval '10 minutes';
Run it on a schedule with pg_cron and you never have to think about it again:
SELECT cron.schedule('requeue-stale', '*/1 * * * *', $$
UPDATE scrape_jobs
SET status = 'pending', claimed_at = NULL
WHERE status = 'running'
AND claimed_at < now() - interval '10 minutes';
$$);
Set the timeout comfortably above your worst-case fetch time, or you’ll requeue jobs whose workers are still mid-flight and fetch some URLs twice — the exact bug you built the queue to avoid.
Measure It: Draining 1,000 URLs with One vs Four Workers
To check that the queue actually parallelizes, I seeded 1,000 rows and ran workers whose “fetch” was a 50ms sleep against local Postgres — no network, so the numbers isolate the queue mechanics:
INSERT INTO scrape_jobs (url)
SELECT 'https://example.com/pages/' || n
FROM generate_series(1, 1000) AS n;
| Setup | Wall time | Duplicate fetches |
|---|---|---|
| 1 worker | 51.4s | 0 |
| 4 workers | 13.9s | 0 |
Four workers drained the queue in roughly a quarter of the single-worker time, and the results table had exactly 1,000 rows both ways. The claim query itself added under 2ms per batch — SKIP LOCKED costs essentially nothing until you’re claiming thousands of batches per second.
When to Graduate from Postgres to Redis or SQS
This queue holds up surprisingly far — tens of thousands of jobs per minute is fine, and the partial index keeps claims cheap into the millions of rows. The honest graduation signs:
- Claim rate, not table size. If workers are claiming hundreds of times per second, the
UPDATE-per-claim write amplification starts to show inpg_stat_statements, and a RedisBLPOP-style queue will be cheaper per claim. - Fan-out to non-Postgres consumers. The moment your workers are Lambda functions or a different service entirely, SQS’s push model beats maintaining a connection pool against the database.
- Priority queues. You can fake it with an
ORDER BY priorityin the claim, but real priority semantics get fiddly; a dedicated broker does them natively.
If you’re nowhere near these, staying on Postgres is the right call — one fewer moving part, one fewer thing to page you at 3am.
Wrap-Up
The whole queue is one table, one claim statement, one requeue cron:
- A partial index on
status = 'pending'keeps claims fast no matter how big the table gets. FOR UPDATE SKIP LOCKEDmakes concurrent claims disjoint and non-blocking — no duplicate fetches, no conga lines.next_run_atplusattemptsgives you retries with exponential backoff and a dead-letter state for free.- A
pg_cronrequeue of stalerunningrows covers crashed workers.
If you want to go deeper on the pipeline side — raw layer, clean layer, curated layer — read the three-layer pipeline pattern; this queue is a natural front end for it. And if you’d rather not run workers at all, FineData handles the fetching end of this pipeline for you.
Related Articles
Dead-Letter Failed URLs, Then Replay Them Safely
Build a scraping pipeline that parks failed URLs in a dead-letter queue, inspects why each one failed, and replays them without losing rows or duplicating work.
TutorialRe-Run a Scrape Batch Without Duplicate Rows
Run a batch of URLs through a scrape pipeline and load results with idempotent upserts, so a re-run updates rows instead of duplicating them.
TutorialAsync Job Results Arrive Out of Order: Merge by Key
Async job results come back in any order. Map each job ID to its URL with a keyed merge, rebuild the batch order, and flag missing or duplicate results.