Asterisk SIP Trunk Failover: Backup Carrier Setup and Test
Asterisk SIP trunk failover works for outbound calls by ordering two trunks in an outbound route, so Asterisk retries the second when Dial() returns CONGESTION or CHANUNAVAIL. Inbound DIDs fail over only at the carrier.
- Outbound failover is a PBX job: list the backup trunk second in the outbound route's Trunk Sequence, and Asterisk moves on only when Dial() returns CONGESTION or CHANUNAVAIL.
- Inbound DID failover is a carrier job: configure forwarding or a second destination in the carrier portal, because Asterisk cannot pull DIDs from a carrier that is down.
- Without qualify, a dead primary costs about 32 seconds (SIP Timer B) per call before failover; qualify_frequency=30 with qualify_timeout=3 marks it Unavail so later calls skip it instantly.
- The backup trunk needs its own identify match, matching inbound routes, authorised caller ID, compatible codecs and DTMF, or it fails silently.
- Prove it with iptables DROP (timeout) and REJECT (refusal) tests, and alert when the primary goes Unavail so a backup carrying traffic does not go unnoticed.
What can fail over automatically, and what cannot?
Trunk failover is two separate problems. Outbound calls are decided by your PBX, so Asterisk can retry another trunk by itself. Inbound calls are decided by the carrier, which sends INVITEs to wherever the DID is pointed, so only the carrier (or a number hosted at two providers) can redirect them.
The usual mistake is configuring a perfect outbound backup and assuming inbound is covered. If the primary carrier has an outage, your DIDs stop ringing no matter what the PBX does.
| Direction | Who decides | Mechanism | Where you configure it |
|---|---|---|---|
| Outbound | Your PBX | Trunk sequence in the outbound route, tried in order on Dial() failure | FreePBX Outbound Routes, or the Dial() chain in the dialplan |
| Inbound, carrier down | Carrier | DID failover or forwarding to a mobile, a second SIP URI or a second PBX | Carrier portal |
| Inbound, PBX unreachable | Carrier | Unreachable-destination rule, or multi-route if the carrier offers it | Carrier portal |
| Inbound on a DID hosted at both carriers | Callers' carriers | Number hosted or ported at the backup provider | Both carriers |
How does FreePBX outbound route trunk failover work?
In an outbound route, the Trunk Sequence for Matched Routes is an ordered list. FreePBX generates one Macro(dialout-trunk,...) call per trunk, in that order. The next trunk is tried only if the previous Dial() ended with a failure status.
Dial() sets the channel variable DIALSTATUS. The generated macro jumps to a label named after that status. CONGESTION and CHANUNAVAIL set the macro result to CONTINUE, which lets the route try the next trunk. BUSY, NOANSWER and a normal answered call end the attempt.
The exact generated text varies by FreePBX version, so read your own copy. This simplified excerpt shows the shape:
- Open Connectivity > Outbound Routes, select the route and add the backup trunk below the primary in Trunk Sequence for Matched Routes.
- Confirm the backup route's Dial Patterns match what the primary route matches. A missing pattern means the backup is never reached for that number format.
- Set Maximum Channels on each trunk to what the carrier actually allows, so a channel-limit hit counts as a failure and rolls to the next trunk.
- Click Submit and Apply Config, then read the generated logic with the command below.
# Show the generated failover logic
asterisk -rx "dialplan show macro-dialout-trunk"
# Simplified shape of what you will see
# s,n,Dial(${DIAL_TRUNK_OPTIONS}...)
# s,n,Goto(s-${DIALSTATUS},1)
# s-CHANUNAVAIL,1,Set(MACRO_RESULT=CONTINUE) <- next trunk
# s-CONGESTION,1,Set(MACRO_RESULT=CONTINUE) <- next trunk
# s-BUSY,1,... <- stops unless Continue if Busy
# s-NOANSWER,1,... <- stops
# Watch it live
asterisk -rx "core set verbose 5"
asterisk -rvvvvvWhich SIP responses trigger failover and which end the call?
Asterisk translates the SIP outcome into a hangup cause, and Dial() turns the cause into DIALSTATUS. Network-level failures and 5xx responses indicate that the trunk is broken, so they map to failover statuses. Most 4xx responses say the call itself is the problem, so retrying elsewhere is considered pointless.
Mappings differ slightly between Asterisk versions and between chan_pjsip and chan_sip, especially for 403 and 404. Test each response your carrier actually sends and read the DIALSTATUS in the verbose log instead of assuming.
| Event | Typical DIALSTATUS | Fails over? | Why |
|---|---|---|---|
| No response, Timer B expiry (32 s) | CONGESTION or CHANUNAVAIL | Yes, after the delay | Trunk looks dead |
| ICMP unreachable or connection refused | CONGESTION or CHANUNAVAIL | Yes, fast | Immediate transport failure |
| Contact marked Unavail by qualify | CHANUNAVAIL | Yes, instantly | Asterisk will not send the INVITE |
| 503 Service Unavailable | CONGESTION | Yes | Carrier overloaded or down |
| 500 Server Error | CONGESTION | Usually | Carrier-side fault |
| 486 Busy Here | BUSY | No, unless Continue if Busy | Callee is busy |
| 480, no answer, CANCEL | NOANSWER | No | Callee did not pick up |
| 404 Not Found | Varies, often CHANUNAVAIL | Check your version | Number or format not accepted |
| 403 Forbidden | Varies, often rejected | Check your version | Authentication or caller ID policy |
How do I make Asterisk detect a dead trunk quickly?
Without monitoring, Asterisk finds out the trunk is dead only when an INVITE gets no answer. SIP Timer B is 64 times T1 (500 ms), so 32 seconds pass before Dial() fails. Most callers hang up long before that.
The fix is qualify. Asterisk sends OPTIONS to the trunk on a schedule, and if the carrier does not respond within the timeout, the contact becomes Unavail. Later calls skip that trunk immediately because there is no available contact to send to.
In PJSIP set qualify_frequency and qualify_timeout on the AOR. In FreePBX the trunk's PJSIP Advanced tab has the qualify fields, and any extra values go in a custom file such as pjsip.aor_custom.conf. The chan_sip equivalent is qualify=yes (or a millisecond value) in the peer, shown by sip show peers.
Registration trunks have a separate set of timers on the registration object. These control how fast Asterisk notices that the carrier stopped accepting REGISTER:
; AOR for an IP-authenticated trunk (static contact)
[primary-aor]
type=aor
contact=sip:sip.primary-carrier.example:5060
qualify_frequency=30 ; send OPTIONS every 30 s
qualify_timeout=3.0 ; Unavail if no reply in 3 s
; Registration trunk
[primary-reg]
type=registration
server_uri=sip:sip.primary-carrier.example
client_uri=sip:account@sip.primary-carrier.example
expiration=600
retry_interval=30
max_retries=10
forbidden_retry_interval=600
fatal_retry_interval=120
; Optional: shorten INVITE timeout (default 32000 ms)
[system]
type=system
timer_t1=500
timer_b=8000 What do the registration and DNS settings change?
A trunk that has lost its registration can still be tried, because registration state and contact availability are separate. What blocks a dead trunk is an Unavail contact. Check both views: pjsip show registrations for Registered, Rejected or Unregistered, and pjsip show contacts for Avail or Unavail.
retry_interval controls how often Asterisk retries after a failed REGISTER. max_retries stops retries after that many attempts, so set it high enough that a long outage does not leave the trunk permanently unregistered until a reload. forbidden_retry_interval applies to 403 replies, and a short value there hammers a carrier that has blocked you.
DNS adds delay. If the provider hostname has several A records, Asterisk uses what it resolved and does not reliably try the others within one call. SRV and NAPTR records can list multiple targets with priorities, but resolver caching and TTLs make DNS-only failover slow and unpredictable. Prefer a carrier that gives you two explicit regional hostnames, and create each as its own trunk or contact, with qualify on both.
Check that primary and backup do not share an upstream. Two brands that resell the same underlying carrier fail together.
How do I fail over inbound DIDs to a backup trunk?
Start at the carrier portal. Configure DID failover or forwarding so that when your PBX does not answer or your trunk is down, calls go to a mobile, a second SIP URI (a second PBX or a cloud PBX), or a hosted backup. If the primary carrier itself is down, that portal may be down as well, so only a number hosted at the backup provider or a provider with its own multi-route platform survives that case.
On the Asterisk side, the backup trunk must deliver calls into the same inbound routes. Create a PJSIP identify for its source IPs so inbound INVITEs are matched to the right endpoint, then make sure the inbound route for each DID matches what that carrier sends.
- Add the backup carrier's signalling IPs to the trunk's Match (Permit) field in FreePBX, or to a type=identify section, and open them in the firewall for UDP/TCP 5060 (or 5061 for TLS) and the RTP range 10000 to 20000 UDP.
- Compare the DID format each carrier sends. One may send +15551234567, another 15551234567 or 5551234567.
- Add inbound routes or DID patterns for every format, or normalise on the carrier side, so both reach the same destination.
- Authorise your outbound caller ID at the backup carrier before you need it. A carrier that does not recognise the number answers with a 403 or a caller ID not allowed message, and the call does not fail over again.
- Align codecs and DTMF. If the primary uses ulaw and RFC 2833 DTMF, enable the same on the backup, or the call connects but IVRs do not respond.
[backup-identify]
type=identify
endpoint=backup-trunk
match=203.0.113.10
match=203.0.113.11
[backup-trunk]
type=endpoint
allow=!all,ulaw,alaw
dtmf_mode=rfc4733
rtp_symmetric=yes
force_rport=yes
direct_media=no
external_media_address=198.51.100.5
external_signaling_address=198.51.100.5
local_net=192.168.1.0/24How do I test SIP trunk failover before a real outage?
Test with the firewall, because it reproduces what a real outage looks like. DROP discards packets silently, which is the timeout case (Timer B, or qualify timeout). REJECT sends back an error, which is the fast-refusal case. Each takes a different path through Dial(), so test both.
Run this off hours. Blocking the primary drops any live calls on it, and a bad rule can lock you out if it matches your SSH session. Use the carrier's IP only.
Expected results: with DROP and no qualify, the first call takes about 32 seconds before the backup rings. With qualify active, the contact turns Unavail within roughly frequency plus timeout and calls go straight to the backup. With REJECT the switch is nearly immediate.
- Baseline: place a call and confirm it uses the primary (verbose shows Dial to PJSIP/primary).
- Apply the DROP rule, place a call and time how long it takes the backup to ring. Note the log lines.
- Remove the rule, wait for pjsip show contacts to show Avail, then apply REJECT and repeat.
- Test other failures: point the trunk at a wrong host, disable the trunk, and ask the carrier for a sandbox 503 if available.
- Test inbound by disabling the carrier's route or pointing it at the backup, then call each DID.
- Test failback: remove the block, confirm Avail and Registered, and confirm new calls use the primary again.
PRIMARY=203.0.113.50 # primary carrier signalling IP
# 1. Timeout simulation (silent drop)
iptables -I OUTPUT -d $PRIMARY -j DROP
iptables -I INPUT -s $PRIMARY -j DROP
# 2. Refusal simulation (use instead of DROP)
iptables -I OUTPUT -d $PRIMARY -p udp -j REJECT --reject-with icmp-port-unreachable
# Observe
asterisk -rx "pjsip set logger on"
asterisk -rx "core set verbose 5"
asterisk -rx "pjsip show contacts"
sngrep -d any port 5060
# Expected: INVITE retransmits with no reply (DROP), then
# 'Everyone is busy/congested at this time', then Dial to backup
# After qualify: contact shows Unavail, call goes straight to backup
# Cleanup (always)
iptables -D OUTPUT -d $PRIMARY -j DROP
iptables -D INPUT -s $PRIMARY -j DROP
iptables -D OUTPUT -d $PRIMARY -p udp -j REJECT --reject-with icmp-port-unreachableCommon questions
Does FreePBX fail over when the number is busy or does not answer?
No. BUSY and NOANSWER end the attempt, because the callee was reached. Only CONGESTION and CHANUNAVAIL continue to the next trunk, plus BUSY when Continue if Busy is enabled on the trunk.
What are the common mistakes in a backup trunk setup?
The most frequent are two trunks that share one upstream carrier, a backup that was never tested, missing dial patterns on the backup route, no alert when failover happens, and a failover delay long enough that callers hang up. Unauthorised caller ID on the backup is another common cause of rejected calls.
Can I fail inbound DIDs over to a different carrier?
Not without help. A DID is routed by the carrier that owns it, so it must be forwarded by that carrier or hosted at both providers. If the owning carrier is fully down, forwarding may not work, so ask about its redundancy before you rely on it.
How long does Asterisk take to fail over from a dead trunk?
With no qualify, the first call waits for Timer B, about 32 seconds. With qualify_frequency=30 and qualify_timeout=3, the contact is marked Unavail within about 33 seconds, then every later call fails over instantly. Lower timer_b to shorten the first call.
Why does the backup trunk connect but have no audio or no DTMF?
Usually the carriers differ in codec, DTMF mode or NAT handling. Set the same allowed codecs, use dtmf_mode=rfc4733, and set external_media_address, local_net and rtp_symmetric correctly. Open the RTP port range for the backup carrier's media IPs, which can differ from its signalling IPs.