Skip to content

No. 37Backend8 min read2,184 words

Background jobs and queues for web apps: a practical guide

A practical guide to background jobs for web apps: what to move off the request path, Postgres vs Redis queues, and workers that survive crashes and retries.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01Move work to a background job when the user does not need its result before you send the response: emails, PDFs, image processing, third-party API calls and fan-out notifications.
  2. 02If you already run Postgres and job volume is modest, a table queue using SELECT ... FOR UPDATE SKIP LOCKED is less infrastructure and lets you enqueue jobs in the same transaction as your business data.
  3. 03Choose Redis with BullMQ, or a managed queue like SQS, when you need high throughput, very low pickup latency, or built-in rate limiting and scheduling.
  4. 04Every job runs at least once, not exactly once: make handlers idempotent, retry transient failures with exponential backoff and jitter, and send repeated failures to a dead-letter state.
  5. 05Recover jobs from crashed workers with a lease or visibility timeout, and alert on queue depth and the age of the oldest pending job.
On this page ยท 08

Background jobs move slow or unreliable work, such as sending email, generating PDFs or calling third-party APIs, out of the HTTP request and into a separate worker that can retry it safely. If you already run Postgres, start with a table-backed queue using FOR UPDATE SKIP LOCKED; reach for Redis with BullMQ or a managed queue when volume or latency demands it. Whatever you pick, make every job idempotent, cap retries, and watch queue depth.

The moment your app sends an email, resizes an image or calls a slow third-party API inside a request handler, you have a problem waiting to happen. The user stares at a spinner, your server holds a connection open it did not need to, and one flaky API turns into a wall of timeout errors. Background jobs are the fix: do the slow thing later, off the request path, where it can fail and retry without anyone watching.

What belongs in a background job

Not everything needs a queue. The honest test: does the user need the result before you can send the HTTP response? If yes, do it inline. If no, push it to a job.

Work that almost always belongs in the background:

  • Email and SMS. Provider calls are slow and occasionally fail.
  • Files and media. PDFs, thumbnails, video transcodes, virus scans on uploaded files.
  • Third-party APIs you do not control. CRM sync, accounting exports, AI calls, payment reconciliation.
  • Incoming webhooks. Verify, store and return fast, then process in a worker, as we explain in webhooks done right.
  • Fan-out. Notifying every member of a workspace about a change.
  • Scheduled work. Nightly reports, trial-expiry emails, data cleanup.
  • Anything you want retried automatically on failure.

Work that should usually stay inline: validating input, writing the row the user just submitted, and returning the ID they need next. Do not background work that the next page load depends on, or you will spend the week explaining race conditions to yourself. If the result matters but takes a while, return 202 Accepted with a job ID the client can poll, or push the result over a realtime channel when it finishes.

The lightweight option: after()

For small fire-and-forget tasks, such as logging or analytics, Next.js has after(), which runs a callback once the response has been sent. It is not a queue: there is no retry, no persistence, and if the process dies the work is gone. Use it for things you can afford to lose occasionally, and a real queue for everything else.

How a job queue works

Every queue, whatever the technology, has the same moving parts:

  1. Producer. Your request handler adds a job: a type, a payload, and options like delay and maximum attempts.
  2. Storage. The queue holds jobs durably: a Postgres table, Redis, or a managed service.
  3. Worker. A separate process claims a job, runs the handler, and marks it done.
  4. Lease. While a worker holds a job, nobody else can take it. If the worker dies, the lease expires and the job becomes available again. SQS calls this the visibility timeout.
  5. Retries and dead letters. Failures are retried with backoff, and jobs that keep failing are parked for a human.

The lease is the part hand-rolled queues most often forget, and it is why a job can always run more than once: the worker might finish the work and crash before it records success.

Start with your database: Postgres as a queue

The default reflex is to reach for Redis and BullMQ. Sometimes that is right. But if you already run Postgres and your job volume is modest, a database-backed queue is less infrastructure, easy to inspect with plain SQL, and gives you one property Redis cannot: transactional enqueue.

The feature that makes Postgres a decent queue is SELECT ... FOR UPDATE SKIP LOCKED. It lets several workers each grab a different row without waiting on rows another worker already locked.

The table is unremarkable, which is the point:

CREATE TABLE jobs (
  id           uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  type         text NOT NULL,
  payload      jsonb NOT NULL,
  status       text NOT NULL DEFAULT 'pending',  -- pending | running | dead
  attempts     int  NOT NULL DEFAULT 0,
  max_attempts int  NOT NULL DEFAULT 5,
  run_after    timestamptz NOT NULL DEFAULT now(),
  locked_until timestamptz,
  last_error   text,
  created_at   timestamptz NOT NULL DEFAULT now()
);
 
-- Partial index: the claim query only ever looks at pending jobs.
CREATE INDEX jobs_pending_idx ON jobs (run_after) WHERE status = 'pending';

