DEV Community

Cover image for Reliable Background Jobs in Node.js with BullMQ: Paid Twice, Still No Cake
Shubhra Pokhariya
Shubhra Pokhariya

Posted on Edited on Originally published at shubhra.dev AI-assisted

Reliable Background Jobs in Node.js with BullMQ: Paid Twice, Still No Cake

Runnable experiments expose hidden payment bugs

Maya orders a chocolate cake for her friend's birthday. The party starts at 6. She taps Pay, and the screen says, "Sit back. We've got this." At 5:15 her phone buzzes. Payment received. Then it buzzes again. Payment received. Maya now has two charges, zero cakes and 45 minutes.

The server dashboard shows nothing wrong.

That's the whole problem in one line. A job can finish, your database can say "paid", and the customer can still have been charged twice. So the payment provider in the lab keeps its own record, and the payment experiments are judged by what it recorded, not by what my worker believed.

This post follows one order through a small bakery system and breaks it seven ways on purpose. Each break is a runnable experiment, so you can check my results on your own machine with one command. The examples use BullMQ, PostgreSQL and a fake payment provider, but most of what they show applies to any queue running background jobs in Node.js.

TL;DR

If you only have a minute, this table is the whole post. Each row is one failure, and the experiments below let you reproduce it.

What goes wrong What helps
A worker dies mid-job and the job runs again Write every job so it is safe to run twice. A queue delivers jobs. It does not promise each one runs once
The payment provider is down for a minute Retry temporary errors with exponential backoff and jitter. Do not retry a declined card
The charge happened but the answer got lost An idempotency key that the provider honors, sent on every attempt
The order was saved but the job was never queued A transactional outbox, with the order ID as the job ID
Two workers take the last cake slot One atomic UPDATE ... WHERE remaining > 0, not read-then-write
A deploy stops a worker mid-job Handle SIGTERM and call worker.close() so the worker finishes what it started
The job succeeds after the party began A deadline check at the start of the job, and an alert on work about to be late

Why I built this

In my earlier posts on whether AbortController cancels server work and whether AbortSignal cancels a database query, both part of my Node.js Cancellation and Resource Management series, the lesson was the same. Aborting a request doesn't stop the work behind it. The server kept going after the client left, and pg, mysql2 and mariadb ignored the signal while the query ran on. Background jobs show the other side of it. When a job is retried, the first attempt may already have changed something, and the retry has no idea.

I wanted to count what really happened instead of trusting my own logs.

The bakery

Diagram of the bakery system: counter, order book, ticket rail, kitchen helper, payment desk and outbox

In the bakery In the code What it does
Counter API Takes the order and answers quickly
Order book PostgreSQL Keeps the order and its status
Ticket rail BullMQ on Redis Holds waiting jobs and hands them to workers
Kitchen helper Worker process Charges the card and marks the order paid
Payment desk Fake provider Records every charge in its own ledger

One rule runs through everything. Redis holds work in flight, PostgreSQL holds the order, and the payment provider holds the record of what was actually charged. If Redis and PostgreSQL disagree about an order, the order book wins. If the question is whether Maya was charged, the provider's ledger wins.

BullMQ 6 can also run on PostgreSQL, according to its documentation. I used Redis because BullMQ ran only on Redis before version 6, so that's what most existing apps use, and this lab is about how jobs behave, not about choosing a backend. Note that BullMQ 6 no longer installs ioredis for you, so the repo lists it as its own dependency.

Run the lab

You need Docker with Compose v2, and Git to clone the repo. Node isn't needed on your machine.

git clone https://github.com/shubhrapokhariya/nodejs-bullmq-background-jobs.git
cd nodejs-bullmq-background-jobs
docker compose run --rm lab
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025

That starts PostgreSQL 18 and Redis 7, installs the dependencies from the lockfile inside a Linux container, and runs all seven experiments. The results are written to results/RESULTS.md. While it installs, npm prints a deprecation warning about node-abort-controller. It comes from a dependency of BullMQ and doesn't affect the lab. The container matters because on Windows Node can't deliver SIGTERM to a child process as a catchable signal, and experiment 6 depends on it.

