← All articles
Backend & Cloud

How a Node.js app moves slow work out of the request

Background jobs in Node.js: why an email sent after the response gets lost, and how a PostgreSQL queue with SKIP LOCKED keeps it safe.

When your Buy handler sends the confirmation email before it responds, every buyer waits on the email service, and a failing provider fails the purchase. Moving the email into background jobs in Node.js removes the wait, but only if the job survives a deploy, a crash or a restart. This article shows how an email sent after the response gets lost, how a PostgreSQL table keeps it, and when another queue fits better.

An email sent after the response, and a deploy restart

The quick fix is to respond first and call sendEmail() without await. This script does that, then sends itself SIGTERM half a second later, the way a deploy restart would. The fake sendEmail() takes two seconds, like a slow SMTP call.

// 1-fire-and-forget-sigterm.mjs
// Respond first, then send the email without awaiting it. Then the process gets SIGTERM (a deploy restart).
import http from 'node:http';
const sendEmail = (to) => new Promise((resolve) => setTimeout(() => { console.log(`email sent to ${to}`); resolve(); }, 2000)); // fake 2 s SMTP call

const server = http.createServer((req, res) => {
  res.end('ok\n');
  sendEmail('a@example.com'); // fire and forget
  console.log('responded, email pending');
});
server.listen(0, async () => {
  const { port } = server.address();
  const r = await fetch(`http://127.0.0.1:${port}/signup`);
  console.log('client got:', (await r.text()).trim());
  setTimeout(() => process.kill(process.pid, 'SIGTERM'), 500); // deploy restart 0.5 s later
});
process.on('exit', (code) => console.log('exit event, code', code));

Before you run it, predict three things. What does the client receive? Does email sent to a@example.com appear? And what is the exit status?

node 1-fire-and-forget-sigterm.mjs; echo "exit status $?"
responded, email pending
client got: ok
exit status 143

These demos ran on Node.js 22.17.0 on macOS.

The client got ok, so the buyer sees a finished order. The email line never appears, and neither does the line from the 'exit' listener. With no SIGTERM listener, Node.js exits at once with code 128 plus the signal number, which is 143 for SIGTERM (signal events). The pending timer and its promise die with the process.

An 'exit' listener can’t rescue the email either. The Node.js docs say these listeners “must only perform synchronous operations”, and work still in the queue is abandoned.

Rule: An un-awaited promise lives only as long as the process that created it.

A graceful shutdown that still loses the email

A shutdown handler you often see closes the server, then exits in the callback.

// 2b-graceful-exit.mjs (excerpt): the SIGTERM handler
process.on('SIGTERM', () => { console.log('SIGTERM'); server.close(() => { console.log('server closed, exiting'); process.exit(0); }); });
responded, email pending
client got: ok
SIGTERM
server closed, exiting
exit status 0

The email is lost again, and this time the exit status is 0, so the shutdown looks clean in every log. The response had already finished, so server.close() had no connection to wait for and called back at once. Then process.exit() ends the process “even if there are still asynchronous operations pending” (process docs).

If you remove process.exit(0) and only close the server, the pending timer keeps the process alive. That version (2-graceful-close.mjs) sent the email and then exited with 0. But the supervisor sets a limit. systemd sends SIGTERM, waits TimeoutStopSec (90 seconds by default), then sends SIGKILL (systemd.kill, systemd-system.conf). Docker sends SIGKILL after 10 seconds (docker container stop).

A failed email that takes down another buyer’s request

A graceful shutdown helps on a planned restart. It does nothing when the email itself fails. This server answers /signup at once and sends an email that fails after 200 ms, with no .catch(). The /report route takes one second, so it stands for any other request in flight.

// 3b-server.mjs
// Server only. /signup responds, then fires a failing email without .catch(). /report takes 1 s.
import http from 'node:http';
const sendEmail = (to) => new Promise((_, reject) => setTimeout(() => reject(new Error(`SMTP 421 for ${to}`)), 200));
http.createServer((req, res) => {
  if (req.url === '/signup') { res.end('ok\n'); sendEmail('a@example.com'); return; }
  setTimeout(() => res.end('report done\n'), 1000);
}).listen(3457, () => console.log('listening'));

