To send an SMS from Heroku, put the REST call in a worker dyno that reads jobs from your database, and use Heroku Scheduler only to start a short one-off dyno that enqueues or drains due texts. Store one idempotency key per message before you send, because Heroku restarts dynos at least once a day and Scheduler can skip or repeat a run.
We make Ready, so the code below uses our REST API and only the request shape we document: POST /v1/messages with to, body and consent_attested, plus the X-API-Key and Idempotency-Key headers. The Heroku parts apply to any HTTP SMS API.
Why dynos make duplicate texts easy
A dyno isn't a server you keep. Heroku restarts every dyno about once every 24 hours, it restarts after a deploy or a config var change, and it can move a dyno to a different host. Each restart sends SIGTERM and gives the process 30 seconds before SIGKILL.
Picture a worker that has sent a text, then gets killed before it marks the job done. On restart it picks the same job again. Without an idempotency key, the customer gets two texts. With one, the second request is recognized as a repeat and isn't sent twice. Our idempotency guide covers the mechanics.
Set the key as a config var
Never commit the key. Set it on the app and Heroku injects it into every dyno, including Scheduler's one-off dynos:
heroku config:set READY_API_KEY=your_key_here -a your-app Changing a config var restarts your dynos, so do it at a quiet moment. See key security and rotation for how to rotate without a gap.
An outbox table gives every text a stable key
The pattern that survives restarts is simple: write the text to a table first, with its key, and let the worker send rows that aren't done.
CREATE TABLE sms_outbox (
id bigserial PRIMARY KEY,
idempotency_key uuid NOT NULL DEFAULT gen_random_uuid(),
to_number text NOT NULL,
body text NOT NULL,
send_after timestamptz NOT NULL DEFAULT now(),
attempts int NOT NULL DEFAULT 0,
status text NOT NULL DEFAULT 'pending'
); The key is created when the row is inserted, not when the worker runs. A restart, a retry and a second dyno all see the same value, so the same text always goes out under the same Idempotency-Key.
The sender and the worker loop
This is Node 20 or later, using the built-in fetch and the pg package. SKIP LOCKED lets you scale the worker to several dynos without two of them taking the same row.
// worker.js
import pg from 'pg';
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false },
});
async function send(row) {
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': row.idempotency_key,
},
body: JSON.stringify({ to: row.to_number, body: row.body, consent_attested: true }),
signal: AbortSignal.timeout(15_000),
});
return { status: res.status, text: await res.text() };
}
function verdict({ status, text }) {
if (status < 300) return 'sent';
if (status === 429 || status === 500) return 'retry';
if (status === 409 && text.includes('idempotency_in_progress')) return 'retry';
if (status === 409 && text.includes('QUIET_HOURS_BLOCK')) return 'later';
if (status === 503) return 'rekey';
return 'failed';
}
let stopping = false;
process.on('SIGTERM', () => { stopping = true; });
async function tick() {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT * FROM sms_outbox
WHERE status = 'pending' AND send_after <= now()
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED`);
if (!rows.length) { await client.query('COMMIT'); return false; }
const row = rows[0];
let v;
try { v = verdict(await send(row)); } catch { v = 'retry'; }
const delay = Math.min(2 ** row.attempts * 30, 3600);
await client.query(
`UPDATE sms_outbox SET attempts = attempts + 1,
status = CASE WHEN $2 = 'sent' THEN 'sent'
WHEN $2 = 'failed' OR attempts >= 7 THEN 'failed'
ELSE 'pending' END,
idempotency_key = CASE WHEN $2 = 'rekey' THEN gen_random_uuid() ELSE idempotency_key END,
send_after = now() + make_interval(secs => CASE WHEN $2 = 'later' THEN 3600 ELSE $3 END)
WHERE id = $1`, [row.id, v, delay]);
await client.query('COMMIT');
return true;
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
while (!stopping) {
const worked = await tick().catch(() => false);
if (!worked) await new Promise((r) => setTimeout(r, 2000));
}
await pool.end(); The row stays locked until the update commits, so if the dyno dies mid-send the transaction rolls back and the row is pending again with the same key. A repeated key means the request isn't sent twice. Set consent_attested to true only when the recipient agreed to texts.
The verdicts follow our retry guide. A 429 or 500 retries with the same key. A 503 means the text wasn't sent, so the row gets a fresh key. Other 4xx answers, such as a bad number or an opted-out contact, are marked failed so you can see them. A 409 QUIET_HOURS_BLOCK is a time rule, not an error: the row waits and goes out later. See handling quiet hours.
The Procfile and scaling
web: node server.js
worker: node worker.js Scale the worker with heroku ps:scale worker=1, and add dynos if the queue grows. Sends are rate limited, so read SMS API rate limits before you scale far.
Where Heroku Scheduler fits
Scheduler starts a one-off dyno on a fixed cadence (every 10 minutes, hourly or daily). It's the right tool for "queue tomorrow's appointment reminders", and the wrong tool for sending directly, because Heroku describes it as best effort: a run can be skipped, and a run can start while the last one still runs.
Make the Scheduler command idempotent. Give it a command such as node enqueue-reminders.js that inserts outbox rows with a deterministic uniqueness rule, so a repeated run adds nothing:
ALTER TABLE sms_outbox ADD COLUMN dedupe text UNIQUE; The script inserts with ON CONFLICT (dedupe) DO NOTHING, where dedupe is built from the appointment id and the date, such as reminder:1042:2026-12-01.
The worker then does the sending, with restarts and retries handled in one place.
| Job | Where it runs | Why |
|---|---|---|
| Send a queued text | worker dyno | Long-running, restart-safe with the outbox |
| Queue daily reminders | Scheduler one-off dyno | Short, repeatable, dedupe column makes reruns harmless |
| Receive replies | web dyno | Verify the signature, return 200 fast, dedupe, enqueue |
| Retry after a failure | worker dyno | Same key, bounded attempts |
For replies, read the webhook docs and our inbound webhook guide before you build the handler.
FAQ
Can I send directly from a Scheduler job?
You can, for a handful of texts, but a skipped or repeated run then means a missed or doubled batch. Enqueue from Scheduler and send from the worker.
What happens to a text in flight when the dyno restarts?
If the process finishes within the 30 seconds after SIGTERM, it commits normally. If not, the transaction rolls back, and the next worker retries the row under the same idempotency key.
Do I need Redis?
No. Postgres is enough for most apps, and it's already there. If you already run Redis, our BullMQ worker guide shows the same idea with a Redis queue.
The short version
Create the key when you create the row, send from a worker, let Scheduler only enqueue, and treat every restart as normal. The messages API docs list every field, and you can start texting today when your key is ready.