A few things to know before you trust any number here:

  • The payment provider is a simulation I wrote. It saves a successful charge and replays it when the same Idempotency-Key comes in again, can drop a response after charging, and can return temporary 503 errors or a 402 decline (the code I picked for a decline in this lab). It doesn't model comparing parameters, caching errors or expiring keys, which real providers can do. It isn't Stripe, so check your own provider's documentation before copying its behavior.
  • Everything runs on one machine, so these are lab results and not production benchmarks.
  • The lab uses Node 22.23.5, BullMQ 6.7.10, ioredis 6.1.0, pg 8.23.1, PostgreSQL 18.7 and Redis 7.4.12, all pinned in the repo.
  • I ran the whole lab three times with the same experiment code. The first run used an earlier version of the report formatting, which changed nothing in the experiments. Experiments 1, 3, 4 and 7 gave identical results every time. Experiments 2, 5 and 6 vary a little, so I report ranges, and the tables below are from the third run. Your exact numbers will vary.

Experiment 1: the same ticket reaches a helper twice (stalled jobs)

Maya's helper starts her cake. The power goes out. A second helper picks up the same ticket and starts again.

BullMQ aims for at-least-once processing, which means a job can be processed more than once. A worker holds a lock on its job and renews it on an interval, by default at half of lockDuration. If the lock expires, the job counts as stalled and gets restarted. The stalled event tells you when that happens, and maxStalledCount (default 1) limits how many times a job can be recovered. See BullMQ's stalled jobs guide for the details, and the WorkerOptions reference for the defaults (30 seconds for both lockDuration and stalledInterval).

To test it, the lab shortens lockDuration to 2 seconds so you don't have to wait for the 30 second default, enqueues a 4 second job and starts worker 1 as a separate OS process. When the job body begins, the lab sends SIGKILL, which is a crash and not a polite shutdown. Worker 2 starts afterwards and runs the stalled-job check. I ran it twice, once with the default maxStalledCount of 1 and once with 0.

const worker = new Worker(queueName, processor, {
  connection: redisConnection({ maxRetriesPerRequest: null }),
  lockDuration: 2000,
  stalledInterval: 1000,
  maxStalledCount: 1, // try 0 to see the difference
});
worker.on("stalled", (jobId) => log(`STALLED job ${jobId}`));
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
Variant Kitchen started Kitchen finished Final job state Stalled events seen Failed reason
maxStalledCount 1 (default) 2 1 completed 1 -
maxStalledCount 0 1 0 failed 1 job stalled more than allowable limit

With the default, the job body began twice, finished once, and the job ended as completed. With maxStalledCount 0, it began once, never finished, and the job ended as failed with "job stalled more than allowable limit". In the logs the default case looks almost like nothing happened. There's one stalled event, one completed job, and an effect that ran twice.

No setting turns at-least-once into exactly-once. Setting maxStalledCount to 0 turns a silent repeat into a visible failure, which suits jobs where a repeat is dangerous and a person can deal with a failure. For everything else, make the job safe to run twice. Experiments 3 to 5 show how.

A related thing to watch is that CPU-heavy synchronous work can block the event loop so the worker misses its lock renewal. A healthy worker can then look dead, and the job gets processed again. BullMQ's stalled jobs guide says to return control to the event loop often enough. Raising lockDuration gives longer pauses more room, but it also makes recovery slower when a worker really does die.

Experiment 2: the card machine sulks (retries, backoff and jitter)

Next, the payment provider has a bad minute. Some failures will fix themselves and others never will.

BullMQ's built-in backoff types are fixed and exponential, and both accept a jitter option that randomizes the delay. A job added without attempts runs once and goes straight to failed if it throws. Throwing UnrecoverableError skips the remaining attempts (see Stop retrying jobs). More in Retrying failing jobs.

I sent two orders through the worker. cake-503 gets two 503 answers and then succeeds. cake-declined gets a 402. Both jobs have four attempts and a 200 ms exponential backoff.