The script 3b-run.sh starts the server, requests /report, and requests /signup 0.1 seconds later. Predict what the /report client receives.

[client signup] ok
[server] Error: SMTP 421 for a@example.com
[client report] curl: (52) Empty reply from server

The output is trimmed to three lines; the stack trace is cut. The signup got ok. When its email promise rejected, nothing handled it, so the whole process crashed, and the /report client got an empty reply. Since Node.js 15, the default --unhandled-rejections mode is throw, which turns an unhandled rejection into an uncaught exception (CLI docs, Node.js 15 release).

An async call without await still runs on the main thread

“In the background” sounds like another thread. This script calls an async function that spends 1.5 seconds of CPU building a PDF, and does not await it. A timer is due at 10 ms. Predict when it fires.

// 6-async-not-background.mjs
// An async function with CPU work still runs on the one main thread.
const start = Date.now();
setTimeout(() => console.log(`timer due at 10 ms fired at ${Date.now() - start} ms`), 10);
async function buildEmailPdf() { const end = Date.now() + 1500; while (Date.now() < end); return 'pdf'; } // 1.5 s CPU
buildEmailPdf(); // not awaited, "in the background"
console.log(`buildEmailPdf() returned at ${Date.now() - start} ms`);
buildEmailPdf() returned at 1500 ms
timer due at 10 ms fired at 1502 ms

An async function runs on the caller’s thread until its first await, and this one has none. So the call blocked the event loop for 1.5 seconds, and every other request would wait with the timer. How the event loop runs your code explains why the timer cannot fire sooner. An un-awaited call means “after the response”, not “somewhere else”.

What a queue for background jobs in Node.js does underneath

All three failures happen because the work exists only inside the web process. A job is a record of work to do, such as “send the confirmation for order 42”. A job queue stores jobs outside the web process, and a worker is a separate process that takes jobs from the queue and runs them.

Node.js has no durable job queue built in. Its API index has timers, worker threads, child processes and cluster, and all of them live and die with a process. So the queue needs a store. If you already run PostgreSQL, that store can be a table, and three properties make it work.

The job is a row in a table

-- 01-schema.sql (excerpt)
CREATE TABLE jobs (
  id         bigserial PRIMARY KEY,
  kind       text        NOT NULL,
  payload    jsonb       NOT NULL,
  run_at     timestamptz NOT NULL DEFAULT now(),
  attempts   int         NOT NULL DEFAULT 0,
  locked_at  timestamptz
);
INSERT INTO jobs (kind, payload) VALUES
  ('send_email', '{"to":"a@example.com"}'),
  ('send_email', '{"to":"b@example.com"}'),
  ('send_email', '{"to":"c@example.com"}');

Once the insert commits, the job survives a restart of the web app, of the worker, or of the whole server. It is a committed row like any other. The run_at column lets a job wait for a later time, which is how retries get delayed.

SKIP LOCKED gives each job to one worker

Two workers must never send the same email at the same moment. FOR UPDATE locks the rows a SELECT returns until the transaction ends. Each worker runs this file.

-- 02-worker.sql
BEGIN;
SELECT id, payload->>'to' AS recipient, pg_backend_pid() AS worker_pid
FROM jobs
WHERE run_at <= now()
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
SELECT pg_sleep(3);  -- pretend to send the email while holding the row lock
COMMIT;

Worker A starts, and worker B starts 0.3 seconds later. Predict which job each one gets.

[A]   1 | a@example.com |        124
[B]   2 | b@example.com |        131

The output is trimmed to the result rows. Worker A locked row 1, so worker B skipped it and took row 2 at once. SKIP LOCKED tells a locking SELECT to skip rows another transaction has locked, instead of waiting for them. PostgreSQL added it in 9.5, released on 2016-01-07.

