AI Hints
Home›PostgreSQL Tutorial›Isolation, Locks and Job Queues
PostgreSQL · Lesson 69 of 120

FOR UPDATE SKIP LOCKED

A safe job queue.

⏱ 2 min read▶ Video at 1:02:11🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Riverside sends emails from a jobs table. Two workers run at the same time. They must never send the same email twice. For update skip locked lets each worker grab a different job.

  • Jobs table
  • Two workers
  • No duplicates

Two workers, different jobs

Each worker selects the oldest pending job for update, which locks it. Skip locked means, ignore jobs someone else has locked. So Alice and Bob each get a different job. Run it. Job one for Alice, job two for Bob.

workers.pypython
import psycopg

URL = "postgresql://postgres:postgres@localhost:5432/riverside"
alice = psycopg.connect(URL)   # first session
bob = psycopg.connect(URL)     # second session

alice.execute("CREATE TABLE jobs (id int PRIMARY KEY, task text)")
alice.execute("INSERT INTO jobs VALUES (1, 'email Tara'), (2, 'email Grace'), (3, 'email Finn')")
alice.commit()

grab = "SELECT id, task FROM jobs ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED"
print("Alice got:", alice.execute(grab).fetchone())
print("Bob got:  ", bob.execute(grab).fetchone())
Output
Alice got: (1, 'email Tara')
Bob got:   (2, 'email Grace')

Queue pattern

Grab a job with skip locked. Do the work. Delete or mark the job, then commit. If a worker crashes, its lock is released, and the job becomes available again. Simple, and no extra queue software.

keyvalue
GrabFOR UPDATE SKIP LOCKED
Workthen delete / mark done
Crashlock released
No extra toolsjust Postgres

Summary

For update skip locked turns a table into a safe job queue for many workers. Next, views.

Key takeaways
  • FOR UPDATE
  • SKIP LOCKED
  • Workers
Next up: Views — saved queries