A realtime SMS inbox is a webhook that writes each inbound text to your database, plus a server-sent events stream that pushes new rows to the browser. Give every row an ever-increasing counter, use it as the SSE event id, and a dropped connection recovers by itself through Last-Event-ID. History you missed comes from GET /v1/messages.

This post sketches that design in Node and TypeScript with Postgres. We make Ready, and Ready's webhook payload fields and event names live in the docs, so the handler below uses generic names you map to whatever your provider documents. The architecture is the part that carries over to any SMS API.

The shape of the system

carrier -> provider -> POST /webhooks/inbound-sms -> Postgres -> NOTIFY
                                                         |
                       browser <- SSE /inbox/stream <- API servers (LISTEN)

The database is the source of truth, and the stream is a convenience on top of it. If the push path fails, the next page load reads the same rows, so a bug in your realtime code can delay a message but never lose one.

SSE or WebSocket

For an inbox, server-sent events are usually enough, because the browser only needs to receive. Sending a reply is a normal POST.

FeatureServer-sent eventsWebSocket
DirectionServer to browserBoth ways
ReconnectBuilt into EventSource, resumes with Last-Event-IDYou write it
TransportPlain HTTP, works with most proxies and auth cookiesUpgrade handshake, sticky routing often needed
HeadersEventSource can't set custom headers, so use a cookie sessionSame limit in the browser API
Pick it whenOne-way pushes like new messages and status changesTyping indicators, presence, chat-style features

If you later add typing indicators or presence, move to WebSocket. Until then SSE gives you resume for free.

The table

The counter column does three jobs: it orders rows, it names events for resume, and it makes replay a simple range query.

CREATE TABLE inbox_messages (
  seq         bigserial PRIMARY KEY,
  tenant_id   uuid NOT NULL,
  provider_id text NOT NULL,
  direction   text NOT NULL,
  phone_e164  text NOT NULL,
  body        text NOT NULL,
  sent_at     timestamptz NOT NULL,
  UNIQUE (tenant_id, provider_id)
);
CREATE INDEX inbox_by_tenant_seq ON inbox_messages (tenant_id, seq);

The unique constraint is what makes the webhook safe to retry. Providers redeliver, and our post on out-of-order webhooks and event ordering explains why you can't count on arrival order matching send order.

Webhook to database to NOTIFY

The handler verifies the sender, inserts with ON CONFLICT DO NOTHING, and announces only rows that are new, and answers 2xx only after the row is stored. Field names here are placeholders. See the API quickstart and the error reference for the real payload and signing details, and SMS API authentication and webhook signing for the verification step.

import express from "express";
import { Pool } from "pg";

export const db = new Pool();
const app = express();

// Generic shape. Map it from your provider's documented payload.
type Inbound = { id: string; from: string; text: string; receivedAt: string };

app.post("/webhooks/inbound-sms", express.json(), async (req, res) => {
  // Verify the provider's signature here and reject on failure.
  const m = req.body as Inbound;
  const tenantId = await tenantForInboundNumber(req); // your own lookup

  try {
    const { rows } = await db.query(
      `INSERT INTO inbox_messages (tenant_id, provider_id, direction, phone_e164, body, sent_at)
       VALUES ($1, $2, 'in', $3, $4, $5)
       ON CONFLICT (tenant_id, provider_id) DO NOTHING
       RETURNING seq`,
      [tenantId, m.id, m.from, m.text, m.receivedAt],
    );
    if (rows[0]) {
      await db.query("SELECT pg_notify('inbox', $1)", [
        JSON.stringify({ tenantId, seq: rows[0].seq }),
      ]);
    }
    res.sendStatus(200); // stored (or a duplicate already stored)
  } catch (err) {
    // Not stored: answer 500 so the provider redelivers. The unique key makes the retry safe.
    console.error("inbound insert failed", m.id, err);
    res.sendStatus(500);
  }
});

Store first, then respond. If you answer 200 before the insert, a crash or a slow database between the reply and the insert loses the text, because the provider was told it arrived and will not redeliver. Answering 500 on a failed insert makes the provider retry, and the unique key makes the retry safe. Our guide to a webhook dead-letter queue and replay covers the safer pattern, and the backfill below also closes the gap.

The SSE endpoint with resume

Each API server holds a set of open responses per tenant and listens on one Postgres connection. The tricky part is the race between replaying history and receiving live rows, so the code buffers live rows until replay finishes.

import { Client } from "pg";
import type { Response } from "express";

type Row = { seq: string; phone_e164: string; body: string; sent_at: string };
const subscribers = new Map<string, Set<(r: Row) => void>>();

const listener = new Client();
await listener.connect();
await listener.query("LISTEN inbox");
listener.on("notification", async (n) => {
  const { tenantId, seq } = JSON.parse(n.payload ?? "{}");
  const subs = subscribers.get(tenantId);
  if (!subs?.size) return;
  const { rows } = await db.query<Row>(
    "SELECT seq, phone_e164, body, sent_at FROM inbox_messages WHERE seq = $1",
    [seq],
  );
  if (rows[0]) subs.forEach((push) => push(rows[0]));
});

