PostgreSQL job queues on dedicated servers: claims, leases and recovery

PostgreSQL job queues on dedicated servers: claims, leases and recovery

When catalog synchronization and report generation share a dedicated server, adding worker processes is easy. Preventing duplicate claims requires an explicit protocol. Simply querying for unfinished jobs and then updating their status can let two workers pick up the same record. Marking a job as running is not enough either: a crashed worker can leave it stuck indefinitely. The following experiment uses PostgreSQL row locks, leases and claim versions to test concurrent claims and recovery from interruptions separately.

Define the experiment boundaries

Prepare PostgreSQL and psql on Debian 12 or Ubuntu Server 24.04 LTS, using an already configured database connection. Work only in a dedicated test database; do not connect to a production queue. The database role needs permission to create a schema. Both sessions must connect to the same database and use the default READ COMMITTED isolation level.

This approach does not depend on the dedicated server's memory tier. The essential constraints are to keep claim transactions short and perform business processing only after committing. An expired lease permits another worker to reclaim the job, but the old worker must not be able to overwrite the new claimant's state.

A lease allows reassignment after a worker becomes unreachable. It does not automatically cancel network requests already sent, nor does it guarantee exactly-once execution.

The 60-second lease in this article is for the experiment, not a recommended production value. Choose a real lease duration based on job runtime, renewal intervals and how long workers can tolerate temporary database unavailability.

Create the job state

Run the following SQL in session A. The test schema name must not already be in use. If creation fails, check the environment first rather than changing the script to overwrite existing objects.

\set ON_ERROR_STOP on

CREATE SCHEMA queue_lab;

CREATE TABLE queue_lab.jobs (
    job_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    payload jsonb NOT NULL,
    state text NOT NULL DEFAULT 'ready'
        CHECK (state IN ('ready', 'running', 'done')),
    lease_until timestamptz,
    claim_version bigint NOT NULL DEFAULT 0
);

INSERT INTO queue_lab.jobs (payload)
VALUES ('{"kind":"catalog","batch":1}'),
       ('{"kind":"report","batch":2}');

job_id identifies the business job and stays the same when it is reclaimed. claim_version identifies the current authorization and increments with every claim. Do not use a process ID as proof of ownership: the ID may be reused after the process exits.

Keeping completed records makes verification easier. In production, archive them according to your business retention policy. This example does not implement delayed execution, failure backoff or a maximum attempt count, so it is not a complete queue implementation ready for direct use.

Verify concurrent claims

In session A, begin a transaction and run the claim statement, but do not commit yet:

BEGIN;

WITH candidate AS (
    SELECT job_id
    FROM queue_lab.jobs
    WHERE state = 'ready'
       OR (
           state = 'running'
           AND lease_until <= statement_timestamp()
       )
    ORDER BY job_id
    LIMIT 1
    FOR UPDATE SKIP LOCKED
)
UPDATE queue_lab.jobs AS j
SET state = 'running',
    lease_until = statement_timestamp() + interval '60 seconds',
    claim_version = j.claim_version + 1
FROM candidate AS c
WHERE j.job_id = c.job_id
RETURNING j.job_id, j.claim_version, j.lease_until, j.payload
\gset claim_

\gset saves the returned fields as variables in the current psql session for use in later conditional updates. Enable ON_ERROR_STOP in session B as well, then run the same claim transaction. A should obtain job 1. B should skip the locked job 1 and obtain job 2, rather than waiting for A to finish its business processing.

Run COMMIT; in each session, then query:

SELECT job_id, state, claim_version, lease_until
FROM queue_lab.jobs
ORDER BY job_id;

You should see two running records, both with claim version 1. If B blocks, first confirm that the statement actually includes SKIP LOCKED, then investigate table-level locks or other database waits. Do not respond to blocking by simply adding more worker processes.

