Databases

PostgreSQL as a Priority Job Queue: Delayed Jobs, Retry Logic, and Dead Letter Queue Without Redis

Ruslan Ismailov Published 14 min read
P

1. Introduction: When PostgreSQL as a Queue Is the Right Choice in 2026

Most teams add Redis to their infrastructure almost automatically: need a job queue — grab Redis + Sidekiq/BullMQ. But the operational cost of every new component is real: separate monitoring, persistence configuration, HA cluster setup, team onboarding. In 2026, PostgreSQL versions 15–17 handle queue patterns so well that for most applications handling up to a few thousand tasks per second, it is a sufficient and more reliable solution.

PostgreSQL as a job queue makes sense when:

  • You need transactional guarantees: a job is created atomically together with a business object in the same transaction.
  • Your team already knows how to manage PostgreSQL and doesn't want to add Redis just for queues.
  • Job volume is up to 5,000–10,000 per second (beyond that, measure and make a conscious decision).
  • You need rich job analytics: SQL is the most convenient tool for that.

In this article, we'll build a complete system: a table schema, a concurrent consumer using SKIP LOCKED, priorities, delayed execution, retry with exponential backoff, and a Dead Letter Queue.

2. Table Schema for the Queue

Let's start with the main table. Every field is intentional: no unnecessary columns, only what the consumer and monitoring need.

CREATE TYPE job_status AS ENUM (
  'pending',
  'running',
  'succeeded',
  'failed',
  'dead'
);