Without SKIP LOCKED (03-worker-noskip.sql), worker B waited for A to commit and then got row 1. In that run, B took 5.6 seconds instead of 3.1. The SELECT docs say SKIP LOCKED is “not suitable for general purpose work”, but fits “a queue-like table” with many consumers.

The job commits or rolls back with the order

Because the queue is a table in the same database as your orders, you can insert the order and its job in one transaction. This script also calls pg_notify(), so a listening worker hears about the job.

// 04-tx.mjs (excerpt, logging removed): one order, its job and a NOTIFY in one transaction
async function placeOrder(email, fail) {
  await app.query('BEGIN');
  const { rows: [order] } = await app.query('INSERT INTO orders (email) VALUES ($1) RETURNING id', [email]);
  const { rows: [job] } = await app.query(
    `INSERT INTO jobs (kind, payload) VALUES ('send_email', $1) RETURNING id`,
    [{ to: email, orderId: order.id }]);
  await app.query(`SELECT pg_notify('jobs_ready', $1)`, [String(job.id)]);
  await new Promise((r) => setTimeout(r, 500));
  await app.query(fail ? 'ROLLBACK' : 'COMMIT');
}

The first order rolls back, as if its payment failed, and the second commits. The rolled-back job (id 4) never appeared in the table, and its NOTIFY never reached the listener. The committed job 5 appeared, and the listener printed NOTIFY jobs_ready payload=5. PostgreSQL delivers a NOTIFY only when its transaction commits (NOTIFY docs).

Now suppose the queue lives in Redis, so the order goes to PostgreSQL and the job goes to Redis. A dual write is two writes to two systems with no transaction around both. If you enqueue inside the transaction, a worker can run before the order commits. If you enqueue after the commit, a crash between the two loses the job (Brandur Leach, 2017).

The usual fix for a dual write is a transactional outbox, where you write the message to a table in the same transaction and a relay process publishes it later (microservices.io). A PostgreSQL queue in the same database is its own outbox, because the job row is the message. The River README puts it this way: jobs “are removed if their transaction rolls back”.

Rule: A job in the same database as the order commits or rolls back with the order.

A crashed worker’s job comes back after a timeout

The demo above held the row lock while it pretended to send the email. That keeps a transaction open for as long as the email service takes, and long transactions hurt a queue table (see the vacuum demo below). So a real queue claims the job in a short transaction and records a deadline on the row instead.

-- 09-handrolled.sql (excerpt): claim one job; the UPDATE commits on its own
UPDATE jobs SET attempts = attempts + 1, locked_until = now() + interval '5 minutes'
WHERE id = (
  SELECT id FROM jobs
  WHERE failed_at IS NULL AND run_at <= now() AND (locked_until IS NULL OR locked_until < now())
  ORDER BY run_at LIMIT 1
  FOR UPDATE SKIP LOCKED)
RETURNING id, attempts, locked_until > now() AS claimed;

The locked_until column is a visibility timeout, a deadline that hides a claimed job from other workers. Once it passes, any worker can claim the job again. In the demo, a simulated crash left an expired claim, and the next claim returned the same job with attempt_after_crash 2. The same file retries a failed job after 2^attempts seconds and sets failed_at once the attempts run out.

That file still has no worker loop, graceful shutdown, heartbeats, cleanup or bloat monitoring. Libraries add those parts. pg-boss and Graphile Worker are Node.js libraries that run this kind of queue in PostgreSQL, both built on SKIP LOCKED.

What a PostgreSQL queue costs

Every queue can run a job twice

The visibility timeout has a cost. If the worker sends the email and then crashes before it marks the job done, the claim expires and the job runs again. That is at-least-once delivery, where every job runs one or more times, never zero.

Every option in this article delivers at least once. The pg-boss docs say so and ask you to write handlers “so that running one twice does no harm”. BullMQ, a Node.js job queue library built on Redis, asks for idempotent processors (BullMQ docs), and Graphile Worker says each job “will execute at least once” (Graphile Worker docs).

