To route an inbound text to the right tenant, look up the number it was sent to in a table where each phone number belongs to exactly one tenant, enforced by a unique constraint. The sender's number tells you who the customer's contact is. The destination number tells you whose inbox the message belongs in.

That sounds like a one-line query, and it is, until a number gets reassigned, released, or arrives from a webhook with formatting you didn't expect. This guide covers the table, the lookup, and the edge cases that cause cross-tenant leaks. We make Ready, and each of our sub-accounts has its own numbers, but the pattern applies to any platform that gives each customer its own numbers.

Why the destination number is the routing key

On a platform where every tenant has its own number, the destination is the only field that reliably identifies the tenant. The sender could be a contact who texts three of your tenants. The message body is free text. A conversation ID is yours to invent, and an inbound text doesn't carry one.

So the rule is simple: the "to" number of an inbound message resolves to one tenant, or it resolves to nothing. It never resolves to two.

A webhook note before the code

Webhook payload shapes differ by provider, and we won't invent one here. The code below uses generic names, to_number, from_number and text, as stand-ins for whatever your provider documents. Map them in a single adapter function. For Ready's webhook details, see the API quickstart and the error reference. Our inbound webhooks post covers verification, retries and acknowledging fast.

The number table

CREATE TABLE phone_numbers (
  id            bigserial PRIMARY KEY,
  e164          text        NOT NULL,
  tenant_id     bigint      NOT NULL REFERENCES tenants(id),
  status        text        NOT NULL DEFAULT 'active'
                CHECK (status IN ('active', 'releasing', 'released')),
  assigned_at   timestamptz NOT NULL DEFAULT now(),
  released_at   timestamptz
);

/* One live owner per number. Released rows stay for history. */
CREATE UNIQUE INDEX phone_numbers_one_live_owner
  ON phone_numbers (e164)
  WHERE status <> 'released';

CREATE INDEX phone_numbers_tenant ON phone_numbers (tenant_id);

Three choices in that schema are worth defending.

  • The partial unique index lets the same number appear many times in history while allowing only one live owner. A plain unique constraint on e164 would force you to delete history to reuse a number.
  • e164 is stored normalized. Normalize on write and on lookup, never only on one side.
  • released is a status, not a deleted row. You'll want the record when someone texts a number after it stops being yours.

Normalize, then look up

import re

def to_e164(raw: str, default_country: str = "1") -> str | None:
    digits = re.sub(r"\D", "", raw or "")
    if len(digits) == 10:
        digits = default_country + digits
    if len(digits) == 11 and digits.startswith(default_country):
        return "+" + digits
    return None  # let your provider's lookup handle anything outside your default country


def resolve_tenant(db, to_number: str) -> int | None:
    e164 = to_e164(to_number)
    if e164 is None:
        return None
    row = db.execute(
        "SELECT tenant_id FROM phone_numbers "
        "WHERE e164 = %s AND status <> 'released'",
        (e164,),
    ).fetchone()
    return row[0] if row else None

The partial index makes this a single-row lookup. Because the index guarantees at most one live row, there's no "pick the first one" logic anywhere, which is the bug that leaks messages across tenants.

The handler

Acknowledge quickly, store the message under the resolved tenant, and do the slow work later. A generic handler:

def handle_inbound(db, event: dict) -> int:
    """event uses generic field names; map your provider's payload into this shape."""
    tenant_id = resolve_tenant(db, event["to_number"])
    if tenant_id is None:
        db.execute(
            "INSERT INTO unrouted_inbound (to_number, from_number, text, received_at) "
            "VALUES (%s, %s, %s, now())",
            (event["to_number"], event["from_number"], event["text"]),
        )
        return 202  # accepted, parked for review

    db.execute(
        "INSERT INTO inbound_messages (tenant_id, from_number, to_number, text, received_at) "
        "VALUES (%s, %s, %s, %s, now())",
        (tenant_id, event["from_number"], event["to_number"], event["text"]),
    )
    return 200

Every query downstream of this point filters by tenant_id. Resolving the tenant once, at the edge, and carrying that ID through is cheaper and safer than re-deriving it in each handler.

Edge cases that cause real incidents

SituationWhat to do
Unknown destination numberPark it in an unrouted table, alert if the count rises, never guess a tenant
Number in releasing stateKeep routing to the old owner until the release finishes, so late replies don't vanish
Number reassigned between tenantsDo it in one transaction: mark the old row released, insert the new live row
Released number gets a textStore as unrouted. The new holder, if any, shouldn't see the previous owner's contacts
Same contact texts two tenantsFine. Routing is by destination, and contacts are per tenant
Formatting differences ((212) 555-0199)Normalize on both sides, as above
Duplicate delivery of the same eventDe-duplicate on your provider's message ID before inserting

Reassignment deserves care. Do the swap in a single transaction and take a row lock on the number first:

BEGIN;
SELECT id FROM phone_numbers
 WHERE e164 = '+15555550142' AND status <> 'released'
 FOR UPDATE;
UPDATE phone_numbers SET status = 'released', released_at = now()
 WHERE e164 = '+15555550142' AND status <> 'released';
INSERT INTO phone_numbers (e164, tenant_id) VALUES ('+15555550142', 42);
COMMIT;

The unique index will refuse the insert if the first update didn't happen, so a half-finished reassignment fails loudly instead of creating two owners. That number is a made-up 555-01xx example.

Release and recycling

A released number can be assigned to someone new, and people keep texting numbers they used to know. Texts to a recycled number can come from contacts of the previous owner, including a STOP. How long to quarantine a number before reassigning it, and what to do with contacts and opt-outs, is covered in phone number release and recycling for platforms. Check your own account's opt-out state with GET /v1/opt-outs/:phone before you re-use a number to message anyone.

If you manage numbers through Ready, GET /v1/numbers lists the numbers on an account and GET /v1/sub-accounts lists the sub-accounts. Use those as the source of truth to reconcile against your own table on a schedule. A nightly diff that flags numbers your table calls live and the API doesn't, or the reverse, catches drift before a customer does.

Test the dangerous paths

Write tests for the cases above on a real Postgres, not a mock. A mock can't tell you the partial unique index works. The tests worth having: two live rows for one number is rejected; a lookup on a released number returns nothing; a reassignment that fails halfway leaves one owner; an unknown number lands in the unrouted table and not in any tenant's inbox.

The short version

One destination number, one live tenant, enforced by the database. Normalize before you look up, park what you can't route, and reassign in a transaction. The routing code is short, and the constraint is what keeps it correct when someone is tired at 2 AM.