await queue.add(
  "bake",
  { orderId, amount: 1200 },
  {
    jobId: orderId,
    attempts: 4,
    backoff: { type: "exponential", delay: 200 },
  },
);
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
if (response.status === 402) throw new UnrecoverableError("card declined");
if (!response.ok) throw new Error(`provider answered ${response.status}`);
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
Order Provider requests Gaps between requests (ms) Final job state Failed reason
cake-503 3 240, 488 completed -
cake-declined 1 - failed card declined

cake-503 reached the provider three times, with two 503 answers and then a success. The gaps roughly doubled (240 to 266 ms, then 464 to 506 ms across the three runs). cake-declined reached the provider once and failed at once, even though it had four attempts available.

One small thing I ran into. In my first run the report showed "provider answered 503" as the failed reason for cake-503, a job that ended as completed. The job had failed on an earlier attempt, and its failedReason was still set after it succeeded. Check a job's state before you read its failedReason. That first report is still in the repo as results/RESULTS-run1.md.

When forty jobs fail together

Now suppose the provider goes down for everyone, and forty jobs fail at the same moment. With plain exponential backoff, their retries come back together too, and you send a synchronized wave at a service that's trying to recover. (If you run that service, my post on how an API should say no, with 429, 503 and Retry-After, is the receiving end of this.) Jitter randomizes each delay so the retries spread out, but only across the window you give it. The lab uses a 3 second base delay and compares no jitter, jitter 0.5 and jitter 1.

Backoff Retries observed Time between first and last retry Busiest fixed 100 ms bucket
exponential, no jitter 40 57 ms 40
exponential, jitter 0.5 40 1412 ms 7
exponential, jitter 1 40 2820 ms 5

Across three runs, the 40 retries without jitter landed within 55 to 95 ms, all in one 100 ms bucket every time (the buckets are fixed 100 ms slots that start at the first retry). With jitter 0.5 they spread over 1315 to 1429 ms with at most 6 or 7 per bucket, and with jitter 1 over 2820 to 2880 ms with at most 5. Jitter can only spread retries across the window it is given. Jitter 0.5 used about half of the 3 second base delay and jitter 1 used nearly all of it. The no-jitter row was tightly clustered on my machine, and your exact figures will differ.

Classify errors before you pick limits. A permanent error that you retry wastes attempts and delays the real failure. A temporary error that you treat as permanent loses work. When you can't tell, retry only if repeating the call is safe, for example because it carries an idempotency key, which is the next experiment.

Experiment 3: paid twice (idempotency keys)

Timeline showing the worker asking for a charge, the provider charging, the answer getting lost and a retry charging again

This is the incident from the opening. The worker asks the provider to charge Maya, and the provider does. Then the answer never arrives, or the worker dies before it can write "paid". The retry knows nothing about the charge.

I used the order ID as the BullMQ job ID. That stops the same order from being added to the queue twice while the job still exists, which is useful, but it does nothing for the provider. The retry is the same job with the same ID, and it still sends a fresh request to the payment desk.

The fix on the provider side is an idempotency key. In Stripe's API v1, the first request with a key has its status and body saved, and later requests with the same key get that saved result back (see idempotent requests). Reusing a key with different parameters is an error, and keys can be removed after 24 hours. If the outcome is still unknown after your retries, Stripe's error handling guide says to retrieve the object, check the request in the Dashboard and use webhook events to reconcile it, and to contact support if you still can't establish what happened, before repeating the operation. API v2 behaves a little differently, with a 30 day window, so read the page for the API you use. My fake provider copies only the first behavior. It saves a successful charge and replays it for the same key.

The lab runs four variants, each against a clean ledger:

  1. The response is lost, and the worker sends no key.
  2. The response is lost, and the worker sends order-maya-cake-charge as the key.
  3. The worker is killed right after the answer arrives, with no key.
  4. The same crash, with the key.

In the lost-response variants the job fails and BullMQ retries it after a fixed 300 ms backoff. In the crash variants a second worker picks the job up through stalled-job detection, as in experiment 1.

const headers = { "content-type": "application/json" };
if (process.env.USE_KEY === "1") {
  // the keyed variants only
  headers["idempotency-key"] = `order-${orderId}-charge`;
}

