October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Build a Fair Job Queue with PostgreSQL Using `SKIP LOCKED`

Use PostgreSQL’s SKIP LOCKED to claim bounded job batches without waiting on other workers, and understand the fairness and recovery policies the database does not provide.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use FOR UPDATE SKIP LOCKED to let concurrent PostgreSQL workers claim different ready jobs without waiting on rows another worker has locked. For a practical queue, select a bounded batch in a short transaction, update those rows to a claimed state atomically, and commit before running the work. This avoids duplicate claims during the transaction, but it does not guarantee strict FIFO, equal worker shares, or freedom from starvation.

How do I use FOR UPDATE SKIP LOCKED for a PostgreSQL job queue?

Store each job as a durable row with an explicit lifecycle, such as ready, running, done, and failed. Give jobs a stable enqueue time or sequence, plus a unique key to break ties. A worker can claim jobs with one statement that selects available rows, locks them without waiting on conflicting locks, changes their state, and returns the claimed records.

As an Amazon Associate I earn from qualifying purchases.

WITH picked AS (
    SELECT id
    FROM jobs
    WHERE state = 'ready'
      AND run_at <= now()
    ORDER BY priority DESC, enqueued_at ASC, id ASC
    LIMIT 20
    FOR UPDATE SKIP LOCKED
)
UPDATE jobs AS j
SET state = 'running',
    claimed_by = $1,
    claimed_at = now(),
    lease_until = now() + interval '5 minutes',
    attempts = attempts + 1
FROM picked
WHERE j.id = picked.id
RETURNING j.*;

This is an illustrative pattern, not a performance-tested query or a queue recipe guaranteed by PostgreSQL. Run the statement in a transaction and commit it before doing slow work. The selected rows are locked while the transaction is active; the update records the claim durably, and RETURNING provides the rows to process. PostgreSQL documents the locking clause in its SELECT reference and the data-modifying statement behavior in its UPDATE reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The ordering above favors higher priority first, then older enqueue time, then lower ID. For oldest-first selection, remove priority. A bounded batch limits how many jobs a worker reserves at once and gives the application a straightforward way to apply backpressure. Keep the eligibility predicate and state change within the same transaction so that competing workers cannot both claim the same ready row.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

What does “fair” mean for a queue?

Fairness is a policy you define, not a property supplied by SKIP LOCKED. A deterministic ORDER BY defines preference among eligible rows a worker can see and lock. Put a unique key last so rows tied on earlier sort fields still have a predictable order; PostgreSQL says rows tied on every ordering expression may be returned in implementation-dependent order.

With several workers, an earlier row may be locked by one worker while another skips it and claims a later row. That is the intended trade-off: workers can make progress instead of waiting, but processing order can diverge from global FIFO. Nor does the feature promise equal work distribution between workers or starvation-free scheduling. A frequently locked, failing, or repeatedly retried job may wait while other jobs proceed.

If old jobs must not be neglected, make that requirement explicit in the scheduling policy. Possible application-level approaches include factoring age into priority, defining retry limits and backoff, using leases, or designing tenant-aware or weighted scheduling. Monitor the age of the oldest ready job; the PostgreSQL reference describes locking behavior, not a guarantee about long-term scheduling fairness.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Does SKIP LOCKED guarantee FIFO?

No. It skips rows that cannot be locked immediately, so a worker can claim a later available row while an earlier row is locked. An ordering clause establishes a preference for eligible rows; it cannot force all concurrent workers to process or finish jobs in one global order.

There is also a separate ordering caveat in PostgreSQL’s documentation: at READ COMMITTED, a locking SELECT with ORDER BY can return rows out of order if it blocks while acquiring a lock and an ordering column changes during the wait. PostgreSQL describes a subquery-locking workaround when a strictly sorted result is required, but warns that it can lock all rows and materially affect performance. Under REPEATABLE READ or SERIALIZABLE, the described case produces a serialization failure instead. Queue workers using SKIP LOCKED generally avoid waiting on conflicting row locks, but applications should account for this caveat if ordering fields can change concurrently or the locking approach changes. See the PostgreSQL 16 SELECT documentation.

