Part 10 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 to Part 9. The numbers in this post come from running the code in it against a real Redis, with a fake email provider and a fake model, so you need no API key. Tested with Node 22, BullMQ 6.5.3, ioredis 6.0.0, zod 4.6.7, and Redis 7.

Every step in this series so far did cheap work: send an email, write a row. A step that calls a language model is different in three ways. It costs money on every call, even when the answer is useless. It answers in free text, so "valid JSON" is something you check, not something you get. And it can decline to answer.

A queue that retries blindly handles all three badly. This post adds an LLM step to the sign-up job: the model writes the welcome email. Each fix starts with what breaks.

Trusting the answer

The model sits behind a small interface. One method returns the text, a stop reason, and the tokens used. The demo uses a fake model that follows a script, so every failure repeats in every run. The queue is the one from Part 6: 3 attempts, jittered backoff, and jobs in Redis. Here is what the fake does with 20 sign-ups:

Users What happens
3 and 15 The first answer is a sentence, then the JSON.
7 and 19 The first answer is valid JSON with no subject.
11 The first answer is cut off at the output limit.
13 The model declines, every time.
17 The answer is a sentence, then the JSON, every time.
2, 5, 9, and 14 The model is fine, but the email provider answers 503 once.
The other 9 A good answer on the first call.

The first handler trusts the model. It parses the text and sends the email:

