DID Management at Scale: Routing 50,000+ Numbers Without Surprises
A few hundred phone numbers can live in a spreadsheet and a dialplan. Fifty thousand cannot. This guide shows how to design a DID inventory, normalise numbers, route them from an in-memory cache, manage their lifecycle and porting, keep tenants apart and reconcile with carriers, with a schema, a Kamailio configuration and a normalisation function you can adapt.
Quick answer
How do you manage and route 50,000+ DIDs?
To route 50,000+ DIDs reliably, keep one authoritative number inventory in a database, normalise every number to E.164 at the SIP edge, and look it up in an in-memory cache loaded from that database, not in dialplan rules. Give each number an explicit lifecycle state, make every change go through one provisioning API that also refreshes the cache, and reconcile against your carriers regularly. A lookup in memory takes microseconds, so the design problem is correctness and change control, not speed.
Why numbers get hard at scale
Routing a DID looks trivial: a number comes in, you send it to a destination. The difficulty is everything around that lookup. Numbers arrive in different formats from different carriers. They belong to tenants, and a mistake exposes one customer's calls to another. They move through states, from ordered to active to ported out. They are billed by the carrier whether you use them or not. And they change constantly, by the hundred, through a portal, an API or a bulk import.
At small scale, teams write one dialplan rule per number. That stops working somewhere in the low thousands: configuration reloads get slow, nobody can find which rule owns a number, and a typo in a regular expression sends a customer's calls to the wrong place. The fix is to treat numbers as data, not configuration. This guide describes that design in the order you would build it.
It builds on our guides to multi-tenant VoIP platform architecture and PBX capacity planning. Those cover isolation and sizing; this one covers the numbers themselves.
The inventory schema
The inventory is the single source of truth. Every number has one row, an owner, a state and a route. The schema below is a starting point in PostgreSQL. It enforces E.164 with a check constraint and prevents duplicates with a unique key.
-- PostgreSQL: DID inventory
CREATE TYPE did_state AS ENUM
('available','reserved','active','porting_out','quarantine','released');
CREATE TYPE route_type AS ENUM
('extension','ring_group','queue','ivr','forward','fax','voicebot');
CREATE TABLE dids (
e164 text PRIMARY KEY
CHECK (e164 ~ '^\+[1-9][0-9]{6,14}$'), -- E.164: max 15 digits
carrier_id integer NOT NULL REFERENCES carriers(id),
country char(2) NOT NULL,
state did_state NOT NULL DEFAULT 'available',
tenant_id integer REFERENCES tenants(id),
route_type route_type,
route_target text, -- extension, queue name, URI ...
caller_id_ok boolean NOT NULL DEFAULT true, -- may be used as outbound caller ID
state_since timestamptz NOT NULL DEFAULT now(),
note text,
CONSTRAINT active_needs_route CHECK
(state <> 'active' OR (tenant_id IS NOT NULL AND route_type IS NOT NULL AND route_target IS NOT NULL))
);
CREATE INDEX dids_tenant_idx ON dids (tenant_id);
CREATE INDEX dids_state_idx ON dids (state);
-- Every change is recorded
CREATE TABLE did_audit (
id bigserial PRIMARY KEY, e164 text NOT NULL, at timestamptz NOT NULL DEFAULT now(),
actor text NOT NULL, action text NOT NULL, before jsonb, after jsonb
);Three design points are worth stressing. First, the check constraint on active numbers makes it impossible to have an active DID with nowhere to go. Second, the primary key is the E.164 string, so lookups are exact matches and fast. Third, the audit table answers the question you will be asked every month: who changed this number, and when?
Number ranges need care. Many organisations hold contiguous blocks, and it is tempting to store the block rather than each number. Store each number as a row anyway: individual rows let you assign, port and bill numbers one at a time, and 50,000 rows is a trivially small table.
Normalise to E.164 at the edge
Carriers deliver the dialled number in different forms: with or without a plus, with a national trunk prefix, with an international dialling prefix. If you compare raw strings, the same number looks like several. Normalise once, at the SIP edge, and use only the E.164 value afterwards.
E.164 is the ITU-T international numbering format. A number is a plus sign followed by the country code and the national number, with a total maximum of 15 digits. Some libraries are more lenient than that limit, so check the length yourself after parsing rather than trusting a validity flag alone. This function uses the popular phonenumbers library, a Python port of Google's libphonenumber, for the heavy lifting.
# Python: normalise a number to E.164, strictly
import phonenumbers
def to_e164(raw: str, default_region: str = "US") -> str:
"""Return +<country><national> or raise ValueError."""
num = phonenumbers.parse(raw, default_region) # accepts +, 00, national forms
if not phonenumbers.is_possible_number(num):
raise ValueError(f"not a possible number: {raw!r}")
e164 = phonenumbers.format_number(num, phonenumbers.PhoneNumberFormat.E164)
if len(e164) - 1 > 15: # enforce the E.164 maximum yourself
raise ValueError(f"longer than 15 digits: {e164}")
return e164
assert to_e164("(415) 555-0132") == "+14155550132"
assert to_e164("0044 20 7946 0958", "GB") == "+442079460958"For inbound calls on the hot path you normally do not call a library from the proxy. Instead, each carrier trunk gets a short normalisation rule in the SIP edge, for example "this carrier sends national format for the US; prefix +1". The library is used when numbers enter the system through the portal, API or bulk import, so the inventory always holds clean values.
Lookup options compared
| Method | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Dialplan rule per number | One regular expression or extension per DID | Simple for tens of numbers | Slow reloads, hard to audit, errors are silent |
| Database query per call | SELECT on every inbound call | Always current | Adds latency, database becomes a single point of failure |
| In-memory cache at the edge | Inventory loaded into Kamailio htable or similar | Microsecond lookups, survives a database outage | Needs a reload or invalidation path |
| Redis or similar shared cache | Edge queries a fast key-value store | Shared across many edges, easy updates | Extra network hop, another service to run |
| Cache with database fallback | Memory first, database on a miss | Fast and correct for new numbers | Slightly more code |
Memory needed for a DID cache by inventory size (calculated, MB)
Calculated as entries × 200 bytes. The 200-byte average is an assumption; your figure depends on the fields cached and the cache's own overhead.
The chart makes the main point: memory is not the constraint. Even five million numbers fit comfortably in a server's RAM. What you are really choosing between is operational complexity and freshness. For one or two edge nodes, an in-process cache with a reload command is simplest. For many edges, a shared cache or a database with change notifications scales better.
A Kamailio hot cache with database fallback
Kamailio's htable module can load a database table into memory at start-up and reload it on command, and the sqlops module can query the database on demand. Together they give the pattern we want: look in memory, and if the number is missing, ask the database once and cache the result. The configuration below is a sketch to adapt, not a drop-in; check the module parameters against your Kamailio version.
# Kamailio: DID lookup with an in-memory table and a database fallback
loadmodule "htable.so"
loadmodule "sqlops.so"
loadmodule "pv.so"
modparam("htable", "db_url", "postgres://kamailio:[email protected]/numbers")
# A database VIEW named did_cache with columns:
# key_name (e164), route_type, tenant_id, route_target
# htable concatenates the listed columns into one value using coldelim.
modparam("htable", "htable",
"did=>size=17;dbtable=did_cache;cols='route_type,tenant_id,route_target';coldelim='|';autoexpire=0")
modparam("sqlops", "sqlcon", "numbers=>postgres://kamailio:[email protected]/numbers")
route[DID_LOOKUP] {
$var(did) = "+" + $rU; # edge already stripped to digits
$var(hit) = $sht(did=>$var(did));
if ($var(hit) == $null) {
# cache miss: one database query, then cache the answer
sql_xquery("numbers",
"SELECT route_type||'|'||tenant_id||'|'||route_target AS v FROM dids
WHERE e164 = '$var(did)' AND state = 'active'", "ra");
if ($xavp(ra=>v) != $null) {
$sht(did=>$var(did)) = $xavp(ra=>v);
$var(hit) = $xavp(ra=>v);
}
sql_result_free("ra");
}
if ($var(hit) == $null) {
sl_send_reply("404", "Number not in service");
exit;
}
$var(rtype) = $(var(hit){s.select,0,|});
$var(tenant) = $(var(hit){s.select,1,|});
$var(target) = $(var(hit){s.select,2,|});
$avp(tenant) = $var(tenant); # used later for isolation and billing
# ... dispatch to the media server pool by route type ...
}
# After the provisioning API changes a number:
# kamcmd htable.reload did (reload all)
# kamcmd htable.delete did +14155550132 (drop one key; next call refetches)Two details matter in production. Use the narrow htable.delete command after a single change rather than reloading everything, so a busy edge never stalls on a full reload. And never cache a negative answer for long: a number that was missing a minute ago may have just been activated, so either skip caching misses or give them a short expiry. If you run several edge nodes, send the same invalidation to all of them from the provisioning API, or use Kamailio's distributed messaging to replicate the table.
Our OpenSIPS load balancing guide shows the equivalent dispatch step on OpenSIPS, and the Kamailio SBC guide covers the surrounding edge configuration.
Number lifecycle states
| State | Meaning | Routes calls? | Typical transition |
|---|---|---|---|
| Available | Owned by you, unassigned, in stock | No | Reserved when an order starts |
| Reserved | Held for an order, not yet live | No | Active when provisioning completes, or back to available on timeout |
| Active | Assigned to a tenant with a route | Yes | Porting out, or quarantine when released by the tenant |
| Porting out | A port-out request is open | Yes until the port completes | Released when the carrier confirms |
| Quarantine | Recently released, held back before reuse | No | Available after the cooling-off period |
| Released | Returned to the carrier or ported away | No | End of life in your inventory |
The quarantine state exists because reusing a number immediately can send a previous owner's callers to a new customer. How long to hold numbers is a business rule, not a technical standard, so set it with your commercial and support teams. The point of making it a state is that the system, not a person's memory, enforces it.
Number porting
Porting moves a number between carriers. Your platform sees it from two sides.
Port-in (a number comes to you)
Track the request, the carrier's acceptance and the planned cutover time. Prepare the route in advance, but keep the number out of active routing until the carrier confirms it is live. Then activate and test an inbound call straight away.
Port-out (a number leaves you)
Mark the number as porting out so it cannot be reassigned or deleted, keep routing until the carrier completes the port, then release it. Keep the audit trail: disputes over ports usually come down to timing.
Porting rules, required documents and timelines differ by country and carrier, and they change. Ask each carrier for its current process and build your workflow around it rather than around a fixed number of days. Whatever the process, a few practices pay off: keep a named owner for every open port, send a test call as soon as a port completes, and keep the old routing available for rollback where the carrier allows it. When only the delivery point changes, for example during a PBX migration, an edge-based approach can avoid porting altogether.
Tenant isolation for numbers
In a multi-tenant platform, a number belongs to exactly one tenant, and nothing should let another tenant see, route or send calls from it. Enforce that in layers.
- The provisioning API checks tenant ownership on every read and write, never trusting an ID sent by the client
- The call path carries the tenant ID from the lookup through to billing and recording
- Routing targets are validated: a number can only point at extensions and queues in the same tenant
- Administrators of one tenant cannot list another tenant's numbers, even by guessing IDs
- Cross-tenant forwarding is an explicit, audited feature, never an accident
- Every change writes an audit row with the actor, the old value and the new value
This is the same principle that applies to the rest of a multi-tenant platform, and a mistake here is the sort that ends up in an incident report. Test it with a deliberate attack case: a tenant administrator trying to assign another tenant's number.
Outbound caller ID and ownership
Numbers matter on the outbound side too. A tenant should be able to present only numbers it owns as caller ID, and only numbers marked as valid for that purpose. Check this at the edge using the same inventory, and reject or rewrite anything else. This protects customers from spoofing and protects you from carrier complaints.
If you originate calls into the United States, caller ID ownership is also tied to call signing. The attestation level a provider can give depends on knowing that the caller is entitled to use the number, which is exactly what an accurate inventory proves. Our STIR/SHAKEN implementation guide explains how the levels work. Emergency calling also needs number data: if your platform supports it, store the registered address or location for each number and keep it current, and have your compliance team confirm what your markets require.
Bulk operations and imports
You will import numbers in blocks: a new carrier allocation, a tenant migrating hundreds of lines, a monthly clean-up. Build bulk operations as first-class features, not scripts run by one person.
-- Bulk import with validation: stage, check, then merge in one transaction
BEGIN;
CREATE TEMP TABLE stage (e164 text, carrier_id int, country char(2)) ON COMMIT DROP;
\copy stage FROM 'new_block.csv' CSV HEADER
-- reject anything malformed or already known
SELECT e164 FROM stage WHERE e164 !~ '^\+[1-9][0-9]{6,14}$'; -- must return 0 rows
SELECT s.e164 FROM stage s JOIN dids d USING (e164); -- must return 0 rows
INSERT INTO dids (e164, carrier_id, country, state)
SELECT e164, carrier_id, country, 'available' FROM stage;
COMMIT;The rule to keep: validate before you write, and write inside a transaction. A half-imported block is worse than a failed one. After a bulk change that affects live routing, such as moving a hundred numbers between tenants, invalidate the affected cache keys and send a test call to a sample.
Reconciliation and reporting
Your inventory and your carriers' records will drift. Numbers are added on the carrier side by support requests, ports complete without your system hearing, and old numbers keep being billed. Reconcile on a schedule.
| Check | What a difference means | Action |
|---|---|---|
| On the carrier, not in your inventory | You are paying for, or may be receiving calls on, a number you do not track | Add it, assign it or release it |
| In your inventory, not on the carrier | You think you own a number you do not; calls will not arrive | Correct the inventory, tell the tenant |
| Active but no calls for a long period | Possibly unused and costing money | Review with the tenant, consider release |
| Calls arriving for a number in quarantine or released state | Callers still dial a previous owner's number | Play an announcement or investigate |
| Cache and database disagree | An invalidation was missed | Reload, then find the missed path |
Report the inventory by tenant, carrier and state, and put a few numbers on a dashboard: available stock by country, numbers in quarantine, open ports and cache hit rate. Stock matters because running out of numbers in a country is an avoidable commercial problem.
A real example: 50,000+ DIDs across 100+ tenants
CelloIP built a multi-tenant hosted PBX platform for a North American enterprise that serves 50,000+ extensions and 50,000+ DIDs across 100+ tenants. Each tenant has its own SIP domain, extensions, numbers, routing, recordings and call records, and the SIP edge and the call-processing layer enforce the same boundaries. A web portal and REST APIs manage the numbers alongside CDR and billing services.
CelloIP project outcome (client kept private)
50,000+ DIDs across 100+ isolated tenants, managed through a portal and APIs rather than per-number configuration.
If you are planning a platform with a large number inventory, our custom PBX development page describes the scope, and the Class 5 softswitch development page covers subscriber platforms for service providers.
Frequently asked questions
What is a DID?
A DID, or direct inward dialling number, is a public phone number that routes inbound calls to a specific destination on your system, such as an extension, a queue or an IVR, without needing a physical line per number. Carriers deliver DIDs to your platform over SIP trunks.
How should I store phone numbers?
Store the number in E.164 format: a plus sign, the country code and the national number, with no spaces or punctuation. E.164 limits a number to 15 digits in total. Keep the original input in a separate column if you need to show users what they typed, but route and compare only on the E.164 value.
Should DID lookups use the database on every call?
Not at high call rates. Querying the database per call adds latency and makes it a single point of failure for all inbound calls. Load the inventory into memory at the SIP edge, for example a Kamailio hash table or Redis, refresh it when the inventory changes, and fall back to the database only on a cache miss.
How much memory does a DID cache need?
Very little. At an assumed 200 bytes per entry, 50,000 numbers need about 10 MB, 500,000 about 100 MB and 5 million about 1 GB. These are calculated estimates from that assumption; real usage depends on the fields you store and the cache's overhead.
How do I handle number porting?
Model it as states in the lifecycle: for a port-in, track the request, the carrier's confirmation and the cutover date, and route the number only when it is live with you; for a port-out, mark the number as porting so it cannot be reassigned, then release it when the carrier confirms. Timelines and rules differ by country and carrier, so take them from your carriers.
How do I stop one tenant using another tenant's numbers?
Make tenant ownership part of the inventory and enforce it in two places: the provisioning API, which only lets a tenant assign numbers it owns, and the call path, where outbound caller ID must belong to the calling tenant. Never rely on the portal alone.
How often should I reconcile numbers with carriers?
Often enough that drift cannot build up: many operators reconcile daily or weekly by comparing their inventory with each carrier's list of numbers on your account. Differences point to numbers you are paying for but not using, or numbers routing on the carrier side that your inventory does not know about.
What does it cost to build a DID and number management system?
It is usually part of a larger platform. As a guide from our PBX pages, a multi-tenant cloud PBX platform with portals and billing is typically $30,000 to $80,000 over 10 to 20 weeks, and carrier-scale systems are scoped after discovery. The number management piece is one component of that scope.
Work with CelloIP
Need number management that scales?
CelloIP builds PBX and hosted PBX platforms with number inventories, portals, APIs and carrier integrations on Kamailio, OpenSIPS, FreeSWITCH and Asterisk. We reply within one business day, and you own the code.