And a minimal but real worker in TypeScript with the pg driver:

import { Pool } from "pg";
 
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
 
type Job = { id: string; type: string; payload: unknown; attempts: number; max_attempts: number };
type Handlers = Record<string, (payload: any) => Promise<void>>;
 
async function claimJob(): Promise<Job | null> {
  const { rows } = await pool.query<Job>(
    `UPDATE jobs
        SET status = 'running',
            attempts = attempts + 1,
            locked_until = now() + interval '5 minutes'
      WHERE id = (
        SELECT id FROM jobs
         WHERE status = 'pending' AND run_after <= now()
         ORDER BY run_after
         FOR UPDATE SKIP LOCKED
         LIMIT 1
      )
      RETURNING id, type, payload, attempts, max_attempts`,
  );
  return rows[0] ?? null;
}
 
export async function runOnce(handlers: Handlers): Promise<boolean> {
  const job = await claimJob();
  if (!job) return false;
 
  try {
    const handler = handlers[job.type];
    if (!handler) throw new Error(`No handler for job type ${job.type}`);
    await handler(job.payload);
    await pool.query(`DELETE FROM jobs WHERE id = $1`, [job.id]);
  } catch (err) {
    const dead = job.attempts >= job.max_attempts;
    // Exponential backoff with full jitter, capped at one hour
    const delaySeconds = Math.random() * Math.min(2 ** job.attempts * 10, 3600);
    await pool.query(
      `UPDATE jobs
          SET status = $2, last_error = $3, locked_until = NULL,
              run_after = now() + make_interval(secs => $4)
        WHERE id = $1`,
      [job.id, dead ? "dead" : "pending", String(err), delaySeconds],
    );
  }
  return true;
}

Because attempts is incremented when the job is claimed, a job that crashes its worker still counts the attempt. Add a sweeper that runs every minute and returns stuck jobs to the queue:

UPDATE jobs SET status = 'pending', locked_until = NULL
WHERE status = 'running' AND locked_until < now();

Set the lease longer than your slowest job, or extend it periodically from long-running handlers.

Transactional enqueue is the real win

With a Postgres queue you can create the job in the same transaction that writes your business data:

BEGIN;
INSERT INTO orders (id, customer_id, total_cents) VALUES ($1, $2, $3);
INSERT INTO jobs (type, payload) VALUES ('send_order_confirmation', jsonb_build_object('orderId', $1::uuid));
COMMIT;

If the transaction rolls back, the job never existed. With a separate queue, you either enqueue before commit (and send confirmations for orders that never saved) or after commit (and lose the job if the process dies in between). The standard fix for that gap is the transactional outbox pattern, which is this exact table under a different name, with a relay that forwards rows to the external queue.

You do not have to write all of this yourself. pg-boss for Node and Graphile Worker package the same pattern with scheduling, retries and cleanup, and they are what we usually reach for before writing a custom loop.

When Redis or a managed queue earns its keep

Postgres queues have limits. Polling adds latency between enqueue and pickup, high churn creates dead rows that autovacuum has to clean up, and very high throughput puts queue load on your primary database. When you hit those limits, or you need features like per-queue rate limiting, job priorities, repeatable jobs and a dashboard, a dedicated queue is the better tool.

BullMQ on Redis is the common choice in Node. Workers block on Redis and wake almost instantly when work arrives, and the library ships with retries, delays, rate limiting and repeatable jobs. It pairs naturally with Redis you may already run for caching, or for pub/sub in a real-time app.

import { Queue, Worker } from "bullmq";
 
const connection = { url: process.env.REDIS_URL! };
 
export const emailQueue = new Queue("email", { connection });
 
// Enqueue from your route handler or server action.
// jobId makes the enqueue idempotent: adding a job whose ID still exists
// in the queue (including kept completed jobs) is ignored.
await emailQueue.add(
  "welcome",
  { userId: user.id },
  {
    jobId: `welcome-${user.id}`,
    attempts: 5,
    backoff: { type: "exponential", delay: 1000 },
    removeOnComplete: 1000,
    removeOnFail: 5000,
  },
);
 
// The worker runs in a separate long-lived process
new Worker(
  "email",
  async (job) => {
    await sendWelcomeEmail(job.data.userId);
  },
  { connection, concurrency: 10 },
);

The cost is that Redis becomes stateful infrastructure you have to back up, monitor and reason about. Configure Redis persistence and set the eviction policy to noeviction on the instance holding the queue, or you can lose in-flight jobs. That is a fine trade at scale and a needless one when you send a few dozen emails an hour.

Comparing your options

OptionInfrastructureTransactional enqueuePickup latencyGood for
Postgres table (pg-boss, Graphile Worker)None extraYesPolling interval, or near-instant with LISTEN/NOTIFYMost early and mid-stage apps
Redis with BullMQRedis with persistenceNoNear-instantHigh volume, rate-limited and scheduled queues
Managed queue (SQS and similar)Cloud serviceNo, use an outboxLowServerless, cross-service messaging
Durable workflow engine (Temporal and similar)Service or cloudNoLowLong, multi-step processes with state
Next.js after()NoneNoImmediateFire-and-forget logging and analytics only

