How to Write a Task Queue in SQL

PostgreSQL can store jobs in a table and let multiple workers claim them. This example uses row locks to claim one job at a time.

1. Create the queue table

CREATE TABLE task_queue (
  id SERIAL PRIMARY KEY,
  task_name TEXT NOT NULL,
  task_params JSONB,
  status TEXT NOT NULL DEFAULT 'pending',
  error_message TEXT,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

A new job starts as pending. The error_message column keeps failure details separate from the original task parameters.

2. Add a task

INSERT INTO task_queue (task_name, task_params)
VALUES ('send_email', '{"to": "[email protected]", "subject": "Hello", "body": "World"}');

3. Claim a pending task

Each worker uses its own connection. This single statement finds and locks the oldest available task, changes its status, and returns its details:

WITH next_task AS (
  SELECT id
  FROM task_queue
  WHERE status = 'pending'
  ORDER BY created_at, id
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE task_queue AS task
SET status = 'processing', updated_at = NOW()
FROM next_task
WHERE task.id = next_task.id
RETURNING task.*;

SKIP LOCKED lets another worker claim a different task while this statement holds the row lock. Commit the claim before starting the work. If the statement returns no rows, no unlocked pending task was available at that moment. With autocommit enabled, the database commits the statement automatically.

4. Mark the task as completed

Use the ID returned by the claim statement as $1:

UPDATE task_queue
SET status = 'completed', updated_at = NOW()
WHERE id = $1 AND status = 'processing';

5. Record failures

On failure, keep the original task parameters and store the error separately. Pass the claimed ID as $1 and the error message as $2:

UPDATE task_queue
SET status = 'failed', error_message = $2, updated_at = NOW()
WHERE id = $1 AND status = 'processing';

6. Run multiple workers

Workers can claim tasks in parallel using separate connections. A worker can still crash after claiming a task, leaving it in processing. A production queue needs a recovery policy, such as expiring a claim and retrying it, and tasks should tolerate retries. This sketch does not implement leases, retries, or exactly-once delivery.