const response = await fetch(`${PROVIDER_URL}/charges`, {
  method: "POST",
  headers,
  body: JSON.stringify({ orderId, amount }),
  signal: AbortSignal.timeout(3000),
});
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025

The key comes from the business operation (this order's charge), not from the attempt. If each attempt generates its own random key, the retry gets a new key and the provider charges again.

There is a catch in the other direction too. Stripe's guide lists two common ways to build keys. One is a random token such as a UUID v4, and the other is a key derived from an object you already have, like a shopping cart ID. The key in this lab is the second kind. In API v1 the saved result is replayed whether the first request succeeded or failed, once it has started to execute. A deterministic key like order-X-charge would therefore replay a decline. If a customer retries with a new card, that's a new operation and needs a new key, for example the order ID plus a payment attempt number. Decide on purpose what counts as the same operation.

Variant Charges in the provider ledger Order status Job state Verdict
Lost response, no idempotency key 2 paid completed charged 2 times
Lost response, with idempotency key 1 paid completed charged once
Crash after the charge, no key 2 paid completed charged 2 times
Crash after the charge, with key 1 paid completed charged once

Without a key, a lost response and a crash right after the charge both left two charges at the provider. With the key, both left exactly one. Look at the middle columns too. Every job ended as completed and every order as paid, so nothing in your own database shows that Maya was charged twice. Only the provider's ledger does.

So the ledger is the record to trust. Your logs say what the worker believed, and the provider's records say what happened. When they disagree, you want to find out from a query and not from Maya.

Remember what the key can't do. It protects the call that carries it. It doesn't protect the email you send afterwards, the stock you decrement in your own database, or a webhook you fire to someone else. Each side effect needs its own protection, which is what the next experiments are about.

A similar problem appears when retrying a group of promises after a partial failure. In my Promise.all() experiment, retrying the whole group repeated writes that had already succeeded. Stable idempotency keys prevented that.

Experiment 4: the ticket that never arrived (transactional outbox)

The counter writes Maya's order into the order book, then walks over to hang the ticket on the rail. In between, the lights go out. The order exists. The ticket does not. Nobody is baking.

This failure is quiet. Nothing is retried, nothing alerts, and Maya just waits.

The lab runs two variants with 20 orders each. The first saves the order and then calls queue.add(), and every fifth request throws between the two writes.

await pool.query(`insert into orders (id, status) values ($1, 'received')`, [
  id,
]);
// a crash here leaves an order with no job
await queue.add("bake", { orderId: id, amount: 1200 }, { jobId: id });
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025

The second variant uses a transactional outbox. The request never talks to Redis. It writes the order and a "please publish this" row in one PostgreSQL transaction, and a separate dispatcher publishes the rows later.

await client.query("begin");
await client.query(`insert into orders (id, status) values ($1, 'received')`, [
  id,
]);
await client.query(`insert into outbox (order_id, payload) values ($1, $2)`, [
  id,
  payload,
]);
await client.query("commit");
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
await client.query("begin");
const { rows } = await client.query(
  `select id, order_id, payload from outbox
   where sent_at is null order by id limit 50 for update skip locked`,
);
for (const row of rows) {
  await queue.add("bake", row.payload, { jobId: row.order_id });
  await client.query("update outbox set sent_at = now() where id = $1", [
    row.id,
  ]);
}
await client.query("commit");
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025

for update skip locked only does its job inside a transaction, because the row locks last until commit. That lets several dispatchers run without grabbing the same rows. The lab holds that transaction open while it talks to Redis, which keeps the example short. In production, keep the batch small so the transaction stays short.

The dispatcher can also crash after add() and before it marks the row as sent. The lab does exactly that once, for cake-7, and then runs the dispatcher again. It throws an exception at these two points instead of killing the process, and the database and the queue end up in the same state as after a real crash.

Variant Orders saved Jobs in the queue Orders without a job add() calls made
Naive: save order, then add job 20 16 4 n/a
Outbox: order and outbox row in one transaction 20 20 0 27

The naive version saved 20 orders and queued 16 jobs, so 4 orders were waiting for a ticket that never came. The outbox version ended with 20 orders and 20 jobs. The 27 add() calls are 7 before the dispatcher crashed (cake-1 to cake-7) plus 20 in the second pass, and the repeated calls were ignored.

The second publish is harmless because BullMQ ignores add() when a job with that ID already exists. BullMQ's Job Ids guide also restricts custom IDs. They must not contain : and must not be digit-only strings. Use something like order-123, not order:123 and not 123. BullMQ has a built-in deduplication feature as well, described in its Deduplication guide. I used plain job IDs because the outbox only needs the simple version.

That protection lasts only while the original job still exists. If you remove completed jobs and the same event arrives again later, there is nothing left to match against. Keep a durable record in PostgreSQL, such as a unique constraint on the order or on the effect.

The outbox gives you at-least-once publishing, so the job ID and an idempotent worker still matter. It also adds a moving part, a dispatcher you have to run and watch. The queries in sql/stuck-orders.sql find outbox rows that have been waiting too long.

Experiment 5: who gets the last cake slot (race conditions)

On Saturday the bakery has three baking slots left. Twenty orders arrive together. Two helpers look at the slot count, both see "1 left", and both promise it.

The lab sends twenty concurrent reservation attempts at a table that starts with three slots.

// Read, think, write back. Two helpers can read the same number.
const { rows } = await pool.query("select remaining from slots where id = 1");
if (rows[0].remaining <= 0) return false;
await sleep(5); // stands in for a network call or any other pause
await pool.query("update slots set remaining = $1 where id = 1", [
  rows[0].remaining - 1,
]);
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
// Let the database decide in one statement.
const result = await pool.query(
  "update slots set remaining = remaining - 1 where id = 1 and remaining > 0 returning remaining",
);
return result.rowCount > 0;
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025

The first version waits 5 ms between the read and the write. That pause stands in for any real delay, such as a network call or a cache lookup. The gap exists in the real code anyway. The lab only makes it wide enough to see on a laptop.

Variant Slots available Concurrent attempts Reservations granted Slots left in the table Oversold
Naive: read, then write 3 20 20 1 17
Atomic: UPDATE ... WHERE remaining > 0 3 20 3 0 0

The read-then-write version granted 20 reservations against 3 slots in every run I did, so 17 were oversold, which is the most possible with 20 attempts and 3 slots. The table afterwards said 0 slots left in two runs and 1 in the third, so nothing in that number shows that 20 customers were promised a cake. The atomic version granted exactly 3 every time.

This pattern covers one counter in one database. If the decision spans several rows, a unique constraint or a row lock with FOR UPDATE can do the same job. If the resource lives in another system, that system has to make the decision, for example through a lease with an expiry. The idea is the same in each case. Let one place make the decision, and make it a single step.

Experiment 6: the kitchen closes mid-order (graceful shutdown)

At 5:30 you deploy a new version. The orchestrator sends SIGTERM to every old worker, and one of them is halfway through Maya's cake.

I covered the HTTP side of this in Node.js Graceful Shutdown Tested on 4 Servers. Workers have their own version of the problem.

The lab uses a 3 second job, sends SIGTERM while it runs, and then starts a replacement worker. The first variant has no signal handler. The second calls worker.close(), which waits for the active job.

process.on("SIGTERM", async () => {
  await worker.close(); // stop taking new jobs, wait for the active one
  await pool.end();
  process.exit(0);
});
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
Variant Old worker exited after Kitchen started Kitchen finished Job state Job completed after SIGTERM
No SIGTERM handler 15 ms 2 1 completed 5499 ms
SIGTERM handler calls worker.close() 2935 ms 1 1 completed 3343 ms

With no handler, the old worker exited within 5 to 16 ms, the job body started twice, and my harness saw the job complete 5477 to 5499 ms after SIGTERM. With worker.close(), the old worker took 2935 to 2947 ms to exit because it finished the 3 second job first, the body started once, and the harness saw it complete 3343 to 3352 ms after SIGTERM.

These are times my harness observed, not job-finish timestamps. The graceful row includes about 0.4 seconds of replacement-worker startup, because that worker only starts after the old one exits. The no-handler row has no such delay, since its replacement starts straight away. So the two rows are about 2.1 seconds apart as observed, or about 2.5 seconds measured from the old worker's exit. Either way that fits the 2 second lock from experiment 1 plus the wait for the stalled-job check.

Graceful shutdown has a deadline. Most platforms send SIGKILL after a grace period, so a job longer than that period will still be cut off. Long jobs need to be split into steps that can resume, or they need checkpoints. A graceful worker helps jobs that are short enough to finish. It doesn't replace idempotency.

Experiment 7: the cake that was ready after the party (deadlines)

The queue backed up during a rush. Maya's order waited, was processed, charged and marked paid. At 6:20. The party started at 6.

Every dashboard says the job succeeded. For Maya it failed. Nothing in the code is wrong, yet a job can eventually succeed and still be a business failure because it succeeded too late.

In the lab, five orders wait five seconds in a backed-up queue. Three have a 4 second deadline and two have a 30 second deadline. One worker has no deadline check. The other refuses a job when too little time remains.

if (Date.now() > deliverBy - MIN_BAKE_MS) {
  await pool.query(
    `update orders set status = 'expired', updated_at = now() where id = $1`,
    [orderId],
  );
  throw new UnrecoverableError(
    `order ${orderId} can no longer be ready in time`,
  );
}
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025

This guard is illustrative. It checks once, at the start of the job, with a fixed 1 second estimate of how long the work needs.

Variant Orders paid Paid after the deadline Orders expired Charges at the provider
No deadline check 5 3 0 5
Deadline check at the start of the job 2 0 3 2

Without the guard, all 5 orders were paid, 3 of them marked paid after their deadline, and the provider's ledger shows 5 charges. With the guard, 2 orders were paid, 3 expired, none was paid late, and the ledger shows 2 charges, so the expired orders weren't charged. In the unguarded run there was no failed job and no error anywhere, only three orders that were paid late.

The guard fails the job visibly instead of taking money for a cake that can't arrive. Someone still has to tell Maya, which is where an alert or a compensation step comes in, such as a refund, an apology or an offer of pickup. The better fix is upstream. Watch queue age, meaning how long the oldest waiting job has been waiting, and get paged before orders go late, not after.

Finding out before Maya calls

After seven failures, the practical question is how you would notice. Four cheap things are worth doing first.

  1. Log every stalled and failed event with the job ID and order ID. A stalled event usually means a job is about to be processed again.
  2. Alert on queue age, not only queue depth. Ten waiting jobs that are ten seconds old are fine. One job that's ten minutes old is not.
  3. Query for stuck rows. The file sql/stuck-orders.sql finds orders stuck in charging, outbox rows nobody published, and unpaid orders close to their deadline.
  4. Keep failed jobs long enough to read them. A retained failed job still occupies its job ID, so a later add() with the same ID can be ignored until the job is removed.
select id, status, updated_at, now() - updated_at as stuck_for
from orders
where status = 'charging' and updated_at < now() - interval '2 minutes';
🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025

Queue or workflow engine?

Either can be the right choice. A queue plus the patterns above keeps your dependencies small and gives you control, and you own the outbox, the idempotency rules, the dead-letter handling and the dashboards.

Durable workflow tools such as Temporal and Inngest work by recording the result of each step, so a retry can resume after the last finished step. That removes a class of bugs and adds a platform to learn. A call to an outside service can still succeed just before its result is recorded, so it still deserves an idempotency key.

I didn't test those tools here, so this lab says nothing about how they compare. As a rough rule, if your jobs are short, few and independent, a queue and some discipline may be enough. If you have long, multi-step processes that must survive deploys, it is worth reading about durable execution.

A production checklist

Copy this into your repo's docs and cross out what doesn't apply.

  • [ ] Every job is safe to run twice, or it fails visibly when it cannot be.
  • [ ] Every external call that changes something is safe to repeat: use the provider's idempotency key where it exists, built from the business operation, and otherwise keep a durable record of the operation and reconcile with the provider.
  • [ ] Temporary errors retry with exponential backoff and jitter. Permanent errors fail at once.
  • [ ] Orders and jobs are created through an outbox, or you accept the gap and monitor it.
  • [ ] Job IDs come from business IDs and avoid :.
  • [ ] Shared counters change in one atomic statement.
  • [ ] Workers handle SIGTERM and finish short jobs. Long jobs can resume.
  • [ ] No job blocks the event loop for long, and lockDuration leaves room for the pauses you can't avoid.
  • [ ] Jobs check their deadline before doing expensive or irreversible work.
  • [ ] You log stalled and failed events and alert on queue age.
  • [ ] If you use the Redis backend, persistence (AOF) is enabled and maxmemory-policy is noeviction, as BullMQ's going to production guide recommends.
  • [ ] Someone can run a reconciling query and see what the provider thinks happened.

What this lab cannot tell you

  • The provider is simulated. A real payment provider can differ, for example in how long it keeps keys or what it returns for a key used with different parameters. Test against its sandbox.
  • It is one machine with one Redis and one Postgres. Network partitions, Redis failover and clock skew aren't tested.
  • Concurrency is small. The lab shows that a race exists, not how often it happens in your traffic.
  • Versions matter. The results come from the versions listed above and recorded in results/RESULTS.md, and queue libraries change, so it is worth rerunning the lab after an upgrade.

Back at the counter

Replay Maya's order through the lab and it goes differently. The charge is recorded once, because the retry carries a key. The ticket exists, because the order and the note were written together. The last slot goes to one helper, and a deploy doesn't drop her cake. If the kitchen is too backed up to make the party, someone tells her before she finds out herself.

The repo is at github.com/shubhrapokhariya/nodejs-bullmq-background-jobs. If you run it and your table differs from mine, I'd like to hear about it.

Top comments (21)

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
smtahosin profile image
S M Tahosin • • Edited

Hey Shubhra! The double charge thing... I ran a nightly check for a few weeks once, our orders against the provider list. First week it found 3 double charges. Logs? nothing lol. After that I stopped trusting webhooks alone honestly

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

Three in the first week, and nothing in the logs. That's very close to what I found in Experiment 3. The jobs completed, the orders said paid, but the provider's ledger showed the second charge.

A regular comparison against the provider's records is the same idea as the reconciling query on my production checklist. I didn't look at webhooks in this lab.

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
smtahosin profile image
S M Tahosin •

Hey Shubhra! 3 in first week, 0 logs, Experiment 3 matching... webhook retries at 1am, no idempotency key, I've been there lol. webhooks next for lab? :)

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 Thread
 
shubhradev profile image
Shubhra Pokhariya •

Haha, webhook retries at 1am! 😅 That's a rough one. A webhook lab might be worth exploring next. Thanks for sharing your experience!

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025 Thread
 
smtahosin profile image
S M Tahosin •

Thanks Shubhra! webhook lab as sequel, 1am retries and all... rough nights make good labs lol. boring logs for both of us from here xD :)

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
webdeveloperhyper profile image
Web Developer Hyper •

