Context & Why
Every growing backend hits the same wall: an HTTP request triggers work that takes too long to finish inline. Sending welcome emails, generating PDF invoices, or calling flaky third-party webhooks inside an API handler makes your endpoints slow and brittle.
The usual reflex is to spin up Redis, RabbitMQ, or Kafka. Dedicated brokers shine at massive scale, but adding one early introduces two headaches you probably do not need yet:
- Operational overhead: You now have another stateful service to secure, back up, upgrade, and monitor.
- The dual-write problem: Suppose your code saves an order to PostgreSQL and then pushes a job to Redis. A crash between those two calls leaves you with an order that never sends an email—or a job pointing to a rolled-back transaction.
Polling a database table with SELECT * FROM jobs WHERE status = 'pending' LIMIT 1 seems like an easy way out. It breaks the moment you start a second Go worker. Both workers read the same row before either updates it, causing duplicate runs and race conditions.
PostgreSQL solves both issues natively with FOR UPDATE SKIP LOCKED. When a worker queries for the next job inside a transaction, PostgreSQL locks that row and tells concurrent workers to skip it instead of waiting.
Each worker claims a distinct job atomically. Better yet, because the queue lives in your primary database, you enqueue jobs in the same transaction as your business data. For workloads under roughly 1,000 jobs per second, this keeps your stack lean—one database to back up, zero dual-write bugs, and sub-5ms job claims.
Installation
You need Go 1.22 or newer and a running PostgreSQL instance (version 12+ supports SKIP LOCKED, though 15 or 16 is ideal). If you do not have PostgreSQL installed locally, boot one in Docker:
docker run -d \
--name pg-queue \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=secret \
-e POSTGRES_DB=jobqueue \
-p 5432:5432 \
postgres:16-alpine
With Postgres running, create a new Go module and install pgx for connection pooling and transaction support:
mkdir go-pg-queue && cd go-pg-queue
go mod init example.com/pgqueue
go get github.com/jackc/pgx/v5/pgxpool
Configuration
1. Designing the Jobs Table and Partial Index
Connect to jobqueue and create the jobs table. Alongside the JSON payload, you want columns for retry counts, delayed scheduling, and tracking when a worker claimed the row.
CREATE TABLE jobs (
id BIGSERIAL PRIMARY KEY,
job_type TEXT NOT NULL,
payload JSONB NOT NULL DEFAULT '{}',
status TEXT NOT NULL DEFAULT 'pending',
attempts INT NOT NULL DEFAULT 0,
max_attempts INT NOT NULL DEFAULT 3,
run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
locked_at TIMESTAMPTZ,
last_error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_jobs_pending_run_at
ON jobs (run_at, id)
WHERE status = 'pending';
That partial index (WHERE status = 'pending') does the heavy lifting. Even if your table grows to 5 million completed rows, the index only tracks the 200 jobs currently waiting to run. Claim queries stay fast without constant table scans.
2. Enqueuing Jobs Transactionally
Putting the queue in PostgreSQL lets your handlers insert a job inside the exact same transaction as an order or user signup. Below is a helper in main.go built around an interface that both *pgxpool.Pool and pgx.Tx satisfy:
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
type DBTX interface {
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
type Job struct {
ID int64
JobType string
Payload json.RawMessage
Attempts int
MaxAttempts int
}
func EnqueueJob(ctx context.Context, db DBTX, jobType string, payload any) error {
data, err := json.Marshal(payload)
if err != nil {
return err
}
_, err = db.Exec(ctx,
`INSERT INTO jobs (job_type, payload) VALUES ($1, $2)`,
jobType, data,
)
return err
}
3. Claiming and Processing Jobs with SKIP LOCKED
Next comes the worker loop. Notice the two-step claim pattern: lock one row with FOR UPDATE SKIP LOCKED, mark it processing, and commit right away. Never hold a database transaction open while sending an email or calling an external API. Long transactions tie up pool connections and block PostgreSQL VACUUM from cleaning up dead tuples.
func claimNextJob(ctx context.Context, pool *pgxpool.Pool) (*Job, error) {
tx, err := pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
var j Job
err = tx.QueryRow(ctx, `
SELECT id, job_type, payload, attempts, max_attempts
FROM jobs
WHERE status = 'pending' AND run_at <= NOW()
ORDER BY run_at ASC, id ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
`).Scan(&j.ID, &j.JobType, &j.Payload, &j.Attempts, &j.MaxAttempts)
if err == pgx.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
_, err = tx.Exec(ctx, `
UPDATE jobs
SET status = 'processing', locked_at = NOW(), attempts = attempts + 1
WHERE id = $1
`, j.ID)
if err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
j.Attempts++
return &j, nil
}
After processJob returns, the worker either marks the row completed or pushes run_at forward using quadratic backoff—5 seconds after attempt 1, then 20 seconds after attempt 2. Once attempt 3 fails, the job moves to failed for manual inspection.
func finishJob(ctx context.Context, pool *pgxpool.Pool, job *Job, execErr error) {
if execErr == nil {
_, err := pool.Exec(ctx,
`UPDATE jobs SET status = 'completed', locked_at = NULL WHERE id = $1`,
job.ID,
)
if err != nil {
log.Printf("failed to mark job %d completed: %v", job.ID, err)
}
return
}
if job.Attempts >= job.MaxAttempts {
_, err := pool.Exec(ctx,
`UPDATE jobs SET status = 'failed', last_error = $2, locked_at = NULL WHERE id = $1`,
job.ID, execErr.Error(),
)
if err != nil {
log.Printf("failed to mark job %d failed: %v", job.ID, err)
}
return
}
backoff := time.Duration(job.Attempts*job.Attempts) * 5 * time.Second
_, err := pool.Exec(ctx,
`UPDATE jobs SET status = 'pending', run_at = NOW() + $2::interval, last_error = $3, locked_at = NULL WHERE id = $1`,
job.ID, fmt.Sprintf("%d seconds", int(backoff.Seconds())), execErr.Error(),
)
if err != nil {
log.Printf("failed to reschedule job %d: %v", job.ID, err)
}
}
Wire those helpers into a polling loop with graceful shutdown. The 500ms idle sleep keeps database CPU quiet when the queue is empty, and signal.NotifyContext ensures an in-flight job finishes and commits its final status before the process exits:
func processJob(ctx context.Context, job *Job) error {
log.Printf("processing job %d (%s): %s", job.ID, job.JobType, string(job.Payload))
time.Sleep(500 * time.Millisecond) // simulate work
return nil
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
dsn := "postgres://postgres:secret@localhost:5432/jobqueue?sslmode=disable"
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
log.Fatal(err)
}
defer pool.Close()
log.Println("worker started")
for {
select {
case <-ctx.Done():
log.Println("shutting down gracefully")
return
default:
}
job, err := claimNextJob(ctx, pool)
if err != nil {
log.Printf("claim error: %v", err)
time.Sleep(time.Second)
continue
}
if job == nil {
time.Sleep(500 * time.Millisecond)
continue
}
err = processJob(ctx, job)
finishJob(context.Background(), pool, job, err)
}
}
4. Recovering from Crashed Workers
What if a container gets OOM-killed mid-job? Because the claim transaction already committed, that row stays stuck in processing. Run a cleanup query every 60 seconds to return stale jobs to pending once they exceed your maximum job timeout (5 minutes here):
UPDATE jobs
SET status = 'pending', locked_at = NULL
WHERE status = 'processing'
AND locked_at < NOW() - INTERVAL '5 minutes';
Verification & Monitoring
To test concurrency, open two terminal windows and start a worker in each:
go run main.go
In a third terminal, seed 10 test jobs directly via psql:
docker exec -it pg-queue psql -U postgres -d jobqueue -c "
INSERT INTO jobs (job_type, payload)
SELECT 'send_email', jsonb_build_object('user_id', g)
FROM generate_series(1, 10) AS g;"
Watch both worker logs. IDs 1 through 10 split cleanly across the two processes with zero overlap—each job is claimed and processed once under normal execution, while crash recovery guarantees at-least-once delivery if a worker dies mid-flight.
Day-to-day observability takes just two SQL queries, no extra dashboards required:
-- Check queue depth and job states
SELECT status, COUNT(*) AS total
FROM jobs
GROUP BY status;
-- Inspect recent failures
SELECT id, job_type, attempts, last_error, created_at
FROM jobs
WHERE status = 'failed'
ORDER BY created_at DESC
LIMIT 20;
Once you cross several thousand jobs per second or need sub-millisecond pub/sub fan-out, reach for a dedicated broker. Until then, Go and PostgreSQL SKIP LOCKED cut out an entire layer of infrastructure while keeping your data and background jobs strictly consistent.

