Designing Durable Node.js Batch Jobs with Queues and WorkersDesigning Durable Node.js Batch Jobs with Queues and Workers
The network for creativity
Join 1.25M professional creatives like you
Connect with clients, get discovered, and run your business 100% commission-free
Creatives on Contra have earned over $150M and we are just getting started
Your deployment shouldn't kill your batch jobs It's 2:07 PM. Your app is generating 8,000 monthly invoices. It's been running for 11 minutes. Half are done. Then someone deploys a small fix. The container restarts. The process dies. So do 4,000 invoices that were never generated — and nobody knows exactly which ones. I see this pattern a lot in Node.js apps, and it has nothing to do with bad code. It has to do with where the work is running. If a long-running job lives inside your web process, it has the same lifespan as that process. Deploy, crash, autoscale, out-of-memory — any of those ends the job too. Message queues fix that by giving the work a life of its own. The core idea: separate asking for work from doing the work A message queue system has three parts:
Producer — your API. It doesn't do the heavy work. It writes a job description down and returns immediately.
Queue — usually Redis or a broker. It stores the job durably, outside your app process.
Worker — a separate process whose only job is to pick up jobs, do them, and mark them complete or failed. User clicks "Generate invoices" ↓ API adds 8,000 jobs to Redis → responds in ~200ms ↓ Workers process jobs in the background (10 at a time, per worker) ↓ Job succeeds → marked completed Job fails → retried automatically, then logged for inspection Your user isn't waiting on a request that times out after 30 or 60 seconds. Your server isn't holding thousands of connections open. And the job no longer depends on one process staying alive. That's the whole shift: from "run it now, in this request, in this process" to "record what needs doing, reliably, and let workers do it." A real scenario: monthly billing in Node.js with BullMQ BullMQ is a queue library for Node.js built on Redis. It's the one I reach for in this stack because the jobs, retries, delays, and concurrency controls are all first-class — not things you have to invent yourself. Say a SaaS app needs to generate invoices, create a PDF for each, and email it — every month, for every customer. Step 1: The API only enqueues // producer.ts — runs in your API process import { Queue } from 'bullmq';
const billingQueue = new Queue('billing', { connection: { host: 'redis', port: 6379 } });
// One job per customer, not one giant job for everyone for (const customer of customers) { await billingQueue.add('generate-invoice', { customerId: customer.id, period: '2026-11' }, { jobId: invoice-${customer.id}-2026-11, // prevents duplicates attempts: 3, backoff: { type: 'exponential', delay: 5000 }, removeOnComplete: 1000, removeOnFail: false // keep failures so you can inspect them }); }
return res.json({ queued: customers.length }); Notice the jobId. If someone clicks twice, or the API retries, BullMQ won't create a second invoice job for the same customer and month. Idempotency starts here. Step 2: A separate worker does the slow work // worker.ts — runs as its OWN process / container import { Worker } from 'bullmq';
const worker = new Worker('billing', async job => { const { customerId, period } = job.data;
const invoice = await generateInvoice(customerId, period); const pdf = await renderPdf(invoice); await emailPdf(customerId, pdf);
return { invoiceId: invoice.id }; }, { connection: { host: 'redis', port: 6379 }, concurrency: 10 // 10 jobs in parallel per worker, no more });
worker.on('failed', (job, err) => { console.error(Job ${job?.id} failed:, err.message); }); That concurrency: 10 matters more than it looks. Without a queue, a batch job will happily eat all your CPU and database connections. With a queue, you decide the pace — and you can scale it by simply starting more worker containers. Need it slower for a third-party API? BullMQ also supports rate limiting per worker. Need it later? Add delay. Need it every month? Use a repeatable / scheduled job instead of a fragile cron inside your API container. Now the DevOps part: what happens when you deploy? This is where queues earn their keep.
The jobs aren't in your app's memory. They're in Redis. Deploy v1.2 while 5,000 jobs are waiting? Those jobs are stored in Redis, not in the old container. The new worker starts, connects to the same queue, and picks up exactly where the old one left off. Nothing in the waiting line is lost. Condition: Redis itself has to be durable — run it as a separate service/container (not inside your app container), with persistence enabled (AOF) and a volume / managed instance. An in-memory-only Redis you restart casually defeats the purpose.
You can deploy the API and the workers independently. API and worker are two deployments using the same codebase. Ship an API-only fix without restarting workers mid-batch. Or scale workers from 1 to 4 for month-end, then scale back down — without touching the API at all. In Docker Compose terms, that's just two services: api and worker. In Kubernetes, it's two Deployments. Same image, different start command.
Graceful shutdown lets active jobs finish. A worker shouldn't be killed mid-PDF if you can avoid it. Handle the termination signal: process.on('SIGTERM', async () => { await worker.close(); // stops taking NEW jobs, finishes the active ones process.exit(0); }); Then give it time to use that grace: in Docker / Kubernetes, set your stop grace period (e.g. terminationGracePeriodSeconds) longer than your longest normal job. This one setting is the difference between a "rolling deploy" and a "rolling interruption".
If a worker does die, the job isn't gone. Sometimes you can't be graceful — a node dies, a container is OOM-killed. BullMQ tracks jobs a worker has picked up. If that worker stops checking in, the job is detected as stalled and returned to the queue for another worker to retry. That's why attempts: 3 + backoff matters, and why every job handler must be safe to run twice. A queue gives you at-least-once delivery, not magic exactly-once. Design for a retry: check "does this invoice already exist for this customer + period?" before creating a duplicate. Do that, and retries become a safety net instead of a source of double-charges.
Keep old and new workers compatible during a rollout. For a few minutes during a rolling deploy, v1 and v2 workers may both be consuming the same queue. So don't change a job's payload shape in a breaking way in the same release that depends on it. Add new fields as optional first, deploy, then tighten later. This is the queue version of a database migration rule — and it's the detail that makes zero-downtime deploys actually zero-downtime. My deployment checklist for queued batch jobs Queue storage (Redis) runs separately, with persistence (AOF) and a real volume / managed service Producer and worker are separate processes/containers, deployable independently SIGTERM handler calls worker.close() — no hard kills as the normal path Stop grace period > longest expected job duration Every job has a deterministic jobId and an idempotent handler attempts + exponential backoff set on every job that can fail transiently Failed jobs are kept and visible (I use Bull Board for a quick dashboard) — a silent failure is worse than a loud one Concurrency / rate limits set deliberately, not left to "as fast as possible" Payload changes are backward-compatible while old workers are still draining Run through that list, and a deployment stops being an event you schedule around your batch jobs. It just becomes... a deployment. When do you actually need this? Not every app does. If your "background job" takes 800ms, just run it. You need a queue when any of these are true: The work takes seconds to hours (reports, invoices, imports, video/image processing, bulk email) The work must finish even if the user closes the tab — or your server restarts You're hitting request timeouts on work that isn't really a request One heavy job slows down the whole API for everyone else You need retries, scheduling, or rate limiting against a third-party API (Shopify, Stripe, an email provider) In other words: the moment losing an in-progress job would mean losing money, data, or a customer's trust — it shouldn't be living inside a web request. The takeaway Message queues aren't about adding complexity. They're about moving risk. The risk moves out of a single fragile process, and into a store designed to hold it, with workers designed to retry it, pace it, and survive being replaced. That's good architecture, but honestly, it's also just good DevOps: decouple the thing that changes often (your app) from the work that must not be lost (your jobs). Deploy freely. Let the queue remember.
I help small businesses and SaaS teams untangle exactly this kind of thing — reliable background processing, safer deployments, and Node.js / PHP backends that don't fall over at month-end. If your batch jobs are living inside HTTP requests right now, that's fixable, and it doesn't require a rewrite.
Post image
Imran's avatar
The same problem shows up in WordPress land too. A long WP-Cron or Action Scheduler run gets cut off by a deploy or a PHP timeout and you're left with half a batch. Small queued chunks that can resume where they stopped is the fix every time. Good write-up.
Back to feed
The network for creativity
Join 1.25M professional creatives like you
Connect with clients, get discovered, and run your business 100% commission-free
Creatives on Contra have earned over $150M and we are just getting started