Model SMS message status as a state machine by giving each message one status column, a fixed list of allowed transitions, and a rule that terminal states never change. Every status update, whether it comes from a webhook, a poll or your own code, goes through one function that checks the transition table and refuses anything not on it.

That sounds like ceremony for a text message, but it removes a whole class of bugs. Without it, a late "sent" report overwrites "delivered", a retried webhook flips a failed message back to pending, and a dashboard shows numbers nobody can explain. The statuses below are generic. Your provider's names will differ, so map them at the edge and keep your own vocabulary inside the database. For the exact fields Ready sends, use the API quickstart.

Why a status column isn't enough

A plain status string with UPDATE messages SET status = $1 trusts whatever arrives last. Delivery reports travel through a provider, a carrier and your own network, and they can arrive late, twice, or in the wrong order. Our guide to out-of-order webhooks covers why. The state machine is the storage-side answer: the database itself decides which updates are legal.

You get three things from this. Updates become safe to repeat, because a repeated transition is a no-op. Updates become safe to reorder, because a transition that would move backward is ignored. And your reports mean something, because every row sits in exactly one well-defined state.

Pick your states

Keep the list short. Each state should answer a question your product asks. Here is a generic set that fits most SMS integrations:

StateMeaningTerminal
pendingYour app created the row and has not called the API yetNo
acceptedThe API accepted the request and returned a message IDNo
sentThe provider handed the message to a carrierNo
deliveredThe carrier confirmed delivery to the handset networkYes
failedThe message did not arrive, with a reason codeYes
refusedThe API declined it before sending (opt-out, quiet hours, bad number)Yes
unknownNo final report after your timeout, outcome unconfirmedNo

Two choices here deserve a note. First, refused is separate from failed. A refusal means the text never left, so there is nothing to retry blindly and nothing to chase at a carrier. Treating it as a failure muddies your failure rate. Our observability guide makes the same split for alerts.

Second, unknown is not terminal. Some carriers never return a final report, so a message can sit at sent and still have arrived. unknown is what your reconciliation job sets after a deadline so the row stops looking healthy, and a later report can still move it to delivered or failed.

Write down the allowed transitions

The transition table is the whole design. Write it as data, not as scattered if statements.

FromAllowed to
pendingaccepted, refused, failed
acceptedsent, delivered, failed, unknown
sentdelivered, failed, unknown
unknowndelivered, failed
deliverednone
failednone
refusednone

Notice that accepted can jump straight to delivered. If the "sent" report is lost or arrives after "delivered", you still want the row to end in the right place. Skipping states forward is fine. Moving backward is not, and the table has no backward edges.

Terminal means terminal. A failed row that later receives a "delivered" report is a real situation, since carriers do contradict themselves. Decide that policy once, and write it down. We recommend refusing the change in the table and logging the conflict to a side table, so a person can look at the odd cases without the main status flapping.

The SQL

Store the status as a constrained text column or an enum, and keep the transition table in the database so no code path can skip it.

CREATE TYPE message_status AS ENUM (
  'pending', 'accepted', 'sent', 'delivered', 'failed', 'refused', 'unknown'
);

CREATE TABLE messages (
  id              uuid PRIMARY KEY,
  provider_msg_id text UNIQUE,
  status          message_status NOT NULL DEFAULT 'pending',
  status_reason   text,
  updated_at      timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE message_transitions (
  from_status message_status NOT NULL,
  to_status   message_status NOT NULL,
  PRIMARY KEY (from_status, to_status)
);

INSERT INTO message_transitions VALUES
  ('pending',  'accepted'),  ('pending',  'refused'),  ('pending', 'failed'),
  ('accepted', 'sent'),      ('accepted', 'delivered'),('accepted','failed'),
  ('accepted', 'unknown'),   ('sent',     'delivered'),('sent',    'failed'),
  ('sent',     'unknown'),   ('unknown',  'delivered'),('unknown', 'failed');

The update then becomes a single conditional statement. It only changes the row if the move is on the table, and it reports whether it did:

UPDATE messages m
SET status = $2, status_reason = $3, updated_at = now()
FROM message_transitions t
WHERE m.provider_msg_id = $1
  AND t.from_status = m.status
  AND t.to_status = $2
RETURNING m.id;

Zero rows returned means one of three things: the message is unknown to you, the transition is illegal, or the row is already in that state. All three are safe to ignore for the status column, and you distinguish them with a follow-up read when you want to log why.

Because the check and the write happen in one statement, two workers handling two reports for the same message can't both win. Postgres serializes the row update, and the second worker sees the new status and re-evaluates against it.

The TypeScript side

Mirror the table in code so you can unit test it without a database and so the compiler catches a missing state.

export const STATUSES = [
  "pending", "accepted", "sent", "delivered", "failed", "refused", "unknown",
] as const;
export type Status = (typeof STATUSES)[number];

const ALLOWED: Record<Status, readonly Status[]> = {
  pending: ["accepted", "refused", "failed"],
  accepted: ["sent", "delivered", "failed", "unknown"],
  sent: ["delivered", "failed", "unknown"],
  unknown: ["delivered", "failed"],
  delivered: [],
  failed: [],
  refused: [],
};

export const isTerminal = (s: Status) => ALLOWED[s].length === 0;
export const canMove = (from: Status, to: Status) => ALLOWED[from].includes(to);

// Map your provider's raw status strings here. These keys are placeholders:
// use whatever your provider documents.
const FROM_PROVIDER: Record<string, Status> = {
  queued: "accepted",
  sent: "sent",
  delivered: "delivered",
  undelivered: "failed",
  failed: "failed",
};

export function mapProviderStatus(raw: string): Status | null {
  return FROM_PROVIDER[raw.toLowerCase()] ?? null;
}

Return null for a status you don't recognize and log it. Never default an unknown string to failed. A new provider status that you silently map to a terminal state will quietly corrupt data until someone notices.

A test for the table takes a few lines: assert that no terminal state has outgoing edges, that every state is a key, and that no edge points backward in your ordering. Run it in CI and the table can't rot.

Keep the event log next to the status

The status column says where a message is. It doesn't say how it got there. Add an append-only message_events table with the message ID, the raw provider status, the received time and a payload reference, and write to it on every report, including the ones the state machine rejects. That gives you:

  • An audit trail when a customer asks why a text shows failed.
  • Material for the dead-letter and replay workflow, since a replay can re-run the same events through the same function.
  • A way to change the transition table later and rebuild statuses from events.

The status is a projection of the events. If you ever doubt it, you can recompute it.

Add a reconciliation deadline

A state machine only moves when something tells it to. For sent and accepted rows that never hear back, add a job that runs on a schedule. Pick a timeout based on your own traffic and label it an assumption. For example, if you assume most final reports arrive within a few minutes, a 30 minute deadline before moving a row to unknown is a reasonable start. Then ask the API for the truth with GET /v1/messages and feed what you learn through the same transition function.

Nothing special happens for reconciled rows. They go through canMove like everything else, which is the point of having one door.

The short version

Give every message one status, a transition table written as data, and terminal states that never reopen. Enforce it in a single conditional UPDATE, keep a raw event log beside it, and map provider words to your own at the edge. Then webhooks, polls and replays can all arrive in any order, any number of times, and the row still ends in the right place.

If you're building on Ready, the error codes reference is the place to learn which refusals map to your refused state before you write the table.