app.get("/inbox/stream", async (req, res: Response) => {
  const tenantId = await tenantFromSession(req); // cookie auth
  if (!tenantId) return void res.sendStatus(401);

  res.set({
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache, no-transform",
    Connection: "keep-alive",
    "X-Accel-Buffering": "no",
  });
  res.flushHeaders();
  res.write("retry: 3000\n\n");

  let lastSent = Number(req.get("Last-Event-ID")) || 0;
  let replaying = true;
  const buffered: Row[] = [];

  const push = (r: Row) => {
    if (Number(r.seq) <= lastSent) return;
    lastSent = Number(r.seq);
    res.write(`id: ${r.seq}\nevent: inbound\ndata: ${JSON.stringify(r)}\n\n`);
  };
  const live = (r: Row) => (replaying ? buffered.push(r) : push(r));

  const set = subscribers.get(tenantId) ?? new Set();
  set.add(live);
  subscribers.set(tenantId, set);

  const { rows } = await db.query<Row>(
    `SELECT seq, phone_e164, body, sent_at FROM inbox_messages
      WHERE tenant_id = $1 AND seq > $2 ORDER BY seq LIMIT 500`,
    [tenantId, lastSent],
  );
  rows.forEach(push);
  buffered.sort((a, b) => Number(a.seq) - Number(b.seq)).forEach(push);
  replaying = false;

  const heartbeat = setInterval(() => res.write(": ping\n\n"), 25_000);
  req.on("close", () => {
    clearInterval(heartbeat);
    set.delete(live);
  });
});

Four details matter. The id: line is what the browser sends back as Last-Event-ID. The seq <= lastSent guard drops duplicates from the replay and buffer overlap. The heartbeat comment keeps idle connections alive through proxies, and X-Accel-Buffering: no stops nginx from holding the stream. And the 500-row limit caps replay: a client that was offline longer than that should reload from the list endpoint.

The browser side

EventSource reconnects on its own and resends the last id, so the client is short. Keep your own dedupe by seq, because a reconnect can deliver a row you already drew.

const seen = new Set<string>();
const es = new EventSource("/inbox/stream", { withCredentials: true });

es.addEventListener("inbound", (e) => {
  const row = JSON.parse((e as MessageEvent).data);
  if (seen.has(row.seq)) return;
  seen.add(row.seq);
  renderMessage(row);
});

es.onerror = () => {
  // readyState CLOSED means the server refused us (for example a 401). Don't loop.
  if (es.readyState === EventSource.CLOSED) showSignedOut();
};

Backfill from GET /v1/messages

Your table only knows what arrived while your webhook was healthy. For a new tenant, an outage or a missed delivery, fill the gap from the API. GET /v1/messages pages with before_id, so you walk backward from the newest message until you reach messages older than the time your webhook was last known healthy, which you pass in as since. Stopping at the first page you already have would skip an outage in the middle.

const PAGE_URL = "https://api.tryready.com/v1/messages";

// Map the documented response to your table. We don't guess its field names here.
declare function normalizePage(json: unknown): {
  items: { providerId: string; direction: string; phone: string; body: string; sentAt: string }[];
};

// since: when the webhook was last known healthy (epoch for a new tenant)
export async function backfill(tenantId: string, apiKey: string, since: Date) {
  let beforeId: string | undefined;
  for (let page = 0; page < 50; page++) {
    const url = beforeId ? `${PAGE_URL}?before_id=${encodeURIComponent(beforeId)}` : PAGE_URL;
    const res = await fetch(url, {
      headers: { "X-API-Key": apiKey },
      signal: AbortSignal.timeout(10_000),
    });
    if (!res.ok) throw new Error(`backfill failed: ${res.status}`);
    const { items } = normalizePage(await res.json());
    if (items.length === 0) return;

    for (const m of items) {
      await db.query(
        `INSERT INTO inbox_messages (tenant_id, provider_id, direction, phone_e164, body, sent_at)
         VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (tenant_id, provider_id) DO NOTHING`,
        [tenantId, m.providerId, m.direction, m.phone, m.body, m.sentAt],
      );
    }
    if (new Date(items[items.length - 1].sentAt) < since) return; // the page reaches back past what we already held
    beforeId = items[items.length - 1].providerId;
  }
}

Backfilled rows get fresh seq values, so they arrive after live ones in the stream, and the UI should sort by sent_at, not seq. Run backfill on tenant onboarding and on a slow schedule as a safety net.

Operating it

  • Auth. Check the tenant on every connection and every row. A stream that leaks another tenant's texts is the worst bug this feature can have.
  • Connection limits. Each open stream is an open socket, so set per-user caps and watch file descriptors.
  • Replies. Send through POST /v1/messages with an Idempotency-Key, and write the outbound row the same way so the thread stays complete.
  • Opt-outs. Show a STOP in the thread and block the compose box. GET /v1/opt-outs/:phone answers for one number.

For the product side of a shared inbox, such as assignment and ownership, see shared SMS inbox for teams, and for the webhook basics see receiving SMS through inbound webhooks.

Where to go next

Build the table and webhook first and render from the database on page load. Add the stream once that works, because the stream is only a latency improvement. Then kill your server mid-conversation and confirm the browser catches up with no gaps.