# A database schema for WhatsApp conversations

> A PostgreSQL schema for WhatsApp contacts, conversations, messages, statuses and media: wamid keys, BSUID mapping, status rank and inbox indexes.

Published 2026-11-02. Z-API Omni team.

Store WhatsApp conversations in six tables. Contacts and an identifier map hold every identifier Meta sends; the others hold conversations per business number, messages keyed by `wamid`, a log of status events and media references. Meta gives each message an `id` starting with `wamid.`, so dedupe on it. A message's status only moves forward, so updates compare a rank. The schema below is one design for PostgreSQL. The field names and definitions come from Meta's webhook reference. The tables, ranks and indexes are design choices you can change.

## Contacts and the identifiers Meta sends

A WhatsApp user reaches your webhook under up to three identifiers. The inbound message carries `from`, described as "WhatsApp user phone number." The `contacts[].wa_id` "may not always match" that number ([text message webhook, accessed 2026-11-02](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text)). The third is the business-scoped user ID, or BSUID.

Meta defines a BSUID as "a unique user identifier that can be used to message a WhatsApp user when you don't know their phone number." It is a two-letter country code, a period and up to 128 alphanumeric characters, such as `US.13491208655302741918`. Webhooks carry it as `user_id` in contacts and `from_user_id` in messages, with `parent_user_id` and `recipient_user_id` elsewhere ([BSUID page, accessed 2026-11-02](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids)). Meta's BSUID page describes sending with `recipient` set to the BSUID.

The phone number can be missing. With usernames enabled, Meta generally leaves it out of webhooks. The exceptions are a message in either direction within the last 30 days, or the user being in your contact book. So every identifier column on `contacts` is nullable, and a separate table maps each identifier to a contact.

Identifiers change. "There is no user_id_update webhook field." A change arrives on the `messages` field as a system message of type `user_changed_number` or `user_changed_user_id`, with a `previous_user_id`. Meta's FAQ asks you to "map relevant fields back to your CRM/database" so you can "join with previous identifiers". The `contact_identifiers` table does that job. On a change, insert the new value for the same contact and set `retired_at` on the old one. Lookups keep working for events that still carry the old value.

Store the phone in E.164 so the same person doesn't become two rows. The [E.164 normalization post](/academy/articles/whatsapp-phone-number-format-e164-normalization/) covers the conversion.

## The schema

```sql
CREATE TABLE contacts (
  id            bigserial PRIMARY KEY,
  account_id    bigint NOT NULL,   -- your tenant, one business portfolio
  phone_e164    text,              -- NULL when the webhook omits the number
  wa_id         text,
  bsuid         text,              -- 'US.13491208655302741918'
  parent_bsuid  text,
  created_at    timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE contact_identifiers (
  account_id  bigint NOT NULL,
  kind        text   NOT NULL CHECK (kind IN ('phone', 'wa_id', 'bsuid')),
  value       text   NOT NULL,
  contact_id  bigint NOT NULL REFERENCES contacts (id),
  first_seen  timestamptz NOT NULL DEFAULT now(),
  retired_at  timestamptz,
  PRIMARY KEY (account_id, kind, value)
);

CREATE TABLE conversations (
  id               bigserial PRIMARY KEY,
  account_id       bigint NOT NULL,
  phone_number_id  text   NOT NULL,  -- your business number's ID at Meta
  contact_id       bigint NOT NULL REFERENCES contacts (id),
  last_message_at  timestamptz NOT NULL DEFAULT now(),
  last_inbound_at  timestamptz,
  UNIQUE (phone_number_id, contact_id)
);

CREATE TABLE messages (
  id               bigserial PRIMARY KEY,
  conversation_id  bigint NOT NULL REFERENCES conversations (id),
  wamid            text   NOT NULL UNIQUE,
  direction        text   NOT NULL CHECK (direction IN ('in', 'out')),
  type             text   NOT NULL,
  body             text,
  reply_to_wamid   text,
  webhook_at       timestamptz,     -- inbound: the webhook's timestamp
  stored_at        timestamptz NOT NULL DEFAULT now(),
  status           text,
  status_rank      smallint NOT NULL DEFAULT 0,
  error            jsonb,
  raw              jsonb
);

CREATE TABLE message_status_events (
  wamid        text NOT NULL,
  status       text NOT NULL,
  errors       jsonb,
  received_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (wamid, status)
);

CREATE TABLE media (
  message_id     bigint PRIMARY KEY REFERENCES messages (id),
  meta_media_id  text NOT NULL,
  mime_type      text,
  sha256         text,
  file_size      bigint,
  storage_key    text,              -- your object storage key
  downloaded_at  timestamptz,
  created_at     timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX conversations_inbox ON conversations (account_id, last_message_at DESC);
CREATE INDEX messages_thread ON messages (conversation_id, stored_at DESC, id DESC);
CREATE INDEX messages_failed ON messages (conversation_id) WHERE status = 'failed';
```

A "conversation" here is the thread between one business number and one contact. It is not a Meta billing unit.

## Messages and their timestamps