CREATE TABLE jobs (
  id              BIGSERIAL PRIMARY KEY,
  queue           TEXT NOT NULL DEFAULT 'default',
  payload         JSONB NOT NULL,
  status          job_status NOT NULL DEFAULT 'pending',
  priority        SMALLINT NOT NULL DEFAULT 100,  -- lower = higher priority
  scheduled_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  started_at      TIMESTAMPTZ,
  finished_at     TIMESTAMPTZ,
  attempts        SMALLINT NOT NULL DEFAULT 0,
  max_attempts    SMALLINT NOT NULL DEFAULT 5,
  error_message   TEXT,
  error_trace     TEXT,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Primary index for job fetching by the consumer
CREATE INDEX idx_jobs_queue_fetch
  ON jobs (queue, priority ASC, scheduled_at ASC)
  WHERE status = 'pending';

-- Index for finding stuck jobs (heartbeat/timeout)
CREATE INDEX idx_jobs_running_started
  ON jobs (started_at)
  WHERE status = 'running';

-- GIN index for searching by payload content
CREATE INDEX idx_jobs_payload_gin
  ON jobs USING GIN (payload jsonb_path_ops);

-- Auto-update updated_at
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$;

CREATE TRIGGER trg_jobs_updated_at
  BEFORE UPDATE ON jobs
  FOR EACH ROW EXECUTE FUNCTION update_updated_at();

A few important decisions in this schema:

  • ENUM for status — saves space and enforces validation at the database level. Partitioning by status (LIST) is possible, but for most projects a partial index WHERE status = 'pending' is sufficient.
  • priority ASC — a lower number means higher priority (like Unix nice). This is the standard convention.
  • scheduled_at — enables Delayed Jobs without additional tables.
  • GIN index on payload — only needed if you search jobs by content (e.g., all jobs for a specific user). If you don't need it — don't create it; GIN is expensive on writes.

Partitioning for High Loads

If the table grows quickly, consider splitting it by status using LIST partitioning or by created_at using RANGE. For most projects, periodic cleanup of completed jobs is sufficient:

-- Archive and clean up jobs older than 30 days
DELETE FROM jobs
WHERE status IN ('succeeded', 'dead')
  AND finished_at < NOW() - INTERVAL '30 days';

3. SKIP LOCKED in Action: Concurrent Consumer Without Locks

SELECT ... FOR UPDATE SKIP LOCKED is a key PostgreSQL feature (available since version 9.5) that makes it suitable for queues. Without it, multiple workers would block each other when trying to claim a job.

-- Atomically claim one job for the worker
WITH next_job AS (
  SELECT id
  FROM jobs
  WHERE status = 'pending'
    AND queue = 'default'
    AND scheduled_at <= NOW()
  ORDER BY priority ASC, scheduled_at ASC
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE jobs
SET
  status     = 'running',
  started_at = NOW(),
  attempts   = attempts + 1
FROM next_job
WHERE jobs.id = next_job.id
RETURNING jobs.*;

How it works: FOR UPDATE locks the row, and SKIP LOCKED causes already-locked rows to be skipped instead of waited on. The result — each worker instantly gets its own unique job without collisions.

EXPLAIN ANALYZE for Optimization

EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
WITH next_job AS (
  SELECT id
  FROM jobs
  WHERE status = 'pending'
    AND queue = 'default'
    AND scheduled_at <= NOW()
  ORDER BY priority ASC, scheduled_at ASC
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE jobs
SET status = 'running', started_at = NOW(), attempts = attempts + 1
FROM next_job
WHERE jobs.id = next_job.id
RETURNING jobs.*;

-- Expected plan:
-- Update on jobs  (cost=0.57..8.59 rows=1)
--   ->  Nested Loop
--         ->  Limit  (rows=1)
--               ->  Index Scan using idx_jobs_queue_fetch on jobs
--                     Index Cond: (queue = 'default' AND scheduled_at <= now())
--                     Filter: (status = 'pending')

If you see a Sequential Scan instead of an Index Scan — verify that the partial index idx_jobs_queue_fetch was created correctly and that the planner can see it.

Handling Stuck Jobs

A worker can crash, leaving a job in running status. You need a periodic process (e.g., once per minute):

-- Return stuck jobs to the queue (10-minute timeout)
UPDATE jobs
SET
  status        = 'pending',
  started_at    = NULL,
  error_message = 'Worker timeout — job returned to queue'
WHERE status = 'running'
  AND started_at < NOW() - INTERVAL '10 minutes';

4. Job Priorities: Weighted Priorities and Fair Scheduling

Simple sorting by priority ASC works well, but creates a starvation problem: low-priority jobs never get executed if high-priority ones keep arriving. Let's implement fair scheduling through weighted randomness.

-- Fair scheduling: mix priority with randomness
WITH next_job AS (
  SELECT id
  FROM jobs
  WHERE status = 'pending'
    AND queue = 'default'
    AND scheduled_at <= NOW()
  ORDER BY
    -- Normalize priority and add random noise
    (priority * 0.7 + RANDOM() * 30) ASC,
    scheduled_at ASC
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE jobs
SET status = 'running', started_at = NOW(), attempts = attempts + 1
FROM next_job
WHERE jobs.id = next_job.id
RETURNING jobs.*;

The coefficient 0.7 determines the "weight" of priority: at 1.0 — pure priority (starvation is possible), at 0.0 — pure randomness (effectively FIFO). Tune it to your requirements.

For different job groups (tenant isolation), add a group_id column and pick one job per group in round-robin:

-- Get the next job with group awareness (fair per tenant)
WITH ranked AS (
  SELECT
    id,
    ROW_NUMBER() OVER (
      PARTITION BY group_id
      ORDER BY priority ASC, scheduled_at ASC
    ) AS rn
  FROM jobs
  WHERE status = 'pending'
    AND scheduled_at <= NOW()
),
next_job AS (
  SELECT id
  FROM ranked
  WHERE rn = 1
  ORDER BY RANDOM()  -- random tenant
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE jobs
SET status = 'running', started_at = NOW(), attempts = attempts + 1
FROM next_job
WHERE jobs.id = next_job.id
RETURNING jobs.*;

5. Delayed Jobs: Scheduled Execution

The scheduled_at field is already part of the schema. Creating a delayed job is trivial:

-- A job that will run in 15 minutes
INSERT INTO jobs (queue, payload, scheduled_at)
VALUES (
  'emails',
  '{"type": "welcome_email", "user_id": 42}',
  NOW() + INTERVAL '15 minutes'
);

-- A job with a specific start time
INSERT INTO jobs (queue, payload, priority, scheduled_at)
VALUES (
  'reports',
  '{"type": "monthly_report", "month": "2026-01"}',
  50,  -- high priority
  '2026-02-01 06:00:00+00'
);

The consumer already includes the condition AND scheduled_at <= NOW(), so delayed jobs won't be picked up before their time. Execution accuracy depends on the worker's polling frequency. With polling every 500 ms, the maximum delay is ~500 ms — sufficient for most cases. For jobs requiring second-level precision, use LISTEN/NOTIFY:

-- Trigger to notify workers of a new job
CREATE OR REPLACE FUNCTION notify_job_inserted()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
  PERFORM pg_notify('jobs_channel', NEW.queue);
  RETURN NEW;
END;
$$;

CREATE TRIGGER trg_jobs_notify
  AFTER INSERT ON jobs
  FOR EACH ROW
  WHEN (NEW.scheduled_at <= NOW())  -- immediate jobs only
  EXECUTE FUNCTION notify_job_inserted();

The worker subscribes to the channel with LISTEN jobs_channel and reacts instantly, instead of constantly polling the database.

6. Retry Logic: Exponential Backoff

After a failed execution, a job should retry with increasing delays. All retry logic can be expressed in a single SQL statement:

-- Mark a job as failed and schedule a retry
UPDATE jobs
SET
  status        = CASE
                    WHEN attempts >= max_attempts THEN 'failed'
                    ELSE 'pending'
                  END,
  finished_at   = CASE
                    WHEN attempts >= max_attempts THEN NOW()
                    ELSE NULL
                  END,
  -- Exponential backoff: 2^attempts seconds + jitter
  scheduled_at  = CASE
                    WHEN attempts >= max_attempts THEN scheduled_at
                    ELSE NOW() + (POWER(2, attempts) * INTERVAL '1 second')
                         + (RANDOM() * INTERVAL '10 seconds')  -- jitter
                  END,
  error_message = $2,
  error_trace   = $3
WHERE id = $1;

Delay calculation with max_attempts = 5:

  • Attempt 1 → retry in ~2 s + jitter
  • Attempt 2 → retry in ~4 s + jitter
  • Attempt 3 → retry in ~8 s + jitter
  • Attempt 4 → retry in ~16 s + jitter
  • Attempt 5 → status failed, job moves to DLQ processing

Jitter (random addition of up to 10 s) prevents the "thundering herd" problem — a situation where all failed jobs return to the queue simultaneously and overwhelm an external service.

7. Dead Letter Queue: Analysis and Manual Requeue

The Dead Letter Queue (DLQ) is where jobs that have exhausted all attempts end up. In our implementation, you can use a separate table or simply the 'dead' status in the same table. I recommend a separate table: it keeps the main queue clean and allows storing history without affecting performance.

CREATE TABLE dead_letter_jobs (
  id              BIGSERIAL PRIMARY KEY,
  original_job_id BIGINT NOT NULL,
  queue           TEXT NOT NULL,
  payload         JSONB NOT NULL,
  attempts        SMALLINT NOT NULL,
  last_error      TEXT,
  error_trace     TEXT,
  died_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  requeued_at     TIMESTAMPTZ,
  notes           TEXT  -- for manual comments during analysis
);

CREATE INDEX idx_dlq_queue ON dead_letter_jobs (queue, died_at DESC);
CREATE INDEX idx_dlq_payload ON dead_letter_jobs USING GIN (payload jsonb_path_ops);

-- Function to move a job to the DLQ
CREATE OR REPLACE FUNCTION move_to_dlq(p_job_id BIGINT)
RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE
  v_job jobs%ROWTYPE;
BEGIN
  SELECT * INTO v_job FROM jobs WHERE id = p_job_id FOR UPDATE;

  INSERT INTO dead_letter_jobs
    (original_job_id, queue, payload, attempts, last_error, error_trace)
  VALUES
    (v_job.id, v_job.queue, v_job.payload, v_job.attempts,
     v_job.error_message, v_job.error_trace);

  UPDATE jobs SET status = 'dead', finished_at = NOW()
  WHERE id = p_job_id;
END;
$$;

Manual requeue of a job from the DLQ:

-- Requeue a single job from the Dead Letter Queue
WITH requeued AS (
  UPDATE dead_letter_jobs
  SET requeued_at = NOW()
  WHERE id = $1
    AND requeued_at IS NULL
  RETURNING original_job_id, queue, payload
)
INSERT INTO jobs (queue, payload, attempts, max_attempts)
SELECT queue, payload, 0, 5
FROM requeued;

-- Bulk requeue all jobs from DLQ for a given queue
WITH requeued AS (
  UPDATE dead_letter_jobs
  SET requeued_at = NOW()
  WHERE queue = 'emails'
    AND requeued_at IS NULL
    AND died_at > NOW() - INTERVAL '24 hours'
  RETURNING queue, payload
)
INSERT INTO jobs (queue, payload, attempts, max_attempts)
SELECT queue, payload, 0, 5
FROM requeued;

8. Queue Monitoring: SQL Queries and Metrics

Good monitoring is what separates a production-ready solution from a pet project. Here are a few key queries:

-- Summary by queue and status
SELECT
  queue,
  status,
  COUNT(*)                                    AS job_count,
  AVG(EXTRACT(EPOCH FROM (NOW() - created_at))) AS avg_age_seconds,
  MIN(scheduled_at)                           AS oldest_scheduled
FROM jobs
GROUP BY queue, status
ORDER BY queue, status;

-- Processing throughput (jobs per minute over the last hour)
SELECT
  queue,
  DATE_TRUNC('minute', finished_at) AS minute,
  COUNT(*) AS completed
FROM jobs
WHERE status = 'succeeded'
  AND finished_at > NOW() - INTERVAL '1 hour'
GROUP BY queue, minute
ORDER BY minute;

-- Jobs with the most errors (top issues)
SELECT
  payload->>'type' AS job_type,
  COUNT(*)         AS failed_count,
  MAX(error_message) AS last_error
FROM dead_letter_jobs
WHERE died_at > NOW() - INTERVAL '7 days'
GROUP BY job_type
ORDER BY failed_count DESC
LIMIT 20;

-- Average execution time by job type
SELECT
  payload->>'type'                                            AS job_type,
  COUNT(*)                                                    AS count,
  ROUND(AVG(EXTRACT(EPOCH FROM (finished_at - started_at))), 2) AS avg_duration_sec,
  ROUND(PERCENTILE_CONT(0.95) WITHIN GROUP
    (ORDER BY EXTRACT(EPOCH FROM (finished_at - started_at))), 2) AS p95_sec
FROM jobs
WHERE status = 'succeeded'
  AND finished_at > NOW() - INTERVAL '24 hours'
GROUP BY job_type;

For Prometheus, use postgres_exporter with custom queries. Add to its configuration:

pg_job_queue_stats:
  query: |
    SELECT queue, status, COUNT(*) AS count
    FROM jobs
    GROUP BY queue, status
  metrics:
    - queue:
        usage: LABEL
    - status:
        usage: LABEL
    - count:
        usage: GAUGE
        description: Number of jobs by queue and status

You can monitor active workers through pg_stat_activity — they will always appear with a FOR UPDATE SKIP LOCKED query:

SELECT COUNT(*) AS active_workers
FROM pg_stat_activity
WHERE query LIKE '%SKIP LOCKED%'
  AND state = 'active';

9. Comparison with Redis Streams

An honest comparison is important for making the right decision. Let's look at the key parameters.

Performance. Redis Streams processes hundreds of thousands of messages per second with microsecond latency — it operates in memory. PostgreSQL with proper configuration and indexes delivers 5,000–20,000 jobs/sec on typical hardware. For most applications, this is more than enough.

Reliability and transactionality. PostgreSQL wins: you can create a job and update a business object in a single transaction. In Redis this is impossible — there is always a window for desynchronization. Data loss on Redis restart without appendonly yes is a real production problem.

Operational complexity. If PostgreSQL is already in your infrastructure — zero additional cost. Redis requires separate monitoring, persistence configuration, HA via Sentinel or Cluster, and memory management.

Query richness. PostgreSQL wins outright: SQL allows any kind of analytics. Access to queue data in Redis is limited.

When Redis is preferable:

  • Load exceeds 10,000 jobs/sec and sub-millisecond latency is critical.
  • You need pub/sub with fan-out to many subscribers.
  • Jobs don't require transactional coupling with primary data.

10. Conclusion: When to Move to a Dedicated Message Broker

PostgreSQL as a job queue is not a compromise — it's a deliberate architectural choice for a wide class of applications. The implementation described in this article covers virtually all requirements: priorities, delayed execution, reliable retry, Dead Letter Queue, and monitoring.

Stay with PostgreSQL if:

  • Load is under 5,000–10,000 jobs/sec (measure, don't guess).
  • Transactionality on job creation is important.
  • The team wants a single source of truth for both data and jobs.
  • PostgreSQL is already part of your stack.

Move to a dedicated broker (RabbitMQ, Kafka, Redis Streams) if:

  • Peak load exceeds PostgreSQL's capacity on your hardware.
  • You need complex message routing (exchanges, bindings).
  • You need to replicate events across multiple systems (event streaming).
  • Latency must be below 1 ms.

Start with PostgreSQL. Measure. Move to a broker only when you have concrete numbers that prove the migration is necessary. Premature infrastructure optimization is just as much an anti-pattern as premature code optimization.

Technologies

Tags

Ruslan Ismailov

Senior Web / Backend Developer. Senior web/backend developer with 9 years of experience. Stack: PHP, Laravel, PostgreSQL, Redis, Docker, Kubernetes, REST, microservices, CI/CD. More about me →