SQS has “no absolute guarantee” against redelivery, for FIFO queues too (SQS docs).

So the email job needs an idempotency key, a value unique to one operation that lets the receiver ignore a repeat. Resend accepts an Idempotency-Key header and keeps each key for 24 hours. Stripe’s docs describe the same pattern for payments.

The API references of Postmark, SES v2 SendEmail and SendGrid Mail Send do not mention one. With those providers, a crash at the wrong moment still sends a second email.

A busy queue table fills with dead rows

Every finished job is deleted or updated. In PostgreSQL, the old version of the row stays on disk as a dead row version until VACUUM removes it (routine vacuuming). This script inserts 100,000 jobs, deletes all of them, and then runs the claim query on the empty table.

-- 07-churn.sql (excerpt)
CREATE TABLE churn (id bigserial PRIMARY KEY, payload jsonb NOT NULL, run_at timestamptz NOT NULL DEFAULT now())
  WITH (autovacuum_enabled = off);  -- off only to make the dead rows visible in this demo
INSERT INTO churn (payload) SELECT jsonb_build_object('to', 'u' || g || '@example.com') FROM generate_series(1, 100000) g;
DELETE FROM churn WHERE id IN (SELECT id FROM churn ORDER BY id LIMIT 100000);
SELECT n_live_tup, n_dead_tup, pg_size_pretty(pg_relation_size('churn')) AS heap_size FROM pg_stat_user_tables WHERE relname = 'churn';
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF) SELECT id FROM churn ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;

The table has no live rows. Predict how many pages the claim query reads to find nothing.

 n_live_tup | n_dead_tup | heap_size
------------+------------+-----------
          0 |     100000 | 8176 kB

 Limit (actual rows=0.00 loops=1)
   Buffers: shared hit=1571
   ->  LockRows (actual rows=0.00 loops=1)
         ->  Index Scan using churn_pkey on churn (actual rows=0.00 loops=1)
 Execution Time: 13.222 ms

The query read 1,571 pages and took 13 ms to return no row. The index scan still walks the entries of all 100,000 deleted jobs and checks each one in the table. How PostgreSQL plans a query shows how to read these EXPLAIN lines.

After VACUUM churn, the same query took 0.017 ms. These timings come from one run on PostgreSQL 18.7 in Docker, and yours will differ.

In production, autovacuum is on and cleans the table on its own schedule. PostgreSQL 18 added the autovacuum_vacuum_max_threshold setting for when it starts (routine vacuuming). Plain VACUUM does not return space to the operating system. The pg-boss 12.29.0 release notes say autovacuum “never shrinks a btree”, and report a 130 MB index over about 136 kB of live data.

A long transaction stops the cleanup

VACUUM can only remove a row version that no open transaction might still see. In this demo, one session holds a REPEATABLE READ snapshot for eight seconds, like a long report query. Meanwhile another session inserts and deletes 50,000 jobs and runs VACUUM (VERBOSE) churn.

tuples: 0 removed, 50000 remain, 50000 are dead but not yet removable

After the long transaction ended, the next VACUUM printed tuples: 50000 removed. So one forgotten transaction anywhere in the database stops the cleanup of your queue table, and every claim gets slower. pg-boss 12.30.0 calls a server too busy for autovacuum “a primary failure pattern of Postgres-hosted queues”, and it now monitors vacuum by default (release notes). PostgreSQL 17 added transaction_timeout, which ends any transaction that runs too long (17.0 release notes).

Polling, LISTEN/NOTIFY and the lock at commit

A worker has to learn that a job is ready. By default, pg-boss polls the table every 2 seconds, so a new job can wait up to 2 seconds. LISTEN/NOTIFY is PostgreSQL’s built-in message channel. A session runs LISTEN on a channel, and a NOTIFY on that channel wakes it after the sender commits.