/** The "before": trust whatever the model says, and let BullMQ retry the whole job. */ const trusting = (model: FakeModel, meter: Meter, send: (signup: Signup, welcome: Welcome) => Promise<void>) => async (job: Job<Signup>) => { const response = await model.complete(promptFor(job.data)); meter.record(response.usage); await send(job.data, JSON.parse(response.text) as Welcome); // a valid JSON of the wrong shape goes straight through }; 

In one run, 31 model calls went out for 20 sign-ups. Eighteen emails were sent, and 2 of them had no subject. Users 7 and 19 got valid JSON of the wrong shape, so JSON.parse accepted it, and the email went out.

Users 3, 11, and 15 got text that did not parse, so the handler threw, and BullMQ retried the job. That worked, but only by accident. User 13 was refused 3 times in a row, and user 17 never got a clean answer in 3 tries, so both jobs gave up after 3 paid calls. And for users 2, 5, 9, and 14, the provider said 503, BullMQ retried the whole job, and the job asked the model for an email it already had.

Check the answer before anything uses it

Here is the first new file. It says what a usable answer looks like, and it names the two ways an answer can fail:

import { z } from "zod"; import type { ModelResponse } from "./model.ts"; import type { Signup } from "./signup-queue.ts"; /** What we accept as a welcome email. The limits are ours: a model can return valid JSON that is still no use. */ export const WelcomeSchema = z.object({ subject: z.string().min(1).max(80), body: z.string().min(20).max(1200), }); export type Welcome = z.infer<typeof WelcomeSchema>; /** The answer is unusable, but another call may give a usable one. */ export class MalformedAnswerError extends Error {} /** The model declined to answer. */ export class ModelRefusedError extends Error {} export const promptFor = (signup: Signup) => `Write a short welcome email for ${signup.userId}. Answer with JSON: {"subject": string, "body": string}.`; /** Check the answer before anything uses it. The stop reason comes first: a cut-off or refused answer is not worth parsing. */ export function parseWelcome(response: ModelResponse): Welcome { if (response.stopReason === "refusal") throw new ModelRefusedError("the model declined to answer"); if (response.stopReason === "max_tokens") throw new MalformedAnswerError("the answer was cut off at the output limit"); let json: unknown; try { json = JSON.parse(response.text); } catch { throw new MalformedAnswerError("the answer is not JSON"); } const result = WelcomeSchema.safeParse(json); if (!result.success) { throw new MalformedAnswerError(`the answer has the wrong shape: ${result.error.issues.map((issue) => issue.path.join(".")).join(", ")}`); } return result.data; } 
  • WelcomeSchema is our definition of usable. It is a zod schema with limits that are ours: a subject up to 80 characters, and a body of 20 to 1,200 characters.
  • Two error classes keep two cases apart. A malformed answer may be better on the next call. A refusal is a different case, and the next section says what to do with it.
  • parseWelcome reads the stop reason first. An answer that stopped at the output limit, or that was declined, is rejected without parsing the text.

The Anthropic API can also constrain the answer to a JSON schema, a feature called structured outputs. Use it if you can.

This post still validates, for three reasons. The rules in WelcomeSchema are yours, whatever the provider guarantees. The stop reasons (max_tokens and refusal among them) can end an answer early, and the part of the structured outputs page I read does not say what the JSON looks like then. And this code should keep working if you change providers.

A retry pays twice

Validation alone does not fix the 503. When the email step fails, BullMQ retries the whole job, and the job calls the model again. The fix is a checkpoint: once an answer is valid, keep it, and let a retry read it. Here is the second new file:

import { Redis } from "ioredis"; import { connection } from "./signup-queue.ts"; import { WelcomeSchema, type Welcome } from "./welcome.ts"; const DAY = 24 * 60 * 60; // seconds /** What the step needs from a store of paid answers. */ export type AnswerStore = Pick<Checkpoints, "get" | "save" | "countCall">; /** Answers we already paid for, kept in Redis. A retry reads them instead of calling the model again. */ export class Checkpoints { private redis = new Redis(connection); /** The TTL must outlive the longest retry window of the job (the same rule as the idempotency keys in Part 5). */ constructor(private run: string, private ttlSeconds = DAY) {} async get(key: string): Promise<Welcome | null> { const saved = await this.redis.get(`${this.run}:checkpoint:${key}`); return saved === null ? null : WelcomeSchema.parse(JSON.parse(saved)); } async save(key: string, welcome: Welcome): Promise<void> { await this.redis.set(`${this.run}:checkpoint:${key}`, JSON.stringify(welcome), "EX", this.ttlSeconds); } /** How many model calls this key has started, this one included. It survives retries, so it is a budget for the whole sign-up. */ async countCall(key: string): Promise<number> { const redisKey = `${this.run}:calls:${key}`; const calls = await this.redis.incr(redisKey); await this.redis.expire(redisKey, this.ttlSeconds); return calls; } async forget(): Promise<void> { const keys = await this.redis.keys(`${this.run}:*`); if (keys.length > 0) await this.redis.del(...keys); } close = () => this.redis.quit(); } 
  • get and save are the checkpoint. The answer lives in Redis under a key named after the sign-up, with an expiration time, so a retry on another worker finds it.
  • The TTL (time to live) must outlive the retries. This is the same rule as the idempotency keys in Part 5, and a delayed job from Part 9 stretches it.
  • countCall is a budget for the whole sign-up. It counts model calls across attempts, because a counter inside the handler would start from zero on every retry.

Now the step itself, and the handler that wraps it:

import { UnrecoverableError, type Job, type Queue } from "bullmq"; import type { Signup } from "./signup-queue.ts"; import type { ModelClient } from "./model.ts"; import type { Meter } from "./cost.ts"; import type { AnswerStore } from "./checkpoint.ts"; import { ModelRefusedError, parseWelcome, promptFor, type Welcome } from "./welcome.ts"; import { waitOnTooManyRequests } from "./rate-limit.ts"; export type StepDeps = { model: ModelClient; meter: Meter; checkpoints: AnswerStore; maxModelCalls: number; // the most paid calls one sign-up may use, across all its attempts (Infinity: no limit) }; const welcomeKey = (signup: Signup) => `welcome-text:${signup.userId}`; /** The text of the welcome email. A paid answer is kept, a useless one is not, and a refusal ends the job. */ export async function welcomeFor(signup: Signup, { model, meter, checkpoints, maxModelCalls }: StepDeps): Promise<Welcome> { const key = welcomeKey(signup); const saved = await checkpoints.get(key); if (saved) return saved; // paid for on an earlier attempt if ((await checkpoints.countCall(key)) > maxModelCalls) { throw new UnrecoverableError(`budget: ${maxModelCalls} model calls used and no usable answer`); } const response = await model.complete(promptFor(signup)); meter.record(response.usage); // the call is paid whether or not the answer is any good try { const welcome = parseWelcome(response); await checkpoints.save(key, welcome); return welcome; } catch (error) { // This post treats a refusal as final, so the attempts that are left are skipped. A malformed answer may be better next time. if (error instanceof ModelRefusedError) throw new UnrecoverableError(error.message); throw error; // MalformedAnswerError: BullMQ retries the job } } /** The handler: write the text, then send it. A 429 from the model pauses the queue, as in Part 9, and costs no attempt. */ export const welcomeHandler = ( queue: Queue<Signup>, deps: StepDeps, send: (signup: Signup, welcome: Welcome) => Promise<void>, ) => waitOnTooManyRequests(queue, async (job: Job<Signup>) => { const welcome = await welcomeFor(job.data, deps); await send(job.data, welcome); }); 
  • welcomeFor runs in a fixed order. It reads the checkpoint first, then checks the budget, then calls the model, then records the cost, then validates, and only then saves. The call is recorded before the answer is checked, because it is paid either way.
  • A refusal ends the job. UnrecoverableError is the error from Part 7 that makes BullMQ skip the attempts that are left. This post treats a refusal as final. The Anthropic docs suggest retrying on a fallback model. I did not build that.
  • A malformed answer is thrown as it is. BullMQ retries the job, and the next call may be clean.
  • welcomeHandler reuses Part 9. waitOnTooManyRequests wraps it, so a 429 from the model pauses the queue and costs no attempt. A test I wrote for this post makes the model answer 429 twice to a job with one attempt, and the job completes.

Four setups, side by side

The same 20 sign-ups ran four ways. Each row adds one fix to the row above it:

Setup Model calls Emails sent Unusable text Gave up USD per 1,000 sign-ups
Trust the answer 31 18 2 2 4.63
Validate 31 18 0 2 4.75
Checkpoint 27 18 0 2 4.13
Budget of 2 calls 26 18 0 2 3.96

The three fixes do three different things:

  • Validation did not save calls. It added 2 (users 7 and 19 now get a second call), and it removed 2 (user 13 is refused once, not three times). What it saved was 2 emails with no subject. The cost went up a little because the calls it added were full answers, and the calls it removed were short refusals.
  • The checkpoint saved 4 calls. They were the 4 retries after a provider 503.
  • The budget saved 1 call. User 17 never gets a clean answer, so the budget stops that job after 2 calls, not 3.

The 2 jobs that gave up are users 13 and 17. In your system, they would go to the dead-letter queue from Part 7, whose handler already treats an UnrecoverableError as the last attempt. I did not wire that into this demo.

What a call costs

The last column uses the prices on the Claude pricing page, which I read on 2026-12-06: Sonnet 5.5 costs $2 per million input tokens and $10 per million output tokens. Haiku 5.5 costs $0.10 and $0.50 for prompts up to 100,000 tokens, so it is 20 times cheaper on both.

The token counts are assumptions in model.ts: an 800-token prompt, and answers of 40 to 170 tokens. They are not measurements, so the dollar column is illustrative. The model calls, the unusable texts, and the failed jobs come from the run. With a real client, read the token counts from the usage field of each response, and feed them to the same meter.

One more cost hides in the client. By default, the Anthropic SDK retries a failed request up to two times for 429 and 5xx errors, among others. Put that under BullMQ's 3 attempts, and one job can send up to 9 requests instead of 3. I did not check which failed requests are billed.

The docs name a maxRetries option on the client, and a value of 0 turns the retries off. Set it, so the queue's attempts are the only retries. I did not run that against the API.

What this does not fix

The fake model is my script. Real models fail in other ways, and real prompts are larger than 800 tokens.

Valid is not the same as good. The schema cannot tell whether the email is polite, correct, or on brand.

The checkpoint has gaps. A crash between the model call and the save pays again. Two workers that start the same sign-up at the same time can both call the model. I did not test either case. The checkpoint also keeps the generated text in Redis until the TTL ends, so decide how long that should be.

A spend-cap 429 does not clear. The errors page says a 429 for a spend cap has no retry-after header and keeps failing until access resumes. waitOnTooManyRequests would pause the queue again and again. A real client needs a guard for that, and I did not build one.

The real API. Nothing here called it. The code knows only the ModelClient interface.

Takeaways

  1. Check an answer before anything uses it. A schema and the stop reason turned 2 emails with no subject into 0, and a refusal stopped retrying after 1 call.
  2. Save what you paid for. The checkpoint turned 31 model calls into 27, because a failed email no longer repeats the model call.
  3. Cap the calls per sign-up across attempts, and let only the queue retry. A stuck sign-up now costs 2 calls, not 3, and with the SDK's own retries off, the queue is the only one that retries.

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 9: the new code needs docker-compose.yml, signup-queue.ts, and emails.ts from Part 6, provider.ts and dead-letter.ts from Part 7, and rate-limit.ts from Part 9. One new package is needed:

pnpm add zod 

Save welcome.ts, checkpoint.ts, and llm-step.ts from above next to them. Then save model.ts, the interface and the fake:

/** What a model call costs us, in tokens. Every provider reports these two numbers with each answer. */ export type Usage = { inputTokens: number; outputTokens: number }; /** Why the model stopped: it finished, it hit the output limit, or it declined to answer. */ export type StopReason = "end_turn" | "max_tokens" | "refusal"; export type ModelResponse = { text: string; stopReason: StopReason; usage: Usage }; /** The only thing our code knows about the model. A real client would sit behind this, and so does the fake below. */ export interface ModelClient { complete(prompt: string): Promise<ModelResponse>; } /** What the fake model does on one call. */ export type Behavior = "ok" | "prose" | "no-subject" | "truncated" | "refusal"; // Assumptions of the demo, not measurements: a prompt with our style guide in it, and a short email as the answer. export const PROMPT_TOKENS = 800; const ANSWER_TOKENS: Record<Behavior, number> = { ok: 150, prose: 170, "no-subject": 120, truncated: 100, refusal: 40 }; const GOOD = { subject: "Welcome aboard", body: "Thanks for signing up. Your account is ready, and you can start right away." }; /** A model that follows a script: `behave(userId, n)` says what call number n for that user does. No network, no API key. */ export class FakeModel implements ModelClient { calls = 0; private perUser = new Map<string, number>(); constructor(private behave: (userId: string, call: number) => Behavior) {} async complete(prompt: string): Promise<ModelResponse> { this.calls++; const userId = /user_\d+/.exec(prompt)![0]; const call = (this.perUser.get(userId) ?? 0) + 1; this.perUser.set(userId, call); const behavior = this.behave(userId, call); const usage = { inputTokens: PROMPT_TOKENS, outputTokens: ANSWER_TOKENS[behavior] }; switch (behavior) { case "ok": return { text: JSON.stringify(GOOD), stopReason: "end_turn", usage }; case "prose": // valid JSON, wrapped in a sentence return { text: `Sure! Here is the email: ${JSON.stringify(GOOD)}`, stopReason: "end_turn", usage }; case "no-subject": // valid JSON, wrong shape return { text: JSON.stringify({ body: GOOD.body }), stopReason: "end_turn", usage }; case "truncated"Source:https://dev.to/sandrosd/adding-an-llm-step-to-a-nodejs-job-queue-3d6

Related posts