Fixing Asterisk PJSIP Ghost Contacts and Registration Thrashing
calricon / field note
When mobile SIP clients switch networks or NAT mappings expire,
Fixing Asterisk PJSIP Ghost Contacts and Registration Thrashing
In production Asterisk deployments using res_pjsip, agents and softphone users frequently report sudden registration rejections, missed inbound calls, and "Maximum number of contacts reached" errors in /var/log/asterisk/messages—even though only a single device is online. This happens when a SIP endpoint changes its source IP or ephemeral NAT port (for example, switching from Wi-Fi to LTE, roaming between access points, or experiencing a router PAT table reset) and sends a fresh REGISTER before the previous binding expires.
Because Asterisk defaults to preserving existing Address of Record (AOR) bindings until their Expiration timer reaches zero, the stale NAT socket remains registered as a ghost contact. When max_contacts is set to 1 (or a low per-user cap), Asterisk rejects the new REGISTER request, leaving the active endpoint offline until the old binding times out.
Problem Diagnosis & Root Cause Architecture
In res_pjsip, AOR contact lifecycle management is governed by strict slot accounting and NAT keepalive timers:
- Default Slot Preservation: Out of the box,
pjsip.confAOR objects setremove_existing=noandremove_unavailable=noalongsidedefault_expiration=3600andmaximum_expiration=7200. If an endpoint loses connectivity without sending a de-register (Expires: 0), its contact URI stays bound for up to two hours. - NAT Port Churn and URI Mismatch: When a client behind Carrier-Grade NAT or a consumer router reconnects on a new source port, its
ContactURI differs from the cached entry. Asterisk treats it as a distinct second contact rather than a refresh of the original binding. - Passive Availability Blindness: Without periodic SIP
OPTIONSprobing (qualify_frequency), Asterisk cannot distinguish an active, reachable socket from a disconnected peer, allowing unreachable contacts to occupy AOR slots indefinitely. - Inbound Forking to Blackholes: When
max_contactsis raised above1to work around rejections without evicting stale entries, Asterisk forks inboundINVITEs to every bound contact, wasting retransmissions on unreachable sockets and delaying ringback.
Production Rule: Never raisemax_contactsas a band-aid for registration rejections. Configure deterministic contact eviction withremove_existing=yes,remove_unavailable=yes, and activequalify_frequencyprobing so every bound contact represents a live, reachable SIP socket.
Why Standard Implementations Fail
1. Increasing max_contacts Without Eviction
Operators often bump max_contacts=5 to stop REGISTER rejections. While the new socket registers, the ghost contacts remain in AstDB. Every inbound call generates parallel INVITE transactions to unreachable IP:port tuples, triggering 408 Request Timeout cascades, bloating PJSIP transaction memory, and polluting CDR/queue logs with phantom ring attempts.
2. Relying on Short Registration Expirations Alone
Lowering maximum_expiration to 60 seconds reduces ghost contact duration but introduces severe registration thrashing. Across thousands of endpoints, 30-to-60-second re-registration storms spike CPU usage on SIP digest verification, saturate UDP receive buffers, and drain mobile device batteries.
3. Omitting rewrite_contact and qualify_frequency
Enabling remove_existing=yes without rewrite_contact=yes on the endpoint causes Asterisk to store private RFC 1918 addresses from the SIP Contact header rather than the observed public NAT socket. Furthermore, omitting qualify_frequency lets stateful firewalls close UDP pinhole mappings during idle periods, breaking inbound reachability even when a single contact is registered.
Validated Step-by-Step Resolution Playbook
Step 1: Audit Active Ghost Contacts and AOR Saturation
Inspect live bindings and identify contacts marked Unavail or Unreach occupying AOR slots on your Asterisk node:
asterisk -rx "pjsip show contacts" | grep -E "Unavail|Unreach"
asterisk -rx "pjsip show aor 1001"
tail -n 50 /var/log/asterisk/messages | grep -i "max_contacts"Look for multiple contacts under a single AOR with identical usernames on different ephemeral ports, or contacts showing Status: Unavail with RTT: nan.
Step 2: Configure Deterministic Eviction and NAT Probing in pjsip.conf
Update your AOR and Endpoint templates in /etc/asterisk/pjsip.conf so Asterisk evicts unreachable bindings first, replaces the oldest contact when a device roams, and maintains NAT pinholes via OPTIONS keepalives:
[endpoint-nat-template](!)
type = endpoint
context = from-internal
disallow = all
allow = ulaw,alaw,opus
rtp_symmetric = yes
force_rport = yes
rewrite_contact = yes
direct_media = no
[aor-single-device](!)
type = aor
max_contacts = 1
remove_existing = yes
remove_unavailable = yes
qualify_frequency = 30
qualify_timeout = 3.0
minimum_expiration = 60
default_expiration = 600
maximum_expiration = 1800
[1001](endpoint-nat-template)
aors = 1001
[1001](aor-single-device)Key Mechanics: On Asterisk 18 and newer, remove_unavailable=yes purges unreachable contacts before evaluating max_contacts. Setting remove_existing=yes guarantees that if a user switches networks while the old socket is still marked Avail, the newest registration displaces the oldest binding cleanly.
Step 3: Tune Multi-Device AORs Without Forking Waste
If an extension legitimately supports both a desk phone and a softphone, set max_contacts = 2 while keeping both eviction flags enabled:
[aor-dual-device](!)
type = aor
max_contacts = 2
remove_existing = yes
remove_unavailable = yes
qualify_frequency = 30
qualify_timeout = 3.0
default_expiration = 600
maximum_expiration = 1800When a third registration arrives (for instance, a softphone switching from Wi-Fi to 5G), Asterisk first drops any Unavail contact; if both are still marked reachable, it evicts the oldest-expiring contact so the active desk phone and new mobile socket stay online.
Step 4: Reload PJSIP and Purge Legacy AstDB Ghost Entries
Reload the configuration and verify that no syntax errors occurred (note that pjsip reload exits with code 0 even on parse errors, so always inspect the CLI output and logs):
asterisk -rx "pjsip reload"
asterisk -rx "pjsip show aor 1001"
asterisk -rx "database show registrar/contact"If legacy stale contacts from before the template change remain in AstDB, flush them cleanly and let active endpoints re-register:
asterisk -rx "database deltree registrar/contact"
asterisk -rx "pjsip show contacts"Step 5: Verify Production Stability Under Network Roaming
Test a live client roaming between Wi-Fi and cellular networks (or restarting a softphone without graceful unregister) and confirm the contact table updates cleanly:
asterisk -rx "pjsip show contacts"
asterisk -rx "pjsip set logger on"You should observe Asterisk returning 200 OK to the new REGISTER, exactly one active Avail contact with a valid sub-100ms RTT under pjsip show aor 1001, and zero max_contacts warnings in /var/log/asterisk/messages.
Experiencing this issue in your production systems?
Calricon conducts senior-level VoIP, SIP trunking, Asterisk, and cloud infrastructure audits. We review your live configs, identify packet drops or contention bottlenecks, and provide exact remediation runbooks.