Graphile Worker uses LISTEN/NOTIFY and reports a delay “typically under 3ms” (Graphile Worker docs). pg-boss added it as an option in 12.21.0, with polling kept as a backstop.

But a committing transaction that sent a NOTIFY takes a global lock, in src/backend/commands/async.c, so those commits run one at a time. Recall.ai reported outages from this lock under many writers. PostgreSQL 19 only narrows which sessions get woken, and the lock is still there.

How many jobs per second a PostgreSQL queue handles

The Graphile Worker scaling page says the jobs table has “extremely high churn”, and suggests looking elsewhere at “5k+ jobs per second”. Its benchmark reached about 15,600 jobs per second unbatched, with the database and workers on one i9-14900K machine. The page itself notes that a more realistic setup is still to do.

BullMQ now runs the same API on Redis or PostgreSQL. In its own measurement, Redis often handled about 1.5 to 2 times as many jobs per second as PostgreSQL. pg-boss publishes no throughput figures.

Connections are a limit too. pg-boss opens a pool of 10 connections, plus one for LISTEN, and Graphile Worker defaults to 10. PostgreSQL’s max_connections is “typically 100” (connection settings).

The alternatives, and when the choice flips

Each option below either loses work on a restart or delivers at least once. They differ in what survives a restart, whether the job commits with the order, and what you must run beside your app.

Option What it is Survives a restart Commits with the order Extra to run
In-process: fire-and-forget An un-awaited promise in the web process No No Nothing
In-process: worker threads Threads in the web process; Piscina pools them with an in-memory queue No No Nothing
In-process cron A timer in every app process (node-cron, croner) No Not applicable Nothing
systemd timer A unit that starts a command on a calendar Yes, with Persistent=true Not applicable A timer and a service unit
PostgreSQL queue A table and a worker process: hand-rolled, pg-boss or Graphile Worker Yes Yes A worker process
Redis queue BullMQ jobs in Redis lists, sorted sets and Lua scripts Only with AOF persistence No Redis, and a worker process
Message broker RabbitMQ, SQS or Kafka Yes No, so you need an outbox A broker, or a cloud service
Workflow engine Temporal, Inngest, Trigger.dev or DBOS Yes Separate system A server, except DBOS, which is a library

In-process: fire-and-forget is the right choice only when losing the work on a restart costs nothing. The demos above lost the email on SIGTERM and crashed another buyer’s request on a rejection.

In-process: worker threads fit CPU-heavy JavaScript, such as building a PDF. The docs say workers “do not help much with I/O-intensive work”, and an email is I/O. A worker thread’s pending email was also lost on SIGTERM, with exit status 143 (5-worker-sigterm.mjs).

In-process cron runs once per process, not once per app. Two instances of a “send the digest every second” script wrote 6 lines for 3 ticks (7-interval-two-instances.mjs). The node-cron README says it “does not persist state”, and points to durable job queues for retries.

systemd timer is the better choice for scheduled work on one Linux server. Persistent=true runs a missed trigger when the timer starts again, and an already-running unit is not started twice (systemd.timer). The cost is two unit files per task, kept outside your code.

PostgreSQL queue fits when you already run PostgreSQL and stay under a few thousand jobs per second. The libraries differ most after a crash. pg-boss retries a crashed job after 15 minutes by default, or sooner with heartbeats, but Graphile Worker keeps a crashed job locked “for at least 4 hours” (error handling). Graphile Worker also has no dead-letter queue, so failed jobs stay in its table.

Redis queue becomes the right choice when you already run Redis, or need more jobs per second than PostgreSQL gives. BullMQ needs AOF persistence and maxmemory-policy noeviction, and warns that many hosts “do not offer persistence by default” (going to production). With AOF every second, a crash can still lose about one second of jobs. The job is also a dual write with your order.

Message broker fits when several services consume the same messages. Each has a cost for a single app. A RabbitMQ quorum queue keeps 3 replicas by default, and SQS standard queues may deliver twice and out of order. Kafka is a log that keeps events after they are consumed.