The `wamid` column has a unique constraint because Meta retries webhooks and the same message can arrive twice. Insert inbound messages with `ON CONFLICT (wamid) DO NOTHING`. Insert outbound messages when the send call returns their ID, before any status for them can matter.

The inbound `timestamp` is a "Unix timestamp indicating when the webhook was triggered" ([text message webhook](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text)). It counts seconds, and it records when the webhook fired rather than when the user pressed send. Convert it with `to_timestamp()` into `webhook_at`. Keep `stored_at` as the time your system wrote the row, and sort threads by it with `id` as the tiebreaker. Messages that arrive in a different order than they were sent are the subject of [the out-of-order sequencing post](/academy/articles/whatsapp-webhooks-out-of-order-message-sequencing/).

The `context` object carries quoted replies, forwards (`forwarded`, `frequently_forwarded`) and product referrals. Store `context.id` in `reply_to_wamid` and keep the full payload in `raw`, so a field you didn't model today is still there next month.

## Status rank and the status log

Meta sends five statuses for an outbound message ([status webhook reference, accessed 2026-11-02](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/status)). Meta sends no rank; the rank column is a design choice. A higher rank replaces a lower one, and nothing moves a message backward.

| Status | Rank | Meta's definition |
| --- | --- | --- |
| `sent` | 1 | "Indicates the message was successfully sent from our servers." |
| `failed` | 2 | "Indicates failure to send or deliver the message to the WhatsApp user's device." |
| `delivered` | 3 | "Indicates message was successfully delivered to the WhatsApp user's device." |
| `read` | 4 | "Indicates the message was displayed in an open chat thread in the WhatsApp user's device." |
| `played` | 5 | "Indicates the first time a voice message is played by the WhatsApp user's device." |

`failed` ranks above `sent` and below `delivered`: a late `sent` can't hide a failure, and a late `failed` can't overwrite a message that already reached the device. The [status webhooks post](/academy/articles/whatsapp-message-status-webhooks-sent-delivered-read-failed/) uses the same order. Meta says "A status is considered read only if it has been delivered." A message read immediately may skip the `delivered` webhook, so never require one before accepting the other. Failed statuses carry an `errors` array with `code`, `title`, `message`, `error_data.details` and `href`. Copy it into `messages.error`.

Each status webhook runs two statements:

```sql
INSERT INTO message_status_events (wamid, status)
VALUES ('wamid.EXAMPLE', 'read')
ON CONFLICT DO NOTHING;

UPDATE messages
SET status = 'read', status_rank = 4
WHERE wamid = 'wamid.EXAMPLE' AND status_rank < 4;
```

The log has no foreign key to `messages`. A status that arrives before your send call has stored the outbound row still lands in the log, and you can replay it later. [The status webhooks post](/academy/articles/whatsapp-message-status-webhooks-sent-delivered-read-failed/) explains what each status means for delivery.

## Media references

Store your own copy of the file and its hash, and treat Meta's URL as temporary. "Media URLs expire after 5 minutes, after which you must query the ID again to get a new URL." "Media IDs in webhooks expire after 7 days." "Media IDs returned by the API expire after 30 days" ([media page, accessed 2026-11-02](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media)). The URL response includes `sha256`, `mime_type` and `file_size`, which fill the `media` table.

Download the file in a worker shortly after the webhook arrives. Write it to object storage and record the key in `storage_key`. An empty `storage_key` older than a few days marks a download that failed while the ID was still valid. The [expired media URL post](/academy/articles/whatsapp-cloud-api-media-download-url-expired/) covers the fetch itself.

## Indexes for inbox queries

An inbox lists recent conversations, then pages through one thread. PostgreSQL can read the first rows of an ordered index and stop. Its manual calls ORDER BY with LIMIT "an important special case". With a matching index, "the first n rows can be retrieved directly, without scanning the remainder at all" ([PostgreSQL indexes and ORDER BY](https://www.postgresql.org/docs/current/indexes-ordering.html)).

```sql
SELECT id, contact_id, last_message_at
FROM conversations
WHERE account_id = 1
ORDER BY last_message_at DESC
LIMIT 50;

SELECT id, direction, body, status
FROM messages
WHERE conversation_id = 42
ORDER BY stored_at DESC, id DESC
LIMIT 50;
```

`conversations_inbox` and `messages_thread` match these two queries column for column, including direction. The `messages_failed` index is partial, "an index built over a subset of a table" ([PostgreSQL partial indexes](https://www.postgresql.org/docs/current/indexes-partial.html)). If failed messages are a small share of rows, the manual names avoiding common values as "One major reason for using a partial index". A "show failed sends" filter stays fast without indexing every delivered message.

## Retention

Decide with whoever owns your data policy how long to keep message bodies, `raw` payloads and media files. The schema lets you clear `body`, `raw` and the stored file on old rows while keeping `wamid`, direction and status. Conversation history then stays countable after the content is gone. If your workers read from a queue, the [webhook queue post](/academy/articles/whatsapp-webhook-queue-architecture-workers/) shows where these inserts run.

*Z-API Omni team*