A real worker loop must not leave a transaction open during business processing. When there is no candidate job, the application should treat a zero-row result as temporarily having no work and poll at intervals. The example's \gset is intended only for an experiment where a record is guaranteed to exist; it is not suitable for handling the zero-row case.

Guard lease renewal and completion

Execute the job only after the claim transaction commits. Renewing a lease must check the job ID, version, state and expiry. The job ID alone is not enough to authorize an extension:

UPDATE queue_lab.jobs
SET lease_until = statement_timestamp() + interval '60 seconds'
WHERE job_id = :claim_job_id
  AND claim_version = :claim_claim_version
  AND state = 'running'
  AND lease_until > statement_timestamp()
RETURNING job_id, claim_version, lease_until;

Completion uses the same authorization conditions:

UPDATE queue_lab.jobs
SET state = 'done', lease_until = NULL
WHERE job_id = :claim_job_id
  AND claim_version = :claim_claim_version
  AND state = 'running'
  AND lease_until > statement_timestamp()
RETURNING job_id, state;

Do not run the completion statement yet; save it for the next section's test. These variables come from each session's own claim result. Do not copy another worker's version.

Check the number of rows returned by both types of update. Zero rows means the current authorization is no longer valid; the worker must not ignore that result and continue writing results. An old version cannot restore its own authorization even if the lease has expired and no other worker has reclaimed the job yet.

Using database time avoids inconsistent decisions caused by differences between workers' local clocks, but it cannot eliminate jumps in the database clock. This example uses the statement start time and commits each renewal independently, rather than treating the start time of a long-running transaction as the current time.

Test reclaiming and clean up

Make sure both A and B have committed their claim transactions. To avoid waiting, use a separate test session to move job 1's lease into the past, simulating natural lease expiry after A exits:

UPDATE queue_lab.jobs
SET lease_until = statement_timestamp() - interval '1 second'
WHERE job_id = 1 AND state = 'running';

Have B run and commit another claim transaction. It should receive job 1 with version 2. Then have A run the completion statement from the previous section; it should return zero rows. B should run the completion statement using its own new variables and receive one row. Perform these operations in quick succession. If the experimental lease has already expired, recreate the test data before repeating the verification.

This proves that the old claimant cannot commit queue state, but it does not prove that external side effects cannot occur more than once. If a job calls a remote API, it must pass a stable business idempotency key. If the downstream system supports version fencing, it should also reject stale claim versions. Checking the version locally just once before sending a request still leaves a window in which authorization can expire.

If all results are written to the same database, use a single short transaction: first update the job under the authorization conditions, confirm success, then write the business results and commit everything together. Roll back if any step fails. When remote systems are involved, you need idempotent handling at the receiving end and result reconciliation; you cannot claim that a database transaction covers network requests.

Finally, retain three pieces of evidence: concurrent claims obtain different jobs, reclaiming increments the version, and completion with the old version returns zero rows. Disconnect unnecessary test sessions, verify the database and schema, then remove the dedicated experiment objects:

DROP TABLE queue_lab.jobs;
DROP SCHEMA queue_lab;

Before deploying to production, also add failure backoff, attempt tracking, lease renewal for long-running jobs and a way to reconcile results manually. The acceptance criterion is not that every job eventually becomes done. It is that every completion has valid authorization and every loss of contact has a defined recovery path.

Frequently asked questions

Does SKIP LOCKED guarantee exactly-once execution?

No. It only skips rows currently locked by another transaction. Once the claim commits, an expired lease can lead to another execution. External systems need idempotency based on a stable job ID or enforcement of the claim version.

Can a worker mark a job complete after its lease expires?

No. Renewal and completion must match the job ID, claim version, running state and an unexpired lease. An update returning no rows means ownership was lost; stop further side effects and reconcile the outcome.

AMD EPYC 7543P Dedicated Server

From $461.7/month

Review server specifications and access

Choose a configuration to match deployment requirements. After delivery, view the login credentials in the console.