Workflow engine fits work with many steps that must resume after a crash, such as a refund that waits days for an answer. Temporal needs its own server and a database, with Elasticsearch recommended for production visibility. A self-hosted Trigger.dev needs PostgreSQL, Redis, ClickHouse, a registry and object storage, with 3 or more vCPUs and 6 GB for its web app alone. Temporal also asks for idempotent activities (Temporal docs), so at-least-once does not go away.

What changed recently

  • BullMQ 6.0 (2026-07-30) added a PostgreSQL backend for PostgreSQL 13 and later (release). Its docs still call Redis “the default and the most battle-tested option”, and they don’t say whether a job can be added inside your own transaction.
  • pg-boss added LISTEN/NOTIFY in 12.21.0 (2026-06-23), vacuum monitoring on by default in 12.30.0 (2026-09-03), and transactional workers in 12.32.0 (2026-09-14) (releases).
  • Rails 8 ships Solid Queue, which uses SKIP LOCKED. Its release notes (November 2024) say it “replaces the need for Redis”. 37signals ran a third of HEY’s jobs on it by 2023-12-18 (37signals).
  • Redis moved to RSALv2 and SSPLv1 with 7.4 on 2024-03-20 (Redis). The Linux Foundation launched the Valkey fork on 2024-03-28 (Linux Foundation), and Redis 8 added AGPLv3 on 2025-05-01 (Redis). BullMQ supports Redis 6.2+, Valkey and Dragonfly.
  • SQS raised the maximum message size to 1 MiB on 2025-08-04 (SQS quotas).

How TinyTickets runs its email jobs with pg-boss

TinyTickets is the invented ticket site in the story. Maya runs it for her friend Leo’s shows on one rented server, with the web app and PostgreSQL side by side. In the story, a festival with 3,000 tickets goes on sale at 10:00, and every buyer arrives in the same minute.

TinyTickets uses a PostgreSQL queue run by pg-boss, in a worker process next to the web app. There is no new service to run, and the email job commits or rolls back with the order. The server has 2 vCPUs and 4 GB of RAM, less than a self-hosted Trigger.dev web app needs on its own. The code below is TypeScript in the shape of the pg-boss demo (05-pgboss.mjs), which ran on pg-boss 12.38.2.

Send the job inside the order transaction

// queue.ts (excerpt)
import pg from 'pg';
import { PgBoss } from 'pg-boss';

export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
export const boss = new PgBoss(process.env.DATABASE_URL!);
boss.on('error', console.error);
// The web app and the worker each call `await boss.start()` once at boot.
// orders.ts (excerpt)
import { pool, boss } from './queue.js';

export async function placeOrder(email: string, showId: number, quantity: number) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const { rows: [order] } = await client.query(
      'INSERT INTO orders (email, show_id, quantity) VALUES ($1, $2, $3) RETURNING id',
      [email, showId, quantity]);
    const db = { executeSql: (text: string, values?: unknown[]) => client.query(text, values) };
    await boss.send('order-email', { orderId: order.id }, { db });
    await client.query('COMMIT');
    return order.id;
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

The db option makes send() run its insert on your client, so “the insert commits or rolls back with your transaction” (pg-boss). Notice that send() returns a job id before the commit. In the demo, a rolled-back send() returned an id for a job that never existed, so don’t log that id as proof that an email is queued.

Retry, then park the job in a dead-letter queue

// worker.ts (excerpt): loadOrder and sendEmail are your own code
import { pool, boss } from './queue.js';

await boss.start();
// getQueue() returns null for a queue that doesn't exist yet
if (!(await boss.getQueue('order-email-dlq'))) await boss.createQueue('order-email-dlq');
if (!(await boss.getQueue('order-email'))) {
  await boss.createQueue('order-email', {
    retryLimit: 5,
    retryDelay: 30,
    retryBackoff: true,
    deadLetter: 'order-email-dlq',
  });
}