The bakery and Maya made the difficult story more approachable. Nice approach! 😄

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

Glad you enjoyed it! 😊 Maya and the bakery made the whole thing a lot more fun to write too. Thanks for reading!

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

Experiment 3 was the one that really got me. Without the idempotency key the job completed and the order said paid, but the provider's ledger in my lab had two charges. My own database had no idea.

How do you catch this in prod? Reconcile against the provider, rely on webhooks, or find out when a customer tells you first?

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
kevinhall profile image
Kevin Hall •

i'd run a small daily job that pulls the charges from the provider and groups them by order id, anything with two is exactly the case your own database can't see

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

Yeah, that's a good way to catch it. Grouping the provider's charges by order ID would show exactly what my database missed in Experiment 3. My production checklist has a reconciling query for this reason. I'd just include the payment attempt in the grouping too, so a legitimate retry with a new card doesn't get flagged as a duplicate.

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
fattakhov profile image
Mansur Fattakhov •

The provider-ledger checks make the experiments especially useful. One next case I'd be curious about: the first attempt charges successfully, crashes, and is retried after deliverBy. Would the retry reconcile the existing charge before marking the order expired? That would distinguish work that never started from work whose payment outcome was lost.

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

Thanks Mansur, good case. No, my guard wouldn't catch it. It checks the clock once at the start of the job, and if there isn't enough time left, it marks the order expired and throws UnrecoverableError. It never asks the provider anything. So a retry after deliverBy would expire the order while the first attempt's charge sits in the ledger.

