Part 8 of 10: Reliable background jobs in Node.js, from zero.
By Sandro Dezerio, senior full-stack engineer.
The sign-up example is the one from Part 1, Part 2, Part 3, Part 4, Part 5, Part 6, and Part 7. The numbers in this post come from running the code in it against a real Redis, with a fake email provider. Tested with Node 22, BullMQ 6.5.3, ioredis 6.0.0, pino 10.4.0, and Redis 7.
Part 6 ended with a worker that died and a second worker that took over without writing a single log line. Part 7 gave failed jobs a place to go, and a parked entry says what failed and how many times. It does not say when each attempt ran, which process ran it, or which request started it. This post closes that gap. Every step of a sign-up writes one JSON line, and one ID finds all of them.
What the logs say today
The Part 7 code writes no line when a job starts, fails, or finishes. The only thing it can print is the console.error for a copy that failed to reach the dead queue. Suppose a customer writes that the welcome email never arrived. For that user, the dead queue has the reason, 503 service unavailable, and three attempts. Nothing records when the attempts ran, how long each took, or which worker handled them.
Adding console.log("sending email") does not fix it. A worker that runs five jobs at a time (Part 2) writes the lines of five sign-ups mixed together, and a line such as provider error does not say whose sign-up it was. Every line needs enough context to be read on its own: which sign-up, which attempt, which request.
A log line is data
Structured logging means one JSON object per line, with the same field names every time. A program can filter it, and so can a person with grep. This post uses pino, a JSON logger for Node.js. Here is the whole logging layer, in one file:
import { randomUUID } from "node:crypto"; import { pino, type DestinationStream, type Logger } from "pino"; import { UnrecoverableError, type Job, type Queue, type Worker } from "bullmq"; import { signupJobOptions } from "./dead-letter.ts"; import type { Signup } from "./signup-queue.ts"; /** A sign-up plus the ID of the request that made it. The ID travels inside the job. */ export type TracedSignup = Signup & { correlationId: string }; type TracedJob = Job<TracedSignup>; // Every job that enqueueSignup adds carries the ID, so the worker side reads a Job<Signup> as a TracedJob. const traced = (job: Job<Signup>) => job as TracedJob; /** One JSON object per line. If someone logs an email address by mistake, it is redacted. */ export const createLogger = (destination: DestinationStream = process.stdout, worker = String(process.pid)): Logger => pino({ base: { service: "signups", worker }, redact: ["email", "signup.email"] }, destination); /** An error message can carry personal data. Take the email address out of it. */ export const reasonOf = (error: Error, signup: Signup) => error.message.replaceAll(signup.email, "<email>"); /** The same four fields go on every line about one attempt of one job. */ export const jobLog = (log: Logger, job: TracedJob, attempt: number): Logger => log.child({ correlationId: job.data.correlationId, jobId: job.id, userId: job.data.userId, attempt }); /** The request side: make the ID, send it along inside the job, and log it before the job can start. */ export async function enqueueSignup(queue: Queue<Signup>, log: Logger, signup: Signup, newId: () => string = randomUUID): Promise<string> { const correlationId = newId(); const data: TracedSignup = { ...signup, correlationId }; const options = signupJobOptions(signup); const fields = { correlationId, jobId: options.jobId, userId: signup.userId }; // The job ID is the same for the same sign-up (Part 6), so a second request adds nothing. Say so, and name the first request. const stored = await queue.getJob(options.jobId); if (stored) { const existing = traced(stored).data.correlationId; log.info({ ...fields, existing }, "job already exists, this request adds nothing"); return existing; } // This line is written before the add: after it, a worker could start the job and write its own line first. log.info(fields, "adding job"); await queue.add("welcome-email", data, options); return correlationId; } type Handler = (job: TracedJob, log: Logger) => Promise<void>; /** Wrap a handler: one line when an attempt starts, and one when it ends. */ export const withLogs = (log: Logger, handler: Handler) => async (plain: Job<Signup>): Promise<void> => { const job = traced(plain); const attemptLog = jobLog(log, job, job.attemptsMade + 1); const started = Date.now(); attemptLog.info("job started"); try { await handler(job, attemptLog); attemptLog.info({ durationMs: Date.now() - started }, "job done"); } catch (error) { attemptLog.warn({ durationMs: Date.now() - started, reason: reasonOf(error as Error, job.data) }, "job attempt failed"); throw error; } }; /** Lines for what the handler cannot see: the last failure, a stalled job, a worker error. */ export function logWorkerEvents(worker: Worker<Signup>, log: Logger): void { worker.on("failed", (plain, error) => { if (!plain) return; const job = traced(plain); const lastAttempt = error instanceof UnrecoverableError || job.attemptsMade >= (job.opts.attempts ?? 1); // the test from parkFailedJobs if (lastAttempt) jobLog(log, job, job.attemptsMade).error({ reason: reasonOf(error, job.data) }, "job gave up"); }); // The stalled event gives only the job ID and the state it was in, so that is all this line can carry. worker.on("stalled", (jobId, previous) => log.warn({ jobId, previous }, "job stalled: its worker stopped renewing the lock")); worker.on("error", (error) => log.error({ reason: error.message }, "worker error")); } Here is what each part does:
-
createLoggerwrites one JSON object per line. Every line getsserviceandworker, plus thelevelandtimefields that pino adds.redactreplaces the value ofemailorsignup.emailif someone logs an email address by mistake (see the redaction page). -
jobLogputs the same four fields on every line about a job:correlationId,jobId,userId, andattempt. It uses a child logger, whose fixed fields appear on every line it writes (see child loggers). -
enqueueSignupis the request side. It makes the correlation ID, a string that names one request, and puts it inside the job's data. The data travels with the job in Redis, so the ID survives retries, a worker restart, parking, and replay. The log line comes beforequeue.add. My first version logged after the add, and a test I wrote for this post showed a running worker writingjob startedbeforeadding job. -
enqueueSignupalso checks for an existing job. The job ID is the same for the same sign-up (Part 6), so a second request adds nothing. The line says so and names the first request. -
withLogswraps a handler. It writes a line when an attempt starts and another when it ends, with the attempt number and the duration. A failed attempt is awarnbecause BullMQ will try again. -
logWorkerEventscovers what the handler cannot see. When a job fails for the last time, it writes anerror. It also logs a stalled job and a worker error. The BullMQ documentation warns that a worker without anerrorlistener may stop processing when an error is emitted.
The levels follow one rule: error means a person has to look.
| Level | Message | Meaning |
|---|---|---|
info | adding job, job started, job done | Normal work |
warn | job attempt failed, job stalled | Something goes wrong, and BullMQ handles it |
error | job gave up, worker error | A person has to look |
Read one request's story
Run the same 20 sign-ups as Part 7: two with a bad address, and the provider down for three users until it recovers. The demo runs the worker with five jobs at a time, parks the failed jobs, and replays the ones that can still work. The logs go into a list, and the demo reads them back.
The 20 sign-ups write 83 lines: 67 info, 11 warn, and 5 error. That is about four lines per sign-up. The five error lines are the five jobs that gave up, each with the request ID, the user, and the reason, so "what needs a person?" is one filter on one field. None of the 83 lines contains an email address.
Now follow one request. The sign-up of user_12 was queued as req-0012, hit the outage, and failed three times. Filtering the logs on that ID gives 10 lines:
| Level | Message | Attempt | Reason |
|---|---|---|---|
info | adding job | ||
info | job started | 1 | |
warn | job attempt failed | 1 | 503 service unavailable |
info | job started | 2 | |
warn | job attempt failed | 2 | 503 service unavailable |
info | job started | 3 | |
warn | job attempt failed | 3 | 503 service unavailable |
error | job gave up | 3 | 503 service unavailable |
info | job started | 1 | |
info | job done | 1 |
Read in order; the lines show what happened. Three attempts, numbered 1 to 3, fail with the same 503. Then job gave up, at level error. Then a job started with attempt 1 again: that is the replay from Part 7, and that line carries the same ID because replay copies the job's data, ID included. A test I wrote for this post checks that the ID stays the same. The last line is job done. Without the ID, those 10 lines would sit among 73 others from other sign-ups.
The demo uses IDs such as req-0012, so its output is the same every time. In real code, enqueueSignup makes a random UUID.
When a worker dies
Part 6 killed a worker in the middle of a job, and a second worker finished it. Nothing was logged. crash.ts repeats that test with the logging in place. It starts worker-1, which sends the email for user_2 and then kills itself. When worker-1 is gone, the demo starts worker-2. This is the story of req-0002:
| Worker | Level | Message | Attempt |
|---|---|---|---|
api | info | adding job | |
worker-1 | info | job started | 1 |
worker-2 | warn | job stalled: its worker stopped renewing the lock | |
worker-2 | info | job started | 1 |
worker-2 | info | job done | 1 |
worker-2 writes the stalled line first, then starts the job: attempt 1 again, from a different worker. That is what "ran twice" looks like in the logs. The BullMQ documentation describes the cause: a worker stops renewing the lock on its job, the job goes back to waiting, and another worker can process it. The attempt number is 1 on both lines, so the stall did not count as a failed attempt in this run. The email count at the end is one per user because the key from Part 5 reaches the provider: the job ran twice, and the email went out once.
The stalled line has no correlation ID. BullMQ 6.5.3 declares the event in its type definitions with two arguments, the job ID and the state the job was in, so that is all the line can carry. story matches such a line by its job ID, which is why every other line carries jobId too.
Keep email addresses out
Logs are copied, searched, and kept longer than most people expect, so they should not hold personal data. Two things leak it here. The first is a field: someone logs the whole sign-up, and the email goes with it. redact covers that. The second is a string. The fake provider puts the address in its error message: 400 invalid address: user4@example,com. Logging error.message as it is would write the address into the job attempt failed and job gave up lines.
Redaction works on keys, not on text inside a string, so reasonOf removes the address from the message by hand. A test I wrote for this post runs the bad-address sign-up and checks that no line contains an @. The demo's second line reports the same count: 0.
What this does not fix
Where the lines go. The logger writes to process.stdout. Collecting, searching, and keeping the lines depend on your platform, so they are not built here.
Volume. Every attempt writes two lines, and each sign-up in the demo writes about four. At real traffic, that is a cost, and I did not measure it.
The duplicate check is not atomic. enqueueSignup looks for the job and then adds it. Two requests at the same instant could both write adding job while BullMQ keeps one job. I did not test that.
Part 7 still stores the raw message. The reason of a dead queue entry is the original error message, so the address of a rejected sign-up sits in Redis. This post cleans the logs, not that field. reasonOf also knows only this sign-up's email, so another kind of personal data in an error message would need its own rule.
One service. If a request crosses several services, the ID has to travel with it, for example in an HTTP header, and each service has to log it. The fake provider does not receive the ID either. I did not build or test that.
Takeaways
- A usable log line is one JSON object with the same fields every time. Put the job ID, the user, and the attempt on every line, and one sign-up is one filter away.
- Make the correlation ID at the request and put it in the job's data. It then follows the job through retries, a crash, parking, and replay.
- Log what changes and what happens next: started, failed, gave up, stalled. Keep
errorfor what needs a person (5 of 83 lines here), and keep personal data out of every line, error messages included.
Try it
This is a teaching version. A more complete implementation comes later in the series. You need Node 22, pnpm, and Docker. Use the folder from Part 7. The new code needs docker-compose.yml, signup-queue.ts, and emails.ts from Part 6, and provider.ts and dead-letter.ts from Part 7. Add pino:
pnpm add pino Save logging.ts from above next to them. Then save story.ts, which reads the logs back:
const LEVELS: Record<number, string> = { 30: "info", 40: "warn", 50: "error" }; type Entry = Record<string, any>; /** Every line is JSON, so a line can be read back as an object. */ export const parse = (lines: string[]): Entry[] => lines.map((line) => JSON.parse(line)); /** All the lines of one request, in the order they were written. A line with no correlation ID is matched by job ID. */ export function story(entries: Entry[], correlationId: string): Entry[] { const jobIds = new Set(entries.filter((entry) => entry.correlationId === correlationId).map((entry) => entry.jobId)); return entries.filter((entry) => entry.correlationId === correlationId || (entry.correlationId === undefined && jobIds.has(entry.jobId))); } /** Print some entries as a table. */ export const show = (entries: Entry[], columns: string[]) => console.table(entries.map((entry) => Object.fromEntries(columns.map((column) => [column, column === "level" ? LEVELS[entry.level] : entry[column] ?? ""])))); Save demo.ts, which runs the same 20 sign-ups as Part 7 with the logging in place:
import { Worker } from "bullmq"; import { connection, createSignupQueue, makeSignups, type Signup } from "./signup-queue.ts"; import { closeEmails, forgetEmails } from "./emails.ts"; import { FakeProvider } from "./provider.ts"; import { classify, createDeadQueue, parkFailedJobs, replay } from "./dead-letter.ts"; import { createLogger, enqueueSignup, logWorkerEvents, withLogs } from "./logging.ts"; import { parse, show, story } from "./story.ts"; const SIGNUPS = 20; const BAD_ADDRESSES = ["user_4", "user_9"]; // typos the provider rejects for good const OUTAGE = ["user_12", "user_13", "user_14"]; // the provider is down for these until it recovers const run = "signups-logs"; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** The logger writes into a list here, so the demo can read its own logs back. */ const lines: string[] = []; const log = createLogger({ write: (line: string) => void lines.push(line) }, "demo"); const queue = createSignupQueue(run); const dead = createDeadQueue(run); await queue.obliterate({ force: true }); await dead.obliterate({ force: true }); await forgetEmails(run); const provider = new FakeProvider(run); provider.down = new Set(OUTAGE); const worker = new Worker<Signup>( run, withLogs(log, async (job) => { try { await provider.send(job.data); } catch (error) { throw classify(error); } }), { connection, concurrency: 5 }, // five jobs at a time, so their lines are mixed together ); logWorkerEvents(worker, log); parkFailedJobs(worker, dead); // The demo uses req-0001, req-0002 and so on, so the output is the same every time. Real code leaves the default: a random UUID. let requests = 0; const newId...