Sandro Dezerio

Rate-limited, delayed, and scheduled jobs in Node.js

Part 9 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 8. 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.

So far, every job in this series ran as soon as a worker was free. Real work often has to wait. The email provider says “too many requests, slow down.” A reminder should go out a day after the sign-up, not now. The dead-letter check from Part 7 should run every few minutes, and Part 7 left that to a cron entry. This post covers all three with BullMQ: a rate limiter, delayed jobs, and job schedulers. Each one starts with what breaks.

A burst meets a quota

Email providers limit how many requests an account can send per second. When you go over, they answer with HTTP 429, Too Many Requests, often with a Retry-After header that says how long to wait (see MDN on 429). The fake provider from Part 7 had no limit, so this post adds one. LimitedProvider accepts 5 requests in any second and answers the sixth with a 429 and the time until a slot frees up.

Now 20 sign-ups arrive at once, as they would after a launch email. One worker runs five jobs at a time (Part 2), with the three attempts and the backoff from Part 6. Without a limit, the first five requests go through, and the rest of the burst hits the 429. The retries come back within a second or two and hit it again. In one run, 11 users got their welcome email, and 9 jobs gave up after 39 rejected requests. In 15 runs of the same demo, between 5 and 9 of the 20 jobs gave up. The numbers move because the backoff has random jitter.

Every 429 used up one of the job’s three attempts. Nothing was wrong with those sign-ups. The provider only asked to wait.

The limiter, and why it is not enough

BullMQ has a rate limiter on the worker: limiter: { max: 5, duration: 1000 } means at most 5 jobs per second. The documentation says the limit is global for the queue, so ten workers with that setting still process 5 jobs per second in total. Jobs that wait for the limiter stay in the waiting state.

With the limiter at 5 per second, all 20 emails went out in every run. In 7 of the 15 runs, the provider still answered at least one 429, up to 9 in one run. The limiter and the provider count different seconds. BullMQ starts its window when it takes the first job, and the provider counts the last 1,000 ms from each request. A few requests at the edge of one window and the start of the next can land inside the same provider second. Retries absorbed those 429s here, but each one still used an attempt.

Now suppose another service starts sending with the same provider account and uses 2 of the 5 requests per second, so this queue has 3. The limiter does not know that. With the same limiter and a quota of 3, between 0 and 3 jobs gave up per run, and at least one gave up in 14 of the 15 runs.

A 429 is not a failure

The fix is to treat a 429 as “wait,” not as a failed attempt. BullMQ has a way to say exactly that: pause the queue for a given time, then throw a special error that puts the job back. Here is the new file:

import { Worker, type Job, type Queue } from "bullmq";
import { FakeProvider } from "./provider.ts";
import type { Signup } from "./signup-queue.ts";

/** The provider says: too many requests, try again later (HTTP 429 with a Retry-After header). */
export class TooManyRequestsError extends Error {
  constructor(readonly retryAfterMs: number) {
    super(`429 too many requests, retry after ${retryAfterMs} ms`);
  }
}

/** The provider from Part 7, with a quota: at most `max` requests in any `windowMs`. */
export class LimitedProvider extends FakeProvider {
  rejected = 0; // requests answered with a 429
  private recent: number[] = []; // when the accepted requests arrived

  constructor(run: string, private max: number, private windowMs: number) {
    super(run);
  }

  async send(signup: Signup): Promise<void> {
    const now = Date.now();
    this.recent = this.recent.filter((time) => now - time < this.windowMs);
    if (this.recent.length >= this.max) {
      this.calls++;
      this.rejected++;
      throw new TooManyRequestsError(this.recent[0] + this.windowMs - now); // when the oldest request leaves the window
    }
    this.recent.push(now);
    await super.send(signup);
  }
}

/** A 429 is not a failure of this job. Pause the whole queue for as long as the provider asks, and put the job back. */
export const waitOnTooManyRequests =
  <T>(queue: Queue<T>, handler: (job: Job<T>) => Promise<void>) =>
  async (job: Job<T>): Promise<void> => {
    try {
      await handler(job);
    } catch (error) {
      if (!(error instanceof TooManyRequestsError)) throw error;
      await queue.rateLimit(error.retryAfterMs); // no worker on this queue takes a job until then
      throw Worker.RateLimitError(); // BullMQ moves the job back to waiting, and the attempt does not count
    }
  };
TypeScript

Here is what each part does:

  • TooManyRequestsError carries the wait. A real client would read it from the Retry-After header. The fake provider computes it: the time until its oldest request leaves the window.
  • LimitedProvider is the fake provider with a quota. It keeps the times of the accepted requests from the last second and rejects a request when there are already max of them.
  • waitOnTooManyRequests wraps a handler. Any other error goes through unchanged, so Part 7’s dead-letter handling still sees it. On a 429, queue.rateLimit stops every worker on the queue from taking new jobs for that long, and Worker.RateLimitError() tells BullMQ that this was a rate limit and not a failure. The rate-limiting page shows the same pair withworker.rateLimit, which the BullMQ 6.5.3 type definitions mark as deprecated in favor of queue.rateLimit.

The documentation says the error moves the job back to waiting without consuming an attempt, but it says so only in a note for the Python version. So I tested it in Node: a test I wrote for this post makes the provider answer 429 five times to a job with three attempts. The job completes, no failed event fires, and attemptsMade is 1.

Here are the four setups side by side, from one run of burst.ts:

SetupQuotaSentGave up429sSeconds
No limiter5/s119392.5
Limiter5/s20003.0
Limiter3/s182125.9
Limiter, wait on 4293/s200126.1

In all 15 runs, the last setup sent all 20 emails, and no job gave up. It is not free: the limiter still lets 5 jobs through per second, so the provider rejects 2 of them each second, between 12 and 15 requests per run. Those requests cost nothing in attempts, but they still reach the provider. Set the limiter to the quota you really have, and keep the 429 handling for the day the quota changes.

A job that runs later

A sign-up sends a welcome email now. Suppose the product also wants a second email a day later: “finish your profile.” It should not go out if the user finishes the profile first.

A setTimeout in the request handler would lose every waiting reminder on a restart, the same problem Part 6 fixed for the queue itself. BullMQ keeps a delayed job in Redis until its time comes. Here is the second new file:

import type { Queue } from "bullmq";
import type { Logger } from "pino";
import type { Signup } from "./signup-queue.ts";
import type { TracedSignup } from "./logging.ts";

const reminderId = (signup: Signup) => `profile-reminder-${signup.userId}`;

/** A second email, later. The job waits in Redis in the delayed set, and it keeps the request's correlation ID. */
export async function addReminder(queue: Queue<Signup>, log: Logger, signup: TracedSignup, delayMs: number): Promise<void> {
  const jobId = reminderId(signup);
  log.info({ correlationId: signup.correlationId, jobId, userId: signup.userId, delayMs }, "adding delayed job");
  await queue.add("profile-reminder", signup, { jobId, delay: delayMs, removeOnFail: { count: 100 } });
}

/** The user finished the profile, so the reminder has no reason to go out. Remove it while it still waits. */
export async function cancelReminder(queue: Queue<Signup>, log: Logger, signup: TracedSignup): Promise<boolean> {
  const job = await queue.getJob(reminderId(signup));
  const removed = (await job?.isDelayed()) === true;
  if (removed) await job!.remove();
  log.info({ correlationId: signup.correlationId, jobId: reminderId(signup), userId: signup.userId, removed }, "cancel delayed job");
  return removed;
}

/** Run a check every `everyMs`. Upsert means create or update: every copy of the app can call it at start-up, and Redis keeps one schedule. */
export const scheduleCheck = (queue: Queue, name: string, everyMs: number) => queue.upsertJobScheduler(name, { every: everyMs }, { name });
TypeScript
  • addReminder adds a job with delay. It names the job after the user, as Part 6 did for the welcome email, so the same reminder added twice is one job. The job data is the sign-up with its correlation ID from Part 8, so the reminder’s log lines belong to the same request. The log line comes before the add, for the same reason as in Part 8.
  • cancelReminder removes the reminder only while it is still delayed. A reminder that already started or finished is left alone, and the function returns false.
  • scheduleCheck is for the next section.

In the demo, the delay is 2 seconds instead of a day. Two users sign up. The story of req-0001, filtered with story from Part 8, now covers two jobs:

AtMessageJob ID
0.0 sadding jobwelcome-email-user_1
0.0 sadding delayed jobprofile-reminder-user_1
0.0 sjob startedwelcome-email-user_1
0.0 sjob donewelcome-email-user_1
2.0 sjob startedprofile-reminder-user_1
2.0 sjob doneprofile-reminder-user_1

The reminder started 2 seconds later and carried the same ID. The second user, user_2, finished the profile after one second, so the story of req-0002 ends with cancel delayed job at 1.0 s, and that user got one email instead of two.

Three things about delays are worth knowing. First, the documentation says a delayed job is not guaranteed to run at the exact time, because it depends on how busy the workers are. Second, the delay option in the type definitions notes that producers and workers need synchronized clocks for accurate delays. Third, the data in a delayed job is a copy from the moment it was added. If the user changes the email address during that day, the reminder goes to the old one, unless the handler reads fresh data when it runs.

A check that runs on a timer

Part 7 built checkDeadLetters and left the schedule open. The simple version is a setInterval at start-up. It works with one copy of the app. Once you run two copies, each one runs its own timer.

The demo puts one sign-up in the dead queue with a failure time two minutes ago, older than the 60-second limit from Part 7. Then it runs the check every second from two copies for 3.5 seconds. WithsetInterval, the team gets 6 alerts, two at each second: 1, 1, 2, 2, 3, 3.

BullMQ’s job schedulers store the schedule in Redis. scheduleCheck calls upsertJobScheduler. The documentation explains that upsert, unlike add, creates or updates the scheduler without duplicates. Both copies call it at start-up, and both run a worker for it. Redis keeps 1 scheduler, and the check runs once per second: 4 alerts, at 0, 1, 2, and 3 seconds. The first one comes right away because the first job of an every scheduler has no delay.

The same page notes two limits. The scheduler creates the next job only when the last one begins processing, and jobs can come less often than the interval when the workers are busy. For a dead-letter check, that is fine. For a job that must run at an exact time, it is not.

What this does not fix

Real quotas are messier. The fake provider counts a sliding second. Real providers count per second, per minute, or per day, sometimes per API key and sometimes per account, and some do not send Retry-After. Read the header your provider sends. I did not build a client that parses it.

One limiter per queue. Two queues that call the same provider each have their own limiter, and together they can go over the quota. Put the calls to one provider behind one queue, or give each queue its share.

The keys from Part 5 must outlive the delay. Part 5 said an idempotency key must live longer than the retry window. A reminder that waits a day stretches that window to a day, plus its retries.

What I did not test. The two copies of the app in the demo are two timers and two workers in one process, not two machines. I did not test clocks that disagree, a Redis restart while jobs wait in the delayed set, or a scheduler with a cron pattern.

Takeaways

  1. A 429 means “wait,” not “failed.” Pause the queue withqueue.rateLimit, throw Worker.RateLimitError(), and the job goes back to waiting without losing an attempt.
  2. A limiter set at the provider’s quota still drew 429s in 7 of 15 runs, because the two count different seconds. Use the limiter to stay near the quota and the 429 handling to stay safe.
  3. Work that runs later belongs in Redis, not in a setTimeout or a setInterval. A delayed job survives a restart and keeps its correlation ID, and an upserted job scheduler runs once per interval, however many copies of the app start it.

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 8: the new code needs docker-compose.yml, signup-queue.ts, and emails.ts from Part 6, provider.ts, dead-letter.ts, and monitor.ts from Part 7, and logging.ts and story.ts from Part 8. There is no new package to add.

Save rate-limit.ts and schedule.ts from above next to them. Then saveburst.ts, which sends the same 20 sign-ups four ways:

import { Worker, type Job } from "bullmq";
import { connection, createSignupQueue, makeSignups, type Signup } from "./signup-queue.ts";
import { closeEmails, emailsPerUser, forgetEmails } from "./emails.ts";
import { signupJobOptions } from "./dead-letter.ts";
import { LimitedProvider, waitOnTooManyRequests } from "./rate-limit.ts";

const SIGNUPS = 20;

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

let runs = 0;
type Setup = { label: string; quota: number; limiter?: { max: number; duration: number }; handle429: boolean };

/** Add 20 sign-ups at once and let one worker (five jobs at a time) send them. */
async function burst({ label, quota, limiter, handle429 }: Setup) {
  const run = `signups-burst-${++runs}`;
  const queue = createSignupQueue(run);
  await queue.obliterate({ force: true });
  await forgetEmails(run);
  const provider = new LimitedProvider(run, quota, 1000); // quota: requests per second
  const send = async (job: Job<Signup>) => provider.send(job.data);
  const worker = new Worker<Signup>(run, handle429 ? waitOnTooManyRequests(queue, send) : send, { connection, concurrency: 5, limiter });
  worker.on("error", () => {});

  const started = Date.now();
  await queue.addBulk(makeSignups(SIGNUPS).map((signup) => ({ name: "welcome-email", data: signup, opts: signupJobOptions(signup) })));
  for (;;) {
    const { waiting, active, delayed, prioritized } = await queue.getJobCounts("waiting", "active", "delayed", "prioritized");
    if (waiting + active + delayed + prioritized === 0) break;
    await sleep(50);
  }
  const seconds = ((Date.now() - started) / 1000).toFixed(1);
  const { failed } = await queue.getJobCounts("failed");
  const sent = Object.values(await emailsPerUser(run)).reduce((sum, count) => sum + count, 0);
  await worker.close();
  await queue.obliterate({ force: true });
  await forgetEmails(run);
  await queue.close();
  return { setup: label, quota: `${quota}/s`, sent, "gave up": failed, "429s": provider.rejected, seconds };
}

const results = [];
const limiter = { max: 5, duration: 1000 }; // BullMQ: at most 5 jobs per second for this queue
results.push(await burst({ label: "no limiter", quota: 5, handle429: false }));
results.push(await burst({ label: "limiter", quota: 5, limiter, handle429: false }));
// Another service now sends with the same account and uses 2 of the 5 requests per second.
results.push(await burst({ label: "limiter", quota: 3, limiter, handle429: false }));
results.push(await burst({ label: "limiter + wait on 429", quota: 3, limiter, handle429: true }));
console.table(results);
await closeEmails();
TypeScript

And save later.ts, which runs the reminder and the scheduled check:

import { Queue, Worker } from "bullmq";
import { connection, createSignupQueue, makeSignups, type Signup } from "./signup-queue.ts";
import { closeEmails, emailsPerUser, forgetEmails, sendEmail } from "./emails.ts";
import { FakeProvider } from "./provider.ts";
import { createDeadQueue } from "./dead-letter.ts";
import { checkDeadLetters } from "./monitor.ts";
import { createLogger, enqueueSignup, logWorkerEvents, withLogs } from "./logging.ts";
import { parse, show, story } from "./story.ts";
import { addReminder, cancelReminder, scheduleCheck } from "./schedule.ts";

const run = "signups-later";
const REMINDER_DELAY = 2000; // in a real app, a day: 24 * 60 * 60 * 1000
const CHECK_EVERY = 1000; // in a real app, every few minutes
const WATCH = 3500; // how long part 2 watches the checks run

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const lines: string[] = [];
const log = createLogger({ write: (line: string) => void lines.push(line) }, "demo");

// Part 1: a reminder two seconds after the sign-up, with the same correlation ID.
const queue = createSignupQueue(run);
await queue.obliterate({ force: true });
await forgetEmails(run);
const provider = new FakeProvider(run);
const worker = new Worker<Signup>(
  run,
  withLogs(log, async (job) => {
    if (job.name === "profile-reminder") await sendEmail(run, job.data.userId, `profile-reminder:${job.data.userId}`); // its own key
    else await provider.send(job.data);
  }),
  { connection },
);
logWorkerEvents(worker, log);

let requests = 0;
const newId = () => `req-${String(++requests).padStart(4, "0")}`;
const signups = [];
for (const signup of makeSignups(2)) {
  const correlationId = await enqueueSignup(queue, log, signup, newId);
  signups.push({ ...signup, correlationId });
  await addReminder(queue, log, signups.at(-1)!, REMINDER_DELAY);
}
await sleep(1000);
await cancelReminder(queue, log, signups[1]); // user_2 finished the profile after one second
for (;;) {
  const { waiting, active, delayed } = await queue.getJobCounts("waiting", "active", "delayed");
  if (waiting + active + delayed === 0) break;
  await sleep(50);
}
await worker.close();

const entries = parse(lines);
const start = entries[0].time;
const timed = (list: typeof entries) => list.map((entry) => ({ ...entry, at: `${((entry.time - start) / 1000).toFixed(1)} s` }));
console.log("The story of req-0001 (user_1):");
show(timed(story(entries, "req-0001")), ["at", "msg", "jobId"]);
console.log("The story of req-0002 (user_2 finished the profile after one second):");
show(timed(story(entries, "req-0002")), ["at", "msg", "jobId"]);
console.log("Emails sent per user:", await emailsPerUser(run));

// Part 2: the dead-letter check from Part 7, run every second by two copies of the app.
const dead = createDeadQueue(run);
await dead.obliterate({ force: true });
const failedAt = Date.now() - 120_000; // one sign-up has been parked for two minutes
await dead.add("welcome-email", { userId: "user_4", email: "<email>", reason: "400 invalid address", attempts: 1, failedAt, jobId: "welcome-email-user_4" });
const limits = { maxDepth: 3, maxAgeMs: 60_000 };
let alerts: string[] = []; // when each alert fired, in whole seconds from the start of the watch
let watchStart = 0;
const alert = () => void alerts.push(String(Math.round((Date.now() - watchStart) / 1000)));

// (a) Each copy starts its own timer.
watchStart = Date.now();
const timers = [1, 2].map(() => setInterval(() => void checkDeadLetters(dead, limits, alert), CHECK_EVERY));
await sleep(WATCH);
timers.forEach(clearInterval);
console.log(`\nsetInterval in 2 copies: ${alerts.length} alerts in ${WATCH / 1000} s, at ${alerts.join(", ")} s.`);

// (b) Each copy upserts the same job scheduler and runs a worker for it.
alerts = [];
const maintenance = new Queue(`${run}-maintenance`, { connection });
await maintenance.obliterate({ force: true });
const checkers = [];
watchStart = Date.now();
for (const copy of [1, 2]) {
  await scheduleCheck(maintenance, "dead-letter-check", CHECK_EVERY);
  checkers.push(new Worker(maintenance.name, () => checkDeadLetters(dead, limits, alert), { connection }));
}
await sleep(WATCH);
await Promise.all(checkers.map((checker) => checker.close()));
console.log(`Job scheduler in 2 copies: ${alerts.length} alerts in ${WATCH / 1000} s, at ${alerts.join(", ")} s. Schedulers in Redis: ${await maintenance.getJobSchedulersCount()}.`);

await maintenance.removeJobScheduler("dead-letter-check");
for (const q of [queue, dead, maintenance]) {
  await q.obliterate({ force: true });
  await q.close();
}
await forgetEmails(run);
await closeEmails();
TypeScript