In experiment 7, the three expired orders had no charges only because the guard ran before any charge was attempted. It can't tell work that never started from a payment outcome that got lost, which is exactly the distinction you're pointing at.

I haven't tested that combination, so I don't have numbers for it. What I'd do is check the provider's record for that order before deciding it's expired. If a charge exists, I'd reconcile the order and either handle a refund or follow a paid-late path if the customer still wants it. I wouldn't send another charge request just to find out, even with an idempotency key.

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
ascendra_ventures_92c21f2 profile image
Ascendra Ventures •

Judging the payment experiments by the provider's ledger rather than by what the worker believed is the detail that makes this post useful. Experiment 3 shows why: the job completed, the order said paid, and only the outside record could see the second charge. Kevin Hall's daily reconciliation by order ID, with the payment attempt added to the grouping as you suggested, catches exactly the case your own database will never notice.

Ascendra Ventures worked on a pipeline with the same failure shape at a seed-stage talent platform. Candidate enrichment involved long API waits, and the problem was not loud crashes but people left in unclear states. The profile processor was rebuilt as a durable workflow: urgent profiles processed immediately, the rest batched, and fallback polling when callbacks went quiet, so every candidate either finished or visibly failed instead of getting stuck in the middle. The write-up reports 99.99% system reliability. Your outbox and idempotency key rows apply the same idea to money: never let the system's own belief be the only record of what happened.

