# Building a Job Queue in PostgreSQL With FOR UPDATE SKIP LOCKED

> You do not need RabbitMQ to run background jobs. FOR UPDATE SKIP LOCKED turns a plain PostgreSQL table into a competing-consumer queue with transactional handoff. Here is the schema, the polling loop, and the one index that makes it fast.

Published: 2026-11-26. Author: Milan Jovanović.

Canonical: https://milanjovanovic.tech/blog/postgresql-queue-skip-locked-dotnet

Your application needs background jobs: emails, webhooks, report generation.
The reflex is to add RabbitMQ or Azure Service Bus, and now you're running one more piece of infrastructure with its own failure modes.

But you already have a database that supports locking, transactions, and durable storage.
Two clauses, `FOR UPDATE SKIP LOCKED`, turn a plain PostgreSQL table into a competing-consumer queue that supports **transactional handoff** with your business data, something most brokers can't give you.

Here's how to build one properly.

## The Problem With Naive Polling

The obvious approach is a status column and a polling query:

```sql
SELECT * FROM jobs WHERE status = 'pending' LIMIT 10;
```

With one worker, this works.
With two workers, both run the query at the same time, both get the same 10 rows, and every job runs twice.

You can try `FOR UPDATE` alone, which locks the selected rows.
But then worker two **blocks** waiting for worker one's locks, and your workers process jobs one batch at a time, sequentially.
You've built a queue with a global lock.

With `SKIP LOCKED`, the query skips locked rows instead of waiting on them and takes the next unlocked ones.
Worker one grabs jobs 1-10, worker two simultaneously grabs jobs 11-20, and nobody waits.

