You can send SMS from a Postgres change by having a trigger call pg_notify when a row is inserted, and a worker that listens on that channel, claims the pending rows and calls your SMS API. Treat the notification as a nudge only. The table is the source of truth, because a notification that arrives while nobody is listening is gone for good.

We make Ready, so the example uses our REST API and only the one request shape we document. The pattern itself works with any provider that accepts an idempotency key. It assumes Postgres 13 or later and Node 18 or later.

Why LISTEN/NOTIFY is a good fit for small volumes

If your texts start as rows (an orders update, a reminders insert), you already have the event. LISTEN/NOTIFY lets the database tell a worker about it within milliseconds, with no broker to run and no polling loop hammering the table.

The tradeoff is what Postgres promises. A NOTIFY is delivered to sessions that are listening at the moment the transaction commits. It isn't stored, it isn't replayed, and the payload is capped at under 8,000 bytes. So the design below never trusts the notification to carry the work.

The table and the trigger

Keep the text itself in a table. The notification carries only the row id.

CREATE TABLE sms_outbox (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  to_phone text NOT NULL,
  body text NOT NULL,
  status text NOT NULL DEFAULT 'pending',
  attempts int NOT NULL DEFAULT 0,
  next_attempt_at timestamptz NOT NULL DEFAULT now(),
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE FUNCTION notify_sms() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  PERFORM pg_notify('sms_pending', NEW.id::text);
  RETURN NEW;
END $$;

CREATE TRIGGER sms_outbox_notify
AFTER INSERT ON sms_outbox
FOR EACH ROW EXECUTE FUNCTION notify_sms();

Because the trigger runs inside the inserting transaction, the notification is only delivered if that transaction commits. A rolled-back insert never wakes anyone.

The worker: listen, then drain

The worker holds one dedicated connection for LISTEN. Don't route it through a transaction-mode pooler such as PgBouncer, which can hand your session to someone else and silently drop the subscription. Use a separate pool for the actual work.

import pg from 'pg';

const listener = new pg.Client();
const pool = new pg.Pool({ max: 4 });
let draining = false;

async function drain() {
  if (draining) return;
  draining = true;
  try {
    while (await claimAndSendOne()) {}
  } finally {
    draining = false;
  }
}

await listener.connect();
await listener.query('LISTEN sms_pending');
listener.on('notification', drain);
setInterval(drain, 30000);
await drain();

The notification handler ignores the payload and just drains. The 30 second interval and the drain at startup cover everything NOTIFY can't promise: a worker restart, a dropped connection, a deploy. Without them, a text inserted during a restart would sit forever.

Claim a row and send it once

FOR UPDATE SKIP LOCKED lets several workers share the table without taking the same row. The row's own id becomes the idempotency key, so a retry after a crash can't text anyone twice.

async function claimAndSendOne() {
  const db = await pool.connect();
  try {
    await db.query('BEGIN');
    const { rows } = await db.query(
      `SELECT id, to_phone, body, attempts FROM sms_outbox
       WHERE status = 'pending' AND next_attempt_at <= now()
       ORDER BY created_at
       LIMIT 1 FOR UPDATE SKIP LOCKED`);
    if (!rows.length) { await db.query('COMMIT'); return false; }
    const m = rows[0];

    const res = await fetch('https://api.tryready.com/v1/messages', {
      method: 'POST',
      headers: {
        'X-API-Key': process.env.READY_API_KEY,
        'Content-Type': 'application/json',
        'Idempotency-Key': m.id,
      },
      body: JSON.stringify({ to: m.to_phone, body: m.body, consent_attested: true }),
      signal: AbortSignal.timeout(15000),
    });

    // 429, or 409 idempotency_in_progress (the first try is still running): same key, later.
    const text = await res.text();
    const again = res.status === 429 || (res.status === 409 && text.includes('idempotency_in_progress'));
    const status = res.ok ? 'sent' : again && m.attempts + 1 < 5 ? 'pending' : 'failed';
    await db.query(
      `UPDATE sms_outbox SET status = $2, attempts = attempts + 1,
         next_attempt_at = now() + make_interval(secs => 30 * (attempts + 1))
       WHERE id = $1`,
      [m.id, status]);
    await db.query('COMMIT');
    return res.ok;
  } catch (err) {
    await db.query('ROLLBACK');
    return false;
  } finally {
    db.release();
  }
}

Set consent_attested from the consent you actually hold for that contact, not a hardcoded true. Until January 20, 2027 (UTC) an API send without it still goes out with a warning and no attestation recorded. From that date it is refused with 403 api_consent_attested_required.

Two details matter. The transaction stays open during the HTTP call, so the timeout bounds how long a row stays locked. And a 429, or a 409 idempotency_in_progress, leaves the row pending with a later next_attempt_at, so the next drain retries it with the same key and one stuck row can't hold the head of the queue. After five attempts it is marked failed, so look at failed rows. A 5xx is marked failed instead, because the API stores a 5xx answer and a same-key retry would replay it without sending: after a 503 (nothing was sent or charged) requeue the text under a new key, and after a 500 or 504 check GET /v1/messages first, since the message may have gone out. A real production version adds jitter and alerting on failed rows, which our guide to SMS API retries and failure handling walks through.

What can go wrong

FailureWhat happensWhy the design survives it
Worker is down during an insertThe notification is lostThe startup drain and the timer find the pending row
Worker crashes mid-sendThe transaction rolls backThe row is pending again; the same Idempotency-Key is reused
Two workers wake at onceBoth try the same rowSKIP LOCKED gives each a different row
Many inserts in one transactionIdentical notifications are collapsedThe drain loop empties the table anyway
Pooler drops the LISTEN sessionWake-ups stopThe timer keeps the queue moving, slowly

The common thread is that no failure depends on NOTIFY arriving. It makes the system fast, and the polling makes it correct.

When to use an outbox instead

LISTEN/NOTIFY with a drained table is already a small outbox. The more durable version writes the text row in the same transaction as the business change, tracks attempts and errors per row, and hands delivery to a relay with proper backoff. Our post on the transactional outbox pattern for SMS covers it, and it's the better choice once texts carry money, security codes or anything you can't afford to delay. If you'd rather not hold a database connection open during a network call, a job queue is the other route: see sending SMS from a BullMQ worker.

Also plan for quiet hours. An API text is held only if the sending window opens within a limited time, and otherwise the API answers 409 QUIET_HOURS_BLOCK and the sender sends it again once the window opens. Treat that as a reschedule, not a failure, and see handling the quiet hours 409.

Takeaways

Use the trigger and NOTIFY for speed, the table for truth, and the row id as the Idempotency-Key for safety. Drain on startup and on a timer. Keep the listener off a transaction pooler. For the full request reference, see the messages API docs, and when you're ready to try it, sign up and send a first text from your own number.