Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Postgres performance optimization and best practices guide maintained by Supabase
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/lock-skip-locked.md
1---2title: Use SKIP LOCKED for Non-Blocking Queue Processing3impact: MEDIUM-HIGH4impactDescription: 10x throughput for worker queues5tags: skip-locked, queue, workers, concurrency6---78## Use SKIP LOCKED for Non-Blocking Queue Processing910When multiple workers process a queue, SKIP LOCKED allows workers to process different rows without waiting.1112**Incorrect (workers block each other):**1314```sql15-- Worker 1 and Worker 2 both try to get next job16begin;17select * from jobs where status = 'pending' order by created_at limit 1 for update;18-- Worker 2 waits for Worker 1's lock to release!19```2021**Correct (SKIP LOCKED for parallel processing):**2223```sql24-- Each worker skips locked rows and gets the next available25begin;26select * from jobs27where status = 'pending'28order by created_at29limit 130for update skip locked;3132-- Worker 1 gets job 1, Worker 2 gets job 2 (no waiting)3334update jobs set status = 'processing' where id = $1;35commit;36```3738Complete queue pattern:3940```sql41-- Atomic claim-and-update in one statement42update jobs43set status = 'processing', worker_id = $1, started_at = now()44where id = (45select id from jobs46where status = 'pending'47order by created_at48limit 149for update skip locked50)51returning *;52```5354Reference: [SELECT FOR UPDATE SKIP LOCKED](https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE)55