![Two workers dequeue from the same pending-jobs table: worker one locks rows 1 to 10 with FOR UPDATE SKIP LOCKED while worker two skips those locked rows and claims rows 11 to 20, so neither blocks the other](https://milanjovanovic.tech/blogs/articles/postgresql-queue-skip-locked-dotnet/competing-consumers.png)

This is the same [**competing consumers pattern**](https://milanjovanovic.tech/blog/competing-consumers-pattern-dotnet) a message broker gives you, expressed in SQL.

## The Schema

Here's a minimal jobs table:

```sql
CREATE TABLE jobs (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    type TEXT NOT NULL,
    payload JSONB NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    attempts INT NOT NULL DEFAULT 0,
    scheduled_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    completed_at TIMESTAMPTZ
);
```

And the index that makes the whole thing fast:

```sql
CREATE INDEX ix_jobs_pending
ON jobs (scheduled_at)
WHERE status = 'pending';
```

This is a partial index.
A queue table is mostly history: millions of completed rows and a handful of pending ones.
The partial index contains **only the pending rows**, so the dequeue query stays fast no matter how much history accumulates.

I covered why partial indexes behave this way in [**PostgreSQL indexing for .NET developers**](https://milanjovanovic.tech/blog/postgresql-indexes-dotnet).

## The Dequeue Query

The core of the queue is one statement that claims a batch atomically:

```sql
UPDATE jobs
SET status = 'processing', attempts = attempts + 1
WHERE id IN (
    SELECT id
    FROM jobs
    WHERE status = 'pending'
      AND scheduled_at <= now()
    ORDER BY scheduled_at
    LIMIT 10
    FOR UPDATE SKIP LOCKED
)
RETURNING id, type, payload, attempts;
```

Walking through it:

- The inner `SELECT` finds up to 10 due jobs, locking them with `FOR UPDATE`.
- `SKIP LOCKED` skips rows another worker has already locked, so concurrent workers get disjoint batches.
- The `UPDATE` marks them as processing and `RETURNING` hands them back in one round trip.

`ORDER BY scheduled_at` gives approximate FIFO.
It's approximate because skipped rows break strict ordering, which is the same trade-off every competing-consumer system makes.
If you need strict message ordering, a queue with parallel workers is the wrong tool no matter what technology backs it.

## The Worker in .NET

Here's a complete polling worker as a `BackgroundService`, using Dapper for brevity:

```bash
dotnet add package Dapper
dotnet add package Npgsql.DependencyInjection
```

```csharp
using Dapper;
using Npgsql;

public interface IJobHandler
{
    Task HandleAsync(string payload, CancellationToken ct);
}

public sealed class JobQueueWorker(
    NpgsqlDataSource dataSource,
    IServiceScopeFactory scopeFactory,
    ILogger<JobQueueWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            int processed = 0;

            try
            {
                processed = await ProcessBatchAsync(ct);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Job batch failed");
            }

            if (processed == 0)
            {
                await Task.Delay(TimeSpan.FromSeconds(1), ct);
            }
        }
    }

    private async Task<int> ProcessBatchAsync(CancellationToken ct)
    {
        await using var connection = await dataSource.OpenConnectionAsync(ct);
        await using var transaction = await connection.BeginTransactionAsync(ct);

        var jobs = (await connection.QueryAsync<JobRow>(
            """
            UPDATE jobs
            SET status = 'processing', attempts = attempts + 1
            WHERE id IN (
                SELECT id FROM jobs
                WHERE status = 'pending' AND scheduled_at <= now()
                ORDER BY scheduled_at
                LIMIT 10
                FOR UPDATE SKIP LOCKED
            )
            RETURNING id, type, payload, attempts;
            """,
            transaction: transaction)).ToList();

        foreach (var job in jobs)
        {
            try
            {
                await using var scope = scopeFactory.CreateAsyncScope();

                var handler = scope.ServiceProvider
                    .GetRequiredKeyedService<IJobHandler>(job.Type);

                await handler.HandleAsync(job.Payload, ct);

                await connection.ExecuteAsync(
                    """
                    UPDATE jobs
                    SET status = 'completed', completed_at = now()
                    WHERE id = @Id;
                    """,
                    new { job.Id },
                    transaction);
            }
            catch (Exception ex) when (ex is not OperationCanceledException)
            {
                // One failing job must not roll back the rest of the batch
                logger.LogWarning(ex, "Job {JobId} failed on attempt {Attempt}", job.Id, job.Attempts);

                await ScheduleRetryAsync(connection, transaction, job.Id);
            }
        }

        await transaction.CommitAsync(ct);

        return jobs.Count;
    }
}

public sealed record JobRow(long Id, string Type, string Payload, int Attempts);
```

Register it in `Program.cs`:

```csharp
builder.Services.AddNpgsqlDataSource(
    builder.Configuration.GetConnectionString("Database")!);

builder.Services.AddKeyedScoped<IJobHandler, SendEmailHandler>("send-email");

builder.Services.AddHostedService<JobQueueWorker>();
```

The worker claims and processes each batch in **one transaction**.
If the worker crashes mid-batch, the transaction never commits, the row locks are released when the connection closes, and the jobs return to `pending` (the status update was never committed).
A crashed worker never leaves jobs stuck in `processing`, so you don't need a visibility timeout or a manual requeue step.
The whole batch runs again, including jobs whose handler had already finished, so handlers must be idempotent.

That's the transactional handoff a broker can't easily offer.
Enqueueing works the same way: insert the job row in the same transaction as your business data, and you've implemented the [**outbox pattern**](https://milanjovanovic.tech/blog/implementing-the-outbox-pattern).

The keyed-services dispatch keeps handlers pluggable, and the scope-per-job means each handler gets its own DbContext and dependencies.

## Retries and Poison Jobs

The claim increments `attempts`, and the worker's `catch` block reschedules a failed job with backoff in the same transaction, so the increment commits with it.
`ScheduleRetryAsync` goes in the worker class:

```csharp
private static Task ScheduleRetryAsync(
    NpgsqlConnection connection, NpgsqlTransaction transaction, long jobId) =>
    connection.ExecuteAsync(
        """
        UPDATE jobs
        SET status = CASE WHEN attempts >= 5 THEN 'failed' ELSE 'pending' END,
            scheduled_at = now() + make_interval(secs => power(2, attempts))
        WHERE id = @Id;
        """,
        new { Id = jobId },
        transaction);
```

Exponential backoff, capped at 5 attempts, after which the job lands in `failed` for manual inspection.
That `failed` status is your dead-letter queue, and the same retry and backoff principles from broker-based messaging apply here unchanged.

The per-job `catch` matters.
Without it, one throwing handler rolls back the whole batch, including the `attempts` increment, so the poison job never reaches the limit and drags the other jobs in its batch back to `pending` on every retry.

A process crash has the same blind spot.
A job that kills the worker (out of memory, stack overflow) rolls back its own increment and is retried forever.
If that risk matters, commit the claim first and use the lease approach from the next section.

## Keeping It Fast

Three operational rules keep a SKIP LOCKED queue healthy:

- **Delete or archive completed rows.** The partial index keeps dequeues fast, but table bloat still costs you. A nightly `DELETE FROM jobs WHERE status = 'completed' AND completed_at < now() - interval '7 days'` is fine; at serious volume, use [**table partitioning**](https://milanjovanovic.tech/blog/postgresql-table-partitioning-dotnet) and drop old partitions instead.
- **Keep transactions short.** Long-running handlers hold row locks and a connection for the whole batch. If a job takes minutes, claim it, commit the claim, and use a lease timestamp with a reaper query for crashed workers.
- **Batch size tunes throughput vs. fairness.** Bigger batches mean fewer round trips; smaller batches spread work across workers more evenly. Start with 10 and measure.

With the partial index in place, the queue mechanics are cheap.
In a local run of this sample (PostgreSQL 18 in Docker on a development machine, 50,000 jobs, no-op handlers, batches of 10), one worker processed about 4,800 jobs per second and eight concurrent workers about 12,500.
Real handlers do I/O and will set a lower ceiling, so measure with your own workload.

## When to Use a Real Broker Instead

A jobs table is the wrong tool in four cases:

- **Fan-out.** One event consumed by many independent subscribers is publish-subscribe, and a jobs table doesn't model it well.
- **Cross-service messaging.** Sharing a queue table between services couples them at the database. That's what [**RabbitMQ**](https://milanjovanovic.tech/blog/rabbitmq-dotnet-beginners-guide) and friends are for.
- **Streaming and replay.** If you need to re-read history, you want a log like Kafka, not a queue.
- **Six-figure messages per second.** Postgres will run out of headroom before a dedicated broker does.

For background jobs inside a single application, none of those usually apply.
And if you'd rather not maintain the polling loop yourself, Hangfire's PostgreSQL storage also dequeues with `FOR UPDATE SKIP LOCKED`, but it stamps a fetched-at time and relies on an invisibility timeout instead of holding one long transaction.
Quartz is different: its ADO.NET job store coordinates scheduler instances through `SELECT ... FOR UPDATE` row locks on its `QRTZ_LOCKS` table.
I compared the options in **background jobs in .NET**.

## Summary

`FOR UPDATE SKIP LOCKED` gives you a competing-consumer queue in the database you already run:

- The **partial index** on pending rows keeps dequeues fast.
- The **claim-and-process-in-one-transaction** pattern returns a crashed worker's jobs to the queue with no extra machinery, as long as handlers are idempotent.
- Retries are a per-job `catch` plus an `UPDATE` with backoff; the `failed` status is your dead-letter queue.
- Enqueue in the same transaction as your business writes and you get outbox semantics for free.

Start with the database queue, and move to a broker when you hit fan-out, cross-service, or throughput limits.

## Frequently asked questions

### What does FOR UPDATE SKIP LOCKED do in PostgreSQL?

FOR UPDATE locks the selected rows so other transactions cannot modify them. SKIP LOCKED makes the query skip rows that are already locked instead of waiting, so multiple workers can each grab different rows from the same table without blocking each other.

### Is a PostgreSQL queue as fast as RabbitMQ?

No, a dedicated broker will push more messages per second. But a well-indexed SKIP LOCKED queue can still process thousands of short jobs per second, which is more than most applications need.

### How do multiple workers avoid processing the same job twice?

Each worker selects pending rows with FOR UPDATE SKIP LOCKED inside a transaction. The row lock guarantees only one worker holds a given job, and SKIP LOCKED means other workers take the next unlocked rows.

### What happens to a job if the worker crashes?

If the worker processes the job inside the same transaction that claimed it, a crash rolls the transaction back and the row lock is released. The job becomes visible again and another worker picks it up.

### When should I move from a PostgreSQL queue to a real message broker?

When you need fan-out to multiple consumers, cross-service messaging, very high throughput, or streaming semantics. For single-application background jobs, the database queue is usually enough.