For the deliverBy case Mansur raised, would you have the guard ask the provider for an existing charge before expiring the order, or leave that to the nightly reconciliation?

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

I wouldn't leave that to the nightly reconciliation. In Experiment 7, the guard runs before any charge is attempted, so expiring those orders is safe. The ledger confirmed it: 3 expired, none charged.

The case I didn't test is a retry. If attempt 1 already reached the provider and then died, the guard on attempt 2 could expire an order that's actually been paid. So if the order is still in charging, I'd check the provider's record for that order by order ID, if the provider supports that lookup, or by a stored payment ID if one is available, before changing its status. If a successful charge exists, the order is paid but late, so I'd either fulfil it or refund it. If I still can't establish the outcome, I'd leave it unresolved rather than expire it or send another charge.

The reconciling query is still the backstop, but it shouldn't be what makes that call.

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
robertpaschal profile image
Odinaka Robert Nnamani •

Forty retries with no jitter all landed within 95 milliseconds in one bucket, jitter 1 spread them over nearly three seconds. Same backoff and window, the spread is the whole difference.

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

Exactly, that's the part I wanted people to actually see. Without jitter, all 40 retries piled into the same 100 ms bucket. With jitter 1, they spread over about 2.8 seconds, never more than 5 in a bucket.

Same 3-second base delay, but a very different load on a provider that's trying to recover.

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
foundrybell profile image
Foundry Bell •

job doubles

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
hemapriya_kanagala profile image
Hemapriya Kanagala •

Loved the bakery analogy, di 😀 The way you broke down each failure with actual experiments makes this so much easier to understand.

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

Thank you so much, Hema! 😀 The bakery part was honestly the most fun to write. I wanted each failure to feel like something you'd actually hit while building a job system, not just another list of what can go wrong. So happy it helped! ❤️

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
technogamerz profile image
𝐓𝐡𝐞 𝐋𝐚𝐳𝐲 𝐆𝐢𝐫𝐥 •

Thanks for this, sis :D

🏆 ยอดนิยม: shubhradev/reliable background jobs in nodejs with bullmq paid twice still no cake il - Kapook Update 2025
 
shubhradev profile image
Shubhra Pokhariya •

You're most welcome, Divya! ❤️ So glad you enjoyed it ☺️