How do I prevent two workers from taking the same job?

Use the locking selection and state update as one atomic claim operation. A worker selects only rows in the eligible state, locks them, updates them to running, and commits. While the transaction holds the row locks, another worker using the same pattern skips those rows; after commit, the changed state keeps them out of the ready-job predicate.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
  • Keep the claim transaction short and do not perform network calls or other slow job work before committing.
  • Store who claimed the job and when, so operators and recovery logic can identify active claims.
  • Use a unique, stable ordering key after policy fields to make selection predictable when values tie.
  • Claim a bounded batch instead of reserving an unbounded queue.

PostgreSQL describes SKIP LOCKED as useful for avoiding contention among consumers of queue-like tables, while warning that it provides an inconsistent view of the data and is not suitable for general-purpose reads. Use it for coordination among queue consumers, not as a substitute for a consistent query elsewhere. The qualification is in the official locking-clause documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I retry jobs after a worker crashes?

A row lock coordinates a claim only while its transaction is open. If a worker commits a claim and then crashes, the row remains marked running unless the application has a recovery policy. A lease or claim deadline lets recovery logic find claims that have expired and decide whether to retry or fail them.

  1. Record the claim. Store the worker identity, claim time, lease deadline, and attempt count when moving the job to running.
  2. Detect expired claims. A recovery process should identify running jobs whose lease has expired and determine whether they are eligible to return to ready.
  3. Apply retry policy. Define a maximum attempt count, retry delay or backoff, and a terminal outcome for jobs that cannot succeed.
  4. Make external effects safe to repeat. A worker may successfully perform an external action and crash before recording completion. Use idempotency or another application-level protocol to prevent a retry from duplicating that effect.

A database transaction cannot, by itself, atomically commit an unrelated network service’s side effect. Leases and retries improve recovery, but they do not create exactly-once external execution. Keeping a transaction open for the entire job is another design, but holds row locks during the work and ties recovery to transaction and connection cleanup; if used, runtime must be bounded carefully.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How should I index and operate the queue?

Choose indexes to match the eligibility filter and ordering policy, then inspect execution plans and benchmark with representative concurrency. For a simple ready-state queue, a partial index over ordering columns restricted to ready rows may be a candidate. The right design depends on filters, priority distribution, scheduled times, and state transitions; there is no universal index or throughput figure established by PostgreSQL’s documentation.

Queue rows are updated repeatedly and may eventually be deleted or archived. Monitor operational signals that reveal both service delay and database maintenance needs:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Claim latency and the age of the oldest ready job.
  • Retry counts, terminal failures, and expired leases.
  • Lock waits and transaction duration.
  • Table and index growth, along with vacuum activity.

PostgreSQL’s routine vacuuming documentation explains vacuum’s maintenance role; it does not set queue-specific operating thresholds. Choose thresholds from the workload and service objectives.

Polling or notifications?

Polling the durable jobs table at a sensible interval is the simpler wake-up strategy. LISTEN/NOTIFY can optionally reduce idle polling latency, but it adds listener-connection lifecycle requirements. Treat notifications as a signal to check the table, not as the job record itself: the table remains the source of truth. PostgreSQL documents NOTIFY as a notification facility, not a durable queue.

When is a PostgreSQL-backed queue a good fit?

PostgreSQL can be a practical choice when jobs belong naturally alongside application data and transactional coupling matters. Whether it remains a good fit depends on actual workload and operational needs; there is no workload-independent point at which every queue should move elsewhere. Evaluate alternatives against the same concrete requirements:

  • How delivery, retries, and failure recovery must work.
  • Whether ordering, priority, or tenant fairness has specific guarantees.
  • Throughput and latency at representative workload and concurrency.
  • How much operational work recovery and queue visibility require.
  • Whether scheduling or dead-letter support is needed.

Benchmark the workload and measure oldest-job age and claim latency rather than relying on a generic capacity claim. PostgreSQL’s concurrency-control and MVCC documentation explain database behavior, but do not establish a universal queue throughput threshold.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.