To send an SMS from Fastify, put the send logic in an encapsulated plugin, expose one schema-validated route that enqueues the text, and let a worker make the HTTP call. The worker is where retries live, so a slow carrier or a restart never loses a message or sends it twice.
We make Ready, so the examples call the Ready REST API and use only the request shape we document: POST /v1/messages with to, body and consent_attested. If you want the plain Node version without a framework first, start with our Node.js SMS guide.
The shape of the app
Fastify rewards small, encapsulated pieces, so we split this into three:
- A plugin that owns the queue and decorates the instance with
app.sms. - A route that validates input with JSON Schema and returns
202. - A worker process that calls the API and decides what to retry.
Install the pieces: npm i fastify fastify-plugin bullmq ioredis. You'll need Node 18 or later for the built-in fetch.
The plugin
import fp from 'fastify-plugin';
import IORedis from 'ioredis';
import { Queue } from 'bullmq';
import { randomUUID } from 'node:crypto';
export interface SmsJob { to: string; body: string; key: string }
declare module 'fastify' {
interface FastifyInstance {
sms: { enqueue(to: string, body: string): Promise<string> };
}
}
export default fp(async (app) => {
const connection = new IORedis(process.env.REDIS_URL!, { maxRetriesPerRequest: null });
const queue = new Queue<SmsJob>('sms', { connection });
app.decorate('sms', {
async enqueue(to: string, body: string) {
const key = randomUUID();
await queue.add('send', { to, body, key }, {
attempts: 5,
backoff: { type: 'exponential', delay: 1000 },
});
return key;
},
});
app.addHook('onClose', async () => {
await queue.close();
connection.disconnect();
});
}); Wrapping it in fastify-plugin lifts the decorator out of the plugin's own scope, so every route sees app.sms. The key is created once, when the job is added, and stored in the job data. That detail matters later.
The route
import Fastify from 'fastify';
import sms from './plugins/sms.js';
const app = Fastify({ logger: true });
await app.register(sms);
app.post<{ Body: { to: string; body: string } }>('/sms', {
schema: {
body: {
type: 'object',
required: ['to', 'body'],
additionalProperties: false,
properties: {
to: { type: 'string', pattern: '^\\+[1-9]\\d{7,14}$' },
body: { type: 'string', minLength: 1, maxLength: 1600 },
},
},
},
}, async (req, reply) => {
const id = await app.sms.enqueue(req.body.to, req.body.body);
return reply.code(202).send({ id });
});
await app.listen({ port: 3000, host: '0.0.0.0' }); Fastify compiles that schema once at startup, so bad numbers get a 400 before any of your code runs. to must be E.164. The 202 tells the caller the text is accepted, not delivered.
The worker
import IORedis from 'ioredis';
import { Worker, UnrecoverableError } from 'bullmq';
import type { SmsJob } from './plugins/sms.js';
const connection = new IORedis(process.env.REDIS_URL!, { maxRetriesPerRequest: null });
new Worker<SmsJob>('sms', async (job) => {
const res = await fetch('https://api.tryready.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': process.env.READY_API_KEY!,
'Idempotency-Key': job.data.key,
},
body: JSON.stringify({ to: job.data.to, body: job.data.body, consent_attested: true }),
signal: AbortSignal.timeout(15_000),
});
if (res.ok) return;
if (res.status === 429 || res.status >= 500) throw new Error(`retry ${res.status}`);
throw new UnrecoverableError(`not sent ${res.status}: ${await res.text()}`);
}, { connection, concurrency: 5 }); Set consent_attested to true only when the recipient agreed to receive texts. It's your statement, and Ready records it when you send. Don't hardcode it for a flow where you haven't collected consent.
Why one key per job
BullMQ re-runs the processor with the same job.data, so every attempt sends the same Idempotency-Key. If the first request reached Ready but your connection dropped before the response came back, the retry won't produce a second text. Without a stable key, a timeout is a coin flip between a lost message and a duplicate. Our guide to idempotency and duplicate texts covers the failure modes in more depth.
What to retry
| Response | Meaning | Worker action |
|---|---|---|
| 2xx | Accepted | Done |
| 429 | Rate limited | Throw, retry with backoff |
| 5xx, timeout, network error | Transient | Throw, retry with the same key |
409 QUIET_HOURS_BLOCK | A time rule, not a fault | Park it, send again once the window opens |
| Other 4xx | Bad number, opted-out contact, bad request | UnrecoverableError, alert on the failed set |
Don't retry a quiet-hours refusal in a tight loop: it will keep failing until the recipient's window opens. The full list of codes is in the errors docs, and our retries and failure handling guide turns it into a policy.
FAQ
Do I need a queue, or can the route call the API directly?
Call directly only when the user is waiting on the answer and a failure is cheap to show. For anything that must arrive, enqueue it. A queue survives deploys, absorbs bursts and keeps your request latency flat.
How do I test the route without sending real texts?
Decorate the instance with a fake sms object in your test and use app.inject() to hit the route. For the worker, stub global fetch. Our mocking guide shows both.
Where does the inbound webhook go?
In its own route. Verify the signature against the raw body, return 200 fast, dedupe, and enqueue the work. The exact fields and signing scheme are in the webhook docs on docs.tryready.com.
The short version
One plugin, one validated route, one worker, and one idempotency key per message. The messages API docs list every field, and you can create an account to get a key and send your first text.