Long, multi-step processes

When a "job" is really a process (charge the card, wait for a webhook, provision an account, email the customer, wait three days, send a follow-up) individual jobs chained together get fragile. Durable workflow engines such as Temporal persist each step and resume where they left off after crashes. They are worth the extra concept count for genuinely long-running business processes, and overkill for sending emails.

Serverless deployments

On platforms where functions are short-lived, you cannot run a permanent worker loop. Two practical options: a scheduled function that drains a database queue in batches every minute, or a managed queue or workflow service that calls an HTTP endpoint per job. The job logic stays the same; only the thing that wakes the worker changes. Make sure each job fits comfortably inside the function's maximum duration, and split large jobs into smaller ones if not.

The rules that keep background jobs out of trouble

Most background job pain comes from skipping one of these.

Make handlers idempotent. A job can and will run twice. The worker might crash after sending the email but before deleting the row. Design every handler so running it again is harmless: charge a card with an idempotency key, record that you sent an email and check before sending, use upserts instead of inserts. Assume at-least-once delivery, never exactly-once.

Pass IDs, not objects. Put { "orderId": "..." } in the payload and load the current record in the handler. A serialised copy of the order goes stale between enqueue and execution, and may hold personal data you now have sitting in a queue.

Retry transient failures, stop on permanent ones. Network blips and rate limits should retry with exponential backoff and jitter; AWS's guide to backoff with jitter explains why the randomness matters. A malformed payload or a deleted user will never succeed, so fail it immediately into a dead-letter state where a human can look. A job that retries forever is a slow-motion incident.

Respect your dependencies. Ten workers each calling an email API in parallel can exceed its limits. Use queue-level concurrency or rate limiting per provider.

Shut down gracefully. On deploy, stop claiming new jobs and let running ones finish within a timeout, so deploys do not create a burst of half-finished work.

Monitoring a job queue

The most useful metrics are simple:

  • Queue depth: how many jobs are pending, per queue.
  • Age of the oldest pending job: the clearest single signal that workers are down or too slow.
  • Failure and dead-letter rate: a jump usually means a dependency broke or a deploy introduced a bug.
  • Job duration: catches handlers that slowly get heavier as data grows.

Alert on oldest-job age and on anything landing in the dead-letter state. Log the job ID and type with every line a handler writes, so you can trace one job end to end. If you are setting this up from scratch, our observability basics guide covers the logging and alerting side.

Make background work the boring part

Start with the simplest thing that works. If you already run Postgres, a SKIP LOCKED queue, or a library built on it, will carry you a long way and gives you transactional enqueue for free. Reach for Redis, a managed queue or a workflow engine when volume, latency or process length actually demands it, not on reflex. Whatever you choose, make handlers idempotent, use leases, cap retries and watch the oldest job. Get those right and background work becomes the boring, reliable part of your system instead of the part that pages you at 2am.

Queues and workers are a core part of our API and backend engineering work. If you have a queue that keeps falling over, or you are deciding what to build on, tell us about it.

FAQ ยท 05 questions

Frequently asked questions

What is a background job in a web app?

A background job is work your application does outside the HTTP request that triggered it. The request handler records what needs doing on a queue and responds immediately, and a separate worker process picks the job up and runs it. This keeps pages fast and lets slow or flaky work retry without the user waiting.

Can I use Postgres as a job queue?

Yes, and for many apps it is the simplest good option. Postgres supports SELECT ... FOR UPDATE SKIP LOCKED, which lets many workers claim different rows without blocking each other. Libraries like pg-boss and Graphile Worker package this pattern. Move to a dedicated queue when volume, latency or table churn starts to hurt.

BullMQ or a Postgres queue: which should I choose?

Start with Postgres if it is already your database and you value transactional enqueueing and fewer moving parts. Choose BullMQ on Redis when you need very high throughput, near-instant pickup, rate-limited queues or a dashboard out of the box, and you are prepared to run Redis with persistence configured.

How do background jobs work on Vercel or other serverless platforms?

Serverless functions are short-lived, so you cannot run a permanent worker loop. Use a managed queue or workflow service that calls an HTTP endpoint per job, or a scheduled cron function that drains a database queue in batches. For small fire-and-forget tasks, Next.js after() runs code once the response is sent, but it has no retries.

What is a dead-letter queue?

A dead-letter queue holds jobs that failed too many times to keep retrying. Instead of retrying forever or silently dropping them, the system parks them where an engineer can inspect the error, fix the cause and replay them. Every production queue should have one, plus an alert when jobs land in it.

Related service

API & Backend Engineering

Secure, well-documented APIs that scale.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts