To send SMS from a BullMQ worker, enqueue one job per message, call your SMS API from the worker with a timeout, and reuse the job id as the idempotency key so a retry never texts anyone twice. Let BullMQ handle attempts, backoff and the rate limit, and decide per status code whether a failure is worth another try.

We make Ready, so the example uses our REST API and only the request shape we document. The pattern works with any provider that accepts an idempotency key. It assumes Node 18 or later (for built-in fetch) and a recent BullMQ with a Redis instance behind it.

Why a queue sits in front of the send

Calling the SMS API inline from a request handler ties your user's click to a carrier-facing network call. A queue breaks that link. The handler writes a job and returns, and a worker sends at a pace you control.

You get three things. Retries that survive a deploy, because the job lives in Redis rather than in a process. A single place to enforce a rate limit across every worker. And a durable record of what you tried to send. If you're designing this for many customers at once, our guide to SMS queue design for platforms covers fairness between tenants, which this post leaves out.

Add a job with a stable id

The job id is the spine of the whole design. Use your own message id, the primary key of the row you wrote, not a random value generated at enqueue time.

import { Queue } from 'bullmq';

const connection = { host: process.env.REDIS_HOST, port: 6379 };

export const smsQueue = new Queue('sms', { connection });

export async function enqueueSms(message) {
  // message.id is your own row id, for example "msg_1042"
  return smsQueue.add(
    'send',
    { to: message.to, body: message.body },
    {
      jobId: message.id,
      attempts: 5,
      backoff: { type: 'exponential', delay: 2000, jitter: 0.5 },
      removeOnComplete: { age: 3600, count: 1000 },
      removeOnFail: { age: 7 * 24 * 3600 },
    },
  );
}

Two things here earn their place. First, BullMQ ignores a second add with a jobId that already exists, so a double click or a retried HTTP handler doesn't create a second job. Second, the id doesn't change across attempts, which makes it a good idempotency key. Avoid colons and plain integers in custom ids, since BullMQ restricts both.

One catch: completed jobs are removed on the schedule above, and after removal the same id can be enqueued again. If duplicates over a longer window matter, keep a unique constraint on your own message table as well.

The worker, with a rate limiter

The limiter caps how many jobs start per time window across all workers on the queue, because the counter lives in Redis.

import { Worker, UnrecoverableError } from 'bullmq';

const API = 'https://api.tryready.com';

async function sendOnce(job) {
  const res = await fetch(`${API}/v1/messages`, {
    method: 'POST',
    headers: {
      'X-API-Key': process.env.READY_API_KEY,
      'Content-Type': 'application/json',
      'Idempotency-Key': job.id,
    },
    body: JSON.stringify({
      to: job.data.to,
      body: job.data.body,
      consent_attested: true,
    }),
    signal: AbortSignal.timeout(15000),
  });
  return res;
}

export const worker = new Worker(
  'sms',
  async (job) => {
    const res = await sendOnce(job);
    if (res.ok) return res.json();
    await handleFailure(worker, job, res);
  },
  {
    connection,
    concurrency: 10,
    limiter: { max: 20, duration: 1000 },
  },
);

concurrency is how many jobs one worker process runs at once. limiter is the ceiling on starts per second, shared by every process. Pick numbers from your provider's documented limits, not from this example. Start low and raise them while watching error rates.

Setting consent_attested: true is your statement that the recipient agreed to receive texts. Only send it when that's true for the contact in the job. Don't hardcode it blindly in production, read it from the consent record you keep.

Which failures to retry

Not every error deserves another attempt. A retry of a doomed request wastes a slot in your rate limit and delays good messages behind it.

OutcomeMeaningWhat the worker does
2xxAcceptedMark done
429You're sending too fastPause the queue for the Retry-After time, retry
5xx, timeout, network errorTheir side or the wire failedRetry with backoff, same key
408Request timed outRetry with backoff
Other 4xxThe request itself is wrongFail permanently, don't retry
409 QUIET_HOURS_BLOCKThe send fell in the recipient's quiet hoursDon't retry blindly, see below

The key point is the split between "try again" and "your request is bad." A 400 or 422 will fail identically on attempt five, so give up on the first.

Handling the failure branch

async function handleFailure(worker, job, res) {
  const text = await res.text();

  if (res.status === 429) {
    const wait = Number(res.headers.get('retry-after')) * 1000 || 5000;
    await worker.rateLimit(wait);
    throw Worker.RateLimitError();
  }

  if (res.status === 408 || res.status >= 500) {
    throw new Error(`retryable ${res.status}: ${text}`);
  }

  // Everything else is a problem with the request. Do not retry.
  throw new UnrecoverableError(`rejected ${res.status}: ${text}`);
}

worker.rateLimit(ms) tells BullMQ to hold the whole queue for that long, and throwing Worker.RateLimitError() puts this job back without counting it as a failed attempt. That's what you want for a 429: the slowdown applies to every job, not just this one.

Plain thrown errors count against attempts and use your backoff. UnrecoverableError skips the remaining attempts and moves the job straight to failed. For the exact error codes and bodies Ready returns, use the errors reference rather than guessing from status alone.

Quiet hours are not a transient error

When a text lands in the recipient's quiet hours, the API can answer 409 with QUIET_HOURS_BLOCK. Retrying in two seconds changes nothing. You have two sensible choices. Send the request with hold_until_allowed: true, so the text is held until the window opens, or fail the job and re-enqueue it with a delay computed from the time the window opens. Either way, treat it as a decision, not an outage.

Idempotency across attempts

Here's the failure the key protects you from. The worker sends, the API accepts and starts delivering, and then the response times out on the way back. From the worker's side that looks like a network error, so BullMQ retries. Without a key, the recipient gets two texts.

With Idempotency-Key set to the job id, the retry carries the same key, and a repeated request with the same key doesn't send a second text. Use the same value on every attempt, and don't derive it from the attempt number or the time.

The same logic covers a stalled job. If a worker process dies mid-send, BullMQ marks the job stalled and another worker picks it up. That second run sends the same key as the first.

Watching the queue

A few events tell you most of what you need:

  • worker.on('failed', ...) fires on every failed attempt. Log the job id, the attempt number and the status.
  • worker.on('completed', ...) is where you store the provider's message id against your own row.
  • Failed jobs kept by removeOnFail are your dead letter list. Review them, fix the cause and re-add them under a new id once you're sure the first never sent.

Alert on the failed count, not the retry count. A burst of retries during a provider blip is normal, and a pile of permanent failures is a bug in your data.

Where to go next

If you'd rather start with the plain request before adding a queue, see how to send SMS in Node.js. The API quickstart in the docs shows keys, a first send and webhook setup, and a test key lets you run this whole worker against simulated sends before you put a card on file.