Start Redis and run both:

docker compose up -d
pnpm exec tsx burst.ts
pnpm exec tsx later.ts
Terminal

burst.ts takes about 20 seconds. Your numbers will differ a little from run to run because of the jitter, but the shape stays the same. One run printed:

┌─────────┬─────────────────────────┬───────┬──────┬─────────┬──────┬─────────┐
│ (index) │ setup                   │ quota │ sent │ gave up │ 429s │ seconds │
├─────────┼─────────────────────────┼───────┼──────┼─────────┼──────┼─────────┤
│ 0       │ 'no limiter'            │ '5/s' │ 11   │ 9       │ 39   │ '2.5'   │
│ 1       │ 'limiter'               │ '5/s' │ 20   │ 0       │ 0    │ '3.0'   │
│ 2       │ 'limiter'               │ '3/s' │ 18   │ 2       │ 12   │ '5.9'   │
│ 3       │ 'limiter + wait on 429' │ '3/s' │ 20   │ 0       │ 12   │ '6.1'   │
└─────────┴─────────────────────────┴───────┴──────┴─────────┴──────┴─────────┘
Output

later.ts takes about 10 seconds and prints:

The story of req-0001 (user_1):
┌─────────┬─────────┬──────────────────────┬───────────────────────────┐
│ (index) │ at      │ msg                  │ jobId                     │
├─────────┼─────────┼──────────────────────┼───────────────────────────┤
│ 0       │ '0.0 s' │ 'adding job'         │ 'welcome-email-user_1'    │
│ 1       │ '0.0 s' │ 'adding delayed job' │ 'profile-reminder-user_1' │
│ 2       │ '0.0 s' │ 'job started'        │ 'welcome-email-user_1'    │
│ 3       │ '0.0 s' │ 'job done'           │ 'welcome-email-user_1'    │
│ 4       │ '2.0 s' │ 'job started'        │ 'profile-reminder-user_1' │
│ 5       │ '2.0 s' │ 'job done'           │ 'profile-reminder-user_1' │
└─────────┴─────────┴──────────────────────┴───────────────────────────┘
The story of req-0002 (user_2 finished the profile after one second):
┌─────────┬─────────┬──────────────────────┬───────────────────────────┐
│ (index) │ at      │ msg                  │ jobId                     │
├─────────┼─────────┼──────────────────────┼───────────────────────────┤
│ 0       │ '0.0 s' │ 'adding job'         │ 'welcome-email-user_2'    │
│ 1       │ '0.0 s' │ 'adding delayed job' │ 'profile-reminder-user_2' │
│ 2       │ '0.0 s' │ 'job started'        │ 'welcome-email-user_2'    │
│ 3       │ '0.0 s' │ 'job done'           │ 'welcome-email-user_2'    │
│ 4       │ '1.0 s' │ 'cancel delayed job' │ 'profile-reminder-user_2' │
└─────────┴─────────┴──────────────────────┴───────────────────────────┘
Emails sent per user: { user_1: 2, user_2: 1 }

setInterval in 2 copies: 6 alerts in 3.5 s, at 1, 1, 2, 2, 3, 3 s.
Job scheduler in 2 copies: 4 alerts in 3.5 s, at 0, 1, 2, 3 s. Schedulers in Redis: 1.
Output

Change the quota or the limiter in burst.ts, or REMINDER_DELAY and CHECK_EVERY in later.ts, and see what moves. When you are done, docker compose down stops Redis.

Previous: Structured logs and correlation IDs for Node.js job queues (Part 8).

Next: Part 10 (coming soon) adds an LLM step to a job: validating its answer, what a retry costs, and checkpoints.


Posted

in

by

Comments

One response to “Rate-limited, delayed, and scheduled jobs in Node.js”

  1. […] for 2 seconds. That is fine for short waits. For waits of minutes, you want delayed jobs, which Part 9 […]

Leave a Reply

Your email address will not be published. Required fields are marked *