await boss.work('order-email', async ([job]) => {
  const { orderId } = job.data as { orderId: number };
  const order = await loadOrder(orderId);
  await sendEmail({
    to: order.email,
    template: 'order-confirmation',
    data: order,
    idempotencyKey: `order-confirmation-${order.id}`,
  });
});

process.on('SIGTERM', async () => {
  await boss.stop(); // graceful: waits up to 30 s for running jobs
  await pool.end();
});

A handler that throws marks the attempt as failed. retryLimit: 5 allows five retries after the first attempt, and retryBackoff makes each wait longer than the one before, with random jitter. After the last failure, pg-boss moves the job to order-email-dlq, a dead-letter queue, which holds jobs that ran out of attempts. The worker creates each queue only when getQueue() returns null, the check the pg-boss docs show. To change the settings of an existing queue, call updateQueue().

In the demo, with retryLimit: 2, a job that failed once succeeded on attempt 2. A job that always failed ran 3 times, with gaps of about 1.5 and 2.5 seconds, and then landed in the dead-letter queue. Nothing in this excerpt works on order-email-dlq, so failed jobs wait there until you look. The pg-boss README describes redriving them back to the main queue.

sendEmail() passes the idempotency key to the email provider, as Resend’s Idempotency-Key header, for example. The key is per order, so a retry after a crash does not send a second confirmation. But Resend keeps a key for 24 hours, so a job you redrive from the dead-letter queue days later can send twice. Keep the whole retry span under 24 hours; retryDelayMax caps each wait.

Run the worker as its own process

Start worker.ts as its own service beside the web app, not as a child of it. A deploy of the web app then leaves running jobs alone. A crash in the worker cannot take a Buy request with it, the way the /report request went down above. Under systemd, the default KillMode=control-group kills every process in the unit, so a worker started from the web app’s unit stops with it (systemd.kill).

boss.stop() waits up to 30 seconds for running jobs, which fits inside systemd’s 90 seconds. Under Docker, SIGKILL comes after 10 seconds, so lower the pg-boss timeout or raise Docker’s. If the worker dies anyway, the job runs again after expireInSeconds (15 minutes by default), and the idempotency key stops the second email.

Watch the age of the oldest job

The queue size alone looks the same during a 10:00 sale and during an outage, because both start with many jobs at once. pg-boss 12.36 added readyOldestSeconds, the age of the oldest job that is ready to run, and its docs call it “the figure that keeps rising” when workers stop. boss.getQueue('order-email') returns it with the counts (queue docs). Alert on it, not on the count.

What pg-boss costs

  • Delay. It polls every 2 seconds by default. LISTEN/NOTIFY shortens that, and brings the commit lock described above.
  • Repeats. It delivers at least once, and a crashed job waits 15 minutes unless you turn on heartbeats.
  • Connections. It takes up to 11 connections from your max_connections: a pool of 10, and one for LISTEN.
  • Vacuum. The queue table is only as healthy as autovacuum. One long transaction anywhere stops its cleanup.
  • Upgrades. Major versions come often. Version 11.0.0 (2025-09-26) had no automatic migration from version 10, and 12.0.0 (2025-11-09) moved to ESM.
  • Requirements. It needs Node.js 22.12 or later and PostgreSQL 13 or later (pg-boss).

Next, start the worker, kill it with kill -9 while a job runs, and time how long pg-boss takes to run that job again.

Primary sources for further reading:

Subscribe to the Stay Online newsletter to get the next article on how backend tools work underneath.

Comments

No comments yet. Ask a question or share what worked for you.

Leave a comment

Write a comment before you post.

Enter your name.

Never shown on the site.

Enter an email address like name@example.com.

Comments are checked before they appear. Fields marked * are required.

Keep reading

Related articles

  • Backend & Cloud

    How Git stores your history

    How Git stores history: blobs, trees and commits named by their hash, branches as pointers, the reflog, packfiles, and how to get lost commits back.