How To

Asterisk IVR: Call Queues, Dial-by-Name and ARI Integration

A basic Asterisk IVR plays a menu and dials an extension. Real call centers need more than that: callers who wait in a queue for the next free agent, a directory that finds people by name, and a way for outside code to take over a call. Asterisk ships all three as app_queue, app_directory and the Asterisk REST Interface (ARI).

Original content from computingforgeeks.com - post 162979

This guide builds one Asterisk IVR with call queues behind keys 1 and 2, dial-by-name on key 3, and a Python ARI app on key 9 that hands the caller back to a queue. You get the real queue show output, ARI websocket events, a curl to /ari/channels, the errors that broke the build and measured ARI latency. Every config below ran on Asterisk 24 LTS on Debian 13 in November 2026, with softphone agents answering real test calls.

Check the modules and lab layout

You need a working Asterisk PBX installation with PJSIP configured and tested before any of this makes sense. If you don’t have one, build it on Ubuntu or Debian first, then come back. The simple single-menu version of this IVR lives in the basic Asterisk IVR guide; this article picks up where that one stops.

Before you start, have these ready:

  • Asterisk with PJSIP, built with the default module set
  • A sudo user on the PBX
  • One or two softphones to act as agents
  • Python 3 for the ARI app

We ran the lab on a 4 vCPU, 4 GB VM, and you should read that as a floor, not a sizing target. Queues and ARI cost almost nothing on their own; CPU in production goes to transcoding, recording and the number of concurrent calls. We set up four extensions to act as agents.

ExtensionNameQueue
1001John Smithsales
1002Jane Doesales
1003Robert Johnsonsupport
1004Maria Garciasupport

Confirm the four modules this build depends on are loaded. A source build with default menuselect options includes all of them, but a trimmed package can leave one out.

sudo asterisk -rx "core show version"
sudo asterisk -rx "module show like app_queue"
sudo asterisk -rx "module show like app_directory"
sudo asterisk -rx "module show like res_ari.so"
sudo asterisk -rx "module show like res_stasis.so"

Each module should report Running. The version line should match the LTS release you built.

asterisk -rx module show output confirming app_queue, app_directory and res_ari are running

If a module is missing from the list entirely, rerun make menuselect, enable it and rebuild. ARI also needs the HTTP server and ari.conf, which you set up in the ARI section below, so do not chase ARI errors before then.

Define the agent endpoints

Queue members are just PJSIP endpoints, so the agents need endpoint, auth and AOR sections. Templates keep four agents from turning into eighty lines of repetition. Open the PJSIP config:

sudo vim /etc/asterisk/pjsip.conf

We put the transport and templates first, then one block per agent. You are looking at the start of the file that ran in the lab; 1003 and 1004 repeat the same pattern with their own names and passwords.

[transport-udp]
type = transport
protocol = udp
bind = 0.0.0.0:5060

[agent](!)
type = endpoint
context = internal
disallow = all
allow = ulaw,alaw
direct_media = no

[agent-auth](!)
type = auth
auth_type = userpass

[agent-aor](!)
type = aor
max_contacts = 1
qualify_frequency = 30

[1001](agent)
auth = 1001
aors = 1001
callerid = "John Smith" <1001>
[1001](agent-auth)
username = 1001
password = Ext1001Lab
[1001](agent-aor)

[1002](agent)
auth = 1002
aors = 1002
callerid = "Jane Doe" <1002>
[1002](agent-auth)
username = 1002
password = Ext1002Lab
[1002](agent-aor)

You should not skip the qualify_frequency = 30 line. It makes Asterisk send OPTIONS pings to each phone, and that reachability is what feeds device state into the queue. Without it a dead phone can look available, so the queue rings it for the full timeout on every call. Reload PJSIP once the file is saved:

sudo asterisk -rx "module reload res_pjsip.so"

Pick strong passwords on a real system. Short numeric SIP passwords get brute forced within hours on any server that exposes port 5060.

Build the call queues

A queue holds callers and rings members by a strategy until one answers. We gave the two queues different strategies on purpose. The rrmemory strategy spreads sales calls round robin and remembers where it stopped, while fewestcalls sends support calls to whoever has handled the fewest. Create the queue config:

sudo vim /etc/asterisk/queues.conf

Paste the general block and both queues, exactly as we ran them in the lab.

[general]
persistentmembers = yes
autofill = yes

[sales]
strategy = rrmemory
timeout = 15
retry = 5
maxlen = 10
wrapuptime = 10
announce-frequency = 60
announce-position = yes
joinempty = unavailable,invalid
leavewhenempty = unavailable
member => PJSIP/1001,0,John Smith,PJSIP/1001
member => PJSIP/1002,0,Jane Doe,PJSIP/1002

[support]
strategy = fewestcalls
timeout = 20
retry = 5
maxlen = 15
wrapuptime = 15
joinempty = unavailable,invalid
leavewhenempty = unavailable
member => PJSIP/1003,0,Robert Johnson,PJSIP/1003
member => PJSIP/1004,0,Maria Garcia,PJSIP/1004

Most of these options are obvious, but three decide how the queue behaves under pressure:

  • joinempty = unavailable,invalid: refuse callers when no member is reachable (paused members still count)
  • leavewhenempty = unavailable: push waiting callers out if every agent drops
  • wrapuptime: seconds an agent gets after a call before the next one rings

Leave joinempty out and callers sit listening to hold music in a queue nobody can answer. With it set, the Queue() call returns at once with QUEUESTATUS=JOINEMPTY, and your dialplan can send them to voicemail. The fourth field of each member line is the state interface, which tells the queue whose device state to watch. persistentmembers keeps agents added at runtime across restarts. Load the file:

sudo asterisk -rx "queue reload all"

You get no output on success, so check the result with queue show in the next step.

Read the queue show output

queue show is the command you’ll run most, and its member status tells you straight away whether a queue can take calls. Before any phone registers, the endpoints and the queues both say so plainly.

sudo asterisk -rx "pjsip show endpoints"
sudo asterisk -rx "queue show"

The endpoints list showed all four as Unavailable, and the screenshot below shows every queue member inheriting that state through its state interface.

asterisk queue show output with sales and support queue members all Unavailable before any phone registers

In the header line, has 0 calls is the number of callers waiting, W is the queue weight, C completed calls, A abandoned calls and SL the service level. Register a softphone as agent 1001, then check its contact and the sales queue again:

sudo asterisk -rx "pjsip show contacts"
sudo asterisk -rx "queue show sales"

The contact shows up as Avail with a sub-millisecond RTT, and John Smith flips to Not in use.

  Contact:  1001/sip:[email protected]:425 56a8b5de32 Avail         0.772

Objects found: 1

sales has 0 calls (max 10) in 'rrmemory' strategy (0s holdtime, 0s talktime), W:0, C:0, A:0, SL:0.0%, SL2:0.0% within 0s
   Members:
      John Smith (PJSIP/1001) (ringinuse enabled) (Not in use) has taken no calls yet (login was 124 secs ago)
      Jane Doe (PJSIP/1002) (ringinuse enabled) (Unavailable) has taken no calls yet (login was 124 secs ago)
   No Callers

Unavailable and paused members are never rung. In-use members are a different story: ringinuse defaults to yes, which is the (ringinuse enabled) tag on every member above, so an agent already on a call still gets rung. Add ringinuse = no to a queue if you want busy agents skipped, which is what most call centers expect.

Write the IVR dialplan

We built the IVR as one context that answers, plays a prompt and waits for a digit. Each digit is its own extension. You need a prompt first, and the stock sound packs don’t include one that lists your menu options. A text-to-speech engine gets you a usable one in seconds; the Festival TTS guide for Asterisk covers generating prompts live at call time instead. Install espeak-ng and sox:

sudo apt install -y espeak-ng sox
sudo mkdir -p /var/lib/asterisk/sounds/custom

Generate the menu and convert it to 8 kHz mono, so Asterisk plays it without resampling.

espeak-ng -w /tmp/menu.wav "For sales, press 1. For support, press 2. To find a person by name, press 3. For self service, press 9."
sudo sox /tmp/menu.wav -r 8000 -c 1 -b 16 /var/lib/asterisk/sounds/custom/main-menu.wav

Replace it with a recorded voice before going live, since callers notice a robot. Now open the dialplan:

sudo vim /etc/asterisk/extensions.conf

In the file below, [internal] holds the agent phones. It dials extensions, sends 500 into the IVR and gives agents *45 and *46 to log in and out of the sales queue. Those codes only change dynamic members: 1001 and 1002 are static in queues.conf, so *45 returns MEMBERALREADY and *46 returns NOTDYNAMIC for them. [moi-ivr] is the menu itself. We also added [ari-test] with two extensions for the ARI benchmark and the missing-app error later on.

[general]
static = yes
writeprotect = no

[internal]
exten => _100X,1,Dial(PJSIP/${EXTEN},20)
 same => n,Hangup()

exten => 500,1,Goto(moi-ivr,s,1)

exten => *45,1,AddQueueMember(sales,PJSIP/${CALLERID(num)})
 same => n,Verbose(1,AQMSTATUS=${AQMSTATUS})
 same => n,Playback(agent-loginok)
 same => n,Hangup()

exten => *46,1,RemoveQueueMember(sales,PJSIP/${CALLERID(num)})
 same => n,Verbose(1,RQMSTATUS=${RQMSTATUS})
 same => n,Playback(agent-loggedoff)
 same => n,Hangup()

[moi-ivr]
exten => s,1,Answer()
 same => n,Set(TIMEOUT(digit)=3)
 same => n,Set(TIMEOUT(response)=8)
 same => n(menu),Background(custom/main-menu)
 same => n,WaitExten(8)

exten => 1,1,Queue(sales,t,,,120)
 same => n,Verbose(1,QUEUESTATUS=${QUEUESTATUS})
 same => n,VoiceMail(1001@default,u)
 same => n,Hangup()

exten => 2,1,Queue(support,t,,,120)
 same => n,Verbose(1,QUEUESTATUS=${QUEUESTATUS})
 same => n,VoiceMail(1003@default,u)
 same => n,Hangup()

exten => 3,1,Directory(default,internal,f)
 same => n,Verbose(1,DIRECTORY_RESULT=${DIRECTORY_RESULT})
 same => n,Goto(moi-ivr,s,menu)

exten => 9,1,Stasis(ivr-app,from-ivr)
 same => n,Verbose(1,STASISSTATUS=${STASISSTATUS})
 same => n,Hangup()

exten => i,1,Playback(pbx-invalid)
 same => n,Goto(moi-ivr,s,menu)

exten => t,1,Playback(vm-goodbye)
 same => n,Hangup()

[ari-test]
exten => 100,1,Answer()
 same => n,Stasis(lat-app)
 same => n,Hangup()

exten => 200,1,Answer()
 same => n,Stasis(missing-app)
 same => n,Verbose(1,STASISSTATUS=${STASISSTATUS})
 same => n,Hangup()

Queue(sales,t,,,120) enters the sales queue with transfer allowed for the agent (t) and a 120 second queue timeout. Asterisk checks that timeout between ring and retry cycles, so a caller can wait a few seconds past it. When Queue() returns, for a timeout, a full queue or no reachable members, the next priority runs, so every queue extension falls through to voicemail instead of looping back to the menu. We first sent JOINEMPTY callers back to the menu, and the test call cycled through the prompt until it was hung up. Reload the dialplan:

sudo asterisk -rx "dialplan reload"

Point your inbound DID or trunk at moi-ivr,s,1, or dial 500 from an agent phone, to reach the menu.

Test a queue call end to end

You can test without a second phone by originating a Local channel straight into the menu extension. Asterisk plays the caller side itself, so the queue logic runs exactly as it would for a real caller:

sudo asterisk -rx "channel originate Local/1@moi-ivr application Wait 4"

With agent 1001 registered on a softphone set to auto answer, the queue rang it and the call connected. Check the queue while the call is up, again after it ends, then read the queue log.

sudo asterisk -rx "queue show sales"
sudo tail -3 /var/log/asterisk/queue_log

During the call John Smith shows (in call) (In use). Afterwards he is back to Not in use, has taken 1 call, and the header moves to C:1. Talk time is however long the caller leg stays up after the agent answers: our captured call logged 8 seconds, and the Wait 4 above will log less, so raise it if you want a longer test call.

queue show sales during and after a call answered by agent 1001 with the matching queue_log CONNECT and COMPLETECALLER rows

Reporting tools read the queue_log rows, not the CLI. ENTERQUEUE marks the caller joining at position 1, CONNECT records the agent and a hold time of 0 seconds, and COMPLETECALLER says the caller hung up after an 8 second call in our run. If you need wallboards or SLA reports, point them at this file or switch on the realtime queue log backend rather than parsing CLI output.

Manage agents at runtime

Static members in queues.conf suit a fixed team, but shift workers need to log in and out without anyone editing a file. You can do that from the CLI, from the dialplan with *45 and *46, or through AMI. Add a dynamic member with a penalty and pause another for lunch:

sudo asterisk -rx "queue add member PJSIP/1003 to sales penalty 1 as Robert state_interface PJSIP/1003"
sudo asterisk -rx "queue pause member PJSIP/1001 queue sales reason lunch"
sudo asterisk -rx "queue show sales"
sudo asterisk -rx "database show Queue"

Robert joins with penalty 1 and the (dynamic) flag, John shows paused:lunch, and the AstDB entry proves the dynamic member will survive a restart.

Asterisk CLI adding a dynamic queue member, pausing an agent with a reason and the member persisted in astdb

Penalty 1 means Robert rings only after the penalty 0 members have been tried or are unavailable, which makes him a natural overflow agent for sales. One CLI trap: an unquoted name with a space breaks the parser. as Robert Johnson printed the command usage instead of adding anyone, while as "Maria Garcia" inside single-quoted shell arguments worked and showed the full name in queue show.

Add dial-by-name with Directory

Directory() lets callers spell a name on the keypad and connects them to the match. It reads names from voicemail.conf, not from PJSIP caller IDs, so every person you want listed needs a mailbox. Open the voicemail config:

sudo vim /etc/asterisk/voicemail.conf

Your mailbox number must equal the extension in the dial context, because Directory() dials that number in internal once the caller confirms.

[general]
format = wav49|gsm|wav

[default]
1001 => 4242,John Smith,[email protected]
1002 => 4242,Jane Doe,[email protected]
1003 => 4242,Robert Johnson,[email protected]
1004 => 4242,Maria Garcia,[email protected]

Reload voicemail so the directory sees the names:

sudo asterisk -rx "voicemail reload"

Our dialplan calls Directory(default,internal,f), which means: search mailbox context default, dial matches in internal, and match on first name. Without f it matches on last name, and b accepts either. To test it, feed DTMF from a Local channel: three digits for J, O, H, a pause while Asterisk reads the match, then 1 to accept.

sudo asterisk -rx "channel originate Local/3@moi-ivr application SendDTMF wwww564wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww1"

You can follow the whole exchange in the log, from the welcome prompt through the digits to the Dial() that agent 1001 answered.

Asterisk Directory dial by name log where DTMF 5 6 4 matches John Smith and pressing 1 dials PJSIP/1001

Notice the 7 second gap between the last digit and dir-instr. No one recorded a name greeting for these mailboxes, so Asterisk spelled “John Smith” letter by letter before asking the caller to press 1. Have each person record their name from the voicemail menu (option 0, then 3) and the directory sounds like a real switchboard instead of a spelling bee.

Enable ARI on loopback

ARI is a REST API plus a websocket that hands whole calls to your own code. A channel enters your app through Stasis(), your code gets every event as JSON, and it sends commands back over HTTP. It rides Asterisk’s built-in HTTP server, so start there and bind it to loopback, because nothing outside the box should reach it directly.

sudo vim /etc/asterisk/http.conf

You only need four lines here.

[general]
enabled = yes
bindaddr = 127.0.0.1
bindport = 8088

Then create the ARI user your application will log in as:

sudo vim /etc/asterisk/ari.conf

Your section name becomes the username. A plain password is fine for a first test, and we swap it for a hash in the hardening section.

[general]
enabled = yes
pretty = yes
allowed_origins = http://localhost:8088

[ivr-app]
type = user
read_only = no
password = Ar1-IvR-Lab-2026
password_format = plain

Restart Asterisk so the HTTP server binds with the new settings, install jq for reading the JSON replies, and export the password so the rest of the commands and scripts can use it. The export only lives in the current shell, so repeat it in every terminal you open for ARI work:

sudo systemctl restart asterisk
sudo apt install -y jq
export ARI_PASS='Ar1-IvR-Lab-2026'

Check the bind address and the user, then call the info endpoint with the right password and once with a wrong one:

sudo asterisk -rx "http show status"
sudo asterisk -rx "ari show users"
curl -s -u "ivr-app:${ARI_PASS}" http://127.0.0.1:8088/ari/asterisk/info | jq .system
curl -i -u ivr-app:wrong-password http://127.0.0.1:8088/ari/channels

You want Bound to 127.0.0.1:8088 with /ari/... in the URI list, a JSON version block from the good request, and a 401 from the bad one.

curl to the Asterisk ARI info endpoint and a 401 Unauthorized Authentication required response for a wrong password

A 401 on the second request is what you want, because it proves ARI checks credentials before it touches anything. ari show apps stays empty at this point: an application only exists while a client holds its websocket open.

Write the ARI app in Python

Older tutorials, including the earlier version of this one, reach for the ari package (ari-py). Skip it. Its last release imports its own modules the Python 2 way, so on a current Python a bare python -c "import ari" against its latest PyPI release dies on the first line:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import ari
  File "/home/josphat/aripy-env/lib/python3.13/site-packages/ari/__init__.py", line 8, in <module>
    import client
ModuleNotFoundError: No module named 'client'

ARI is plain HTTP and JSON, so requests and websocket-client cover everything a call-routing app needs, with no wrapper to go stale. Create a virtual environment for them.

sudo apt install -y python3-venv
python3 -m venv ~/ari-env
~/ari-env/bin/pip install requests websocket-client

Our app answers any channel that arrives with the from-ivr argument, plays a prompt, and waits for a digit. On 1 or 2 it calls /channels/{id}/continue, which drops the caller back into the dialplan at the matching queue extension. That split is deliberate: the app makes the decision, the dialplan and app_queue do the queueing they’re already good at. Create the script:

vim ~/ivr_app.py

Paste in the script that handled the calls in our lab.

#!/usr/bin/env python3
"""Minimal ARI IVR app: answers Stasis channels, plays a prompt, routes on DTMF."""
import json
import os
import sys

import requests
import websocket

ARI = os.environ.get("ARI_URL", "http://127.0.0.1:8088/ari")
APP = "ivr-app"
AUTH = (os.environ.get("ARI_USER", "ivr-app"), os.environ["ARI_PASS"])

ROUTES = {"1": "sales", "2": "support"}


def ari(method, path, **params):
    r = requests.request(method, f"{ARI}{path}", auth=AUTH, params=params, timeout=5)
    r.raise_for_status()
    return r.json() if r.content else None


def on_event(ev):
    kind = ev["type"]
    chan = ev.get("channel", {})
    cid = chan.get("id")
    print(f"{ev.get('timestamp')} {kind} {chan.get('name', '')} {ev.get('digit', '')}".rstrip(), flush=True)

    if kind == "StasisStart" and "from-ivr" in ev.get("args", []):
        ari("POST", f"/channels/{cid}/answer")
        ari("POST", f"/channels/{cid}/play", media="sound:queue-thankyou")
    elif kind == "ChannelDtmfReceived" and ev["digit"] in ROUTES:
        queue = ROUTES[ev["digit"]]
        print(f"routing {chan['name']} to queue {queue}", flush=True)
        ari("POST", f"/channels/{cid}/continue", context="moi-ivr", extension=ev["digit"], priority=1)


def main():
    user, pw = AUTH
    url = ARI.replace("http", "ws", 1) + f"/events?app={APP}&api_key={user}:{pw}"
    ws = websocket.create_connection(url)
    print(f"connected to {ARI}, app {APP} registered", flush=True)
    try:
        while True:
            on_event(json.loads(ws.recv()))
    except KeyboardInterrupt:
        ws.close()
        sys.exit(0)


if __name__ == "__main__":
    main()

Start it in its own terminal and leave it running. The script reads the password from ARI_PASS and stops with a KeyError without it, so export it in this terminal first. The websocket connection is what registers ivr-app with Asterisk.

export ARI_PASS='Ar1-IvR-Lab-2026'
~/ari-env/bin/python -u ~/ivr_app.py

From a second terminal, confirm the app is registered.

sudo asterisk -rx "ari show apps"

You should now see the app in the list that was empty before.

Application Name
=========================
ivr-app

Now send a test call to key 9 and press 1 once the prompt plays (the curl needs ARI_PASS exported in this terminal too), then ask ARI which channels exist while the call is inside the app, and again after it moves on.

sudo asterisk -rx "channel originate Local/9@moi-ivr application SendDTMF wwwwww1wwwwwwwwwwwwwwwwwwwwwwww"
curl -s -u "ivr-app:${ARI_PASS}" http://127.0.0.1:8088/ari/channels | jq -r '.[] | [.name, .state, .dialplan.context, .dialplan.exten, .dialplan.app_name] | @tsv'

Our first curl caught the caller leg sitting in Stasis. The second, a few seconds later, shows the same leg on extension 1 running Queue, and agent 1001’s channel bridged to it through AppQueue.

Local/9@moi-ivr-00000009;1	Up	moi-ivr	9	SendDTMF
Local/9@moi-ivr-00000009;2	Up	moi-ivr	9	Stasis

Local/9@moi-ivr-00000009;1	Up	moi-ivr	9	SendDTMF
Local/9@moi-ivr-00000009;2	Up	moi-ivr	1	Queue
PJSIP/1001-00000005	Up	internal	1	AppQueue

You can see the websocket events that drove that move in the app’s own log. StasisStart arrives with the channel, the prompt plays for about 1.6 seconds, the DTMF event carries digit 1, and StasisEnd fires 2 ms after the DTMF event, once the continue request moves the channel out of the app.

Python ARI IVR app printing StasisStart, PlaybackFinished and ChannelDtmfReceived events before routing the caller to the sales queue

Underneath, the Asterisk log confirms the other half: Stasis(ivr-app,from-ivr) ran, then Queue(sales,t,,,120), then PJSIP/1001 answered. That is the whole pattern for real self-service menus. Swap the hard-coded ROUTES dict for a CRM lookup on the caller ID and the same 50 or so lines route VIP customers to a different queue.

Measure ARI latency

ARI adds a network hop to every decision, so it is fair to ask what that costs a caller. We timed two round trips over 200 calls with a small benchmark script on the lab VM. One measured an originate request until StasisStart arrived on the websocket. The other measured a DTMF request until ChannelDtmfReceived came back on the other leg of the Local channel. Both client and Asterisk ran on the same 4 vCPU host over loopback. Save the benchmark as ~/ari_latency.py if you want to reproduce it on your own hardware:

#!/usr/bin/env python3
"""Measure ARI round trips: originate -> StasisStart, and DTMF POST -> ChannelDtmfReceived."""
import json
import os
import statistics
import threading
import time

import requests
import websocket

ARI = "http://127.0.0.1:8088/ari"
APP = "lat-app"
AUTH = ("ivr-app", os.environ["ARI_PASS"])
RUNS = int(os.environ.get("RUNS", "50"))
DURATION = int(os.environ.get("DTMF_MS", "100"))

events = {}
cond = threading.Condition()


def reader(ws):
    while True:
        try:
            ev = json.loads(ws.recv())
        except Exception:
            return
        now = time.perf_counter()
        key = (ev["type"], ev.get("channel", {}).get("id"))
        with cond:
            events[key] = now
            cond.notify_all()


def wait_for(key, timeout=5):
    with cond:
        ok = cond.wait_for(lambda: key in events, timeout)
    return events.pop(key) if ok else None


def main():
    ws = websocket.create_connection(
        ARI.replace("http", "ws", 1) + f"/events?app={APP}&api_key={AUTH[0]}:{AUTH[1]}")
    threading.Thread(target=reader, args=(ws,), daemon=True).start()
    s = requests.Session()
    s.auth = AUTH
    originate, dtmf = [], []
    for i in range(RUNS):
        cid = f"lat-{i}-{int(time.time())}"
        t0 = time.perf_counter()
        s.post(f"{ARI}/channels", params={"endpoint": "Local/100@ari-test", "app": APP,
                                          "channelId": cid, "otherChannelId": cid + "-2"}).raise_for_status()
        t1 = wait_for(("StasisStart", cid))
        if t1 is None:
            print("no StasisStart for", cid)
            continue
        originate.append((t1 - t0) * 1000)
        wait_for(("StasisStart", cid + "-2"), 2)
        t2 = time.perf_counter()
        s.post(f"{ARI}/channels/{cid}/dtmf", params={"dtmf": "5", "duration": DURATION}).raise_for_status()
        t3 = wait_for(("ChannelDtmfReceived", cid + "-2"))
        if t3 is not None:
            dtmf.append((t3 - t2) * 1000)
        s.delete(f"{ARI}/channels/{cid}")
        wait_for(("StasisEnd", cid), 2)
    for name, xs in (("originate -> StasisStart", originate), ("POST dtmf -> ChannelDtmfReceived", dtmf)):
        xs.sort()
        print(f"{name}: n={len(xs)} min={xs[0]:.1f}ms median={statistics.median(xs):.1f}ms "
              f"p95={xs[int(len(xs) * 0.95) - 1]:.1f}ms max={xs[-1]:.1f}ms")


if __name__ == "__main__":
    main()

It uses the [ari-test] extension 100 from the dialplan, so no phone is needed. Run it with 200 calls:

RUNS=200 ~/ari-env/bin/python ~/ari_latency.py

On the lab VM the originate path stayed under 6 ms on every one of the 200 calls, and never passed 13 ms across all 500 benchmark calls, while the DTMF path with the default tone sat just above 200 ms.

ARI latency benchmark showing originate to StasisStart median 2.7 ms and DTMF to ChannelDtmfReceived about 202 ms

That DTMF number looked slow, so we ran three more batches of 100 calls with DTMF_MS set to 100, 50 and 250.

MeasurementRunsMedianp95Max
Originate to StasisStart2002.7 ms4.2 ms5.4 ms
DTMF to event, 100 ms tone200202.0 ms202.4 ms202.7 ms
DTMF to event, 100 ms tone100201.7 ms202.2 ms207.0 ms
DTMF to event, 50 ms tone100201.9 ms202.2 ms202.9 ms
DTMF to event, 250 ms tone100352.0 ms352.5 ms354.8 ms

You pay about 3 ms for the control plane itself. The DTMF figure tracks the tone length, because ChannelDtmfReceived only fires when the digit ends, plus a steady 100 ms on top that we observed but did not trace to its cause. A 50 ms request behaved exactly like 100 ms, so treat 100 ms as the floor. In other words, a Python app on the PBX adds nothing a caller can hear; the time in an ARI menu goes to prompts and to how long people hold the key. If your app runs on another host, add that network round trip to the 3 ms and it still disappears next to the prompt audio.

To exercise queues and ARI with real SIP traffic instead of Local channels, drive the IVR from outside with SIPp as described in the SIPp install and load testing guide.

Fix common queue and ARI errors

We hit every error below during the build. Each one has a clear log line, so grep for it before you change anything else.

WARNING app_queue.c: Unable to join queue ‘sales’

You see this when joinempty refuses the caller because no member is in a ringable state. It is the queue doing its job, not a bug, and the dialplan shows QUEUESTATUS=JOINEMPTY right after.

Asterisk log showing Unable to join queue sales and QUEUESTATUS=JOINEMPTY before the caller drops to voicemail

Run queue show sales. If every member says Unavailable, the phones aren’t registered or qualify pings are failing, so check pjsip show contacts before touching the queue. If the members are fine but the state interface points at the wrong device, fix the fourth field of the member line. Whatever the cause, make sure the next priority after Queue() goes somewhere useful, such as voicemail.

Queue members show (Unavailable) with phones registered

Your member’s state interface has to match the endpoint name exactly, including the PJSIP/ prefix and case. A member defined as PJSIP/1001 watching SIP/1001 stays unavailable forever on a server where chan_sip no longer exists. The Avail column and RTT in pjsip show contacts tell you whether Asterisk can reach the phone at all; if that column says Unavail, the problem is NAT or a firewall, not the queue.

ARI returns 401 Unauthorized “Authentication required”

Asterisk sent this exact response when we passed a wrong password.

HTTP/1.1 401 Unauthorized
Server: Asterisk/24.0.0
Date: Sat, 14 Nov 2026 09:16:46 GMT
Cache-Control: no-cache, no-store
WWW-Authenticate: Basic realm="Asterisk REST Interface"
Content-type: application/json
Content-Length: 42

{
  "message": "Authentication required"
}

Check ari show users for the username, then confirm the password format. A crypt hash pasted under password_format = plain fails every time, because Asterisk compares your password with the hash string itself. Our script sends websocket credentials as api_key=user:password in the query string, so a password containing & or # must be URL encoded there.

Stasis app ‘missing-app’ doesn’t exist

You get this when the dialplan sends a channel to Stasis() for an app with no websocket connected. Extension 200 in [ari-test] reproduces it on purpose.

Asterisk log showing Stasis app doesn't exist, STASISSTATUS=FAILED and the outbound websocket per-call config warning

Stasis() returns at once with STASISSTATUS=FAILED, so the call carries on in the dialplan. The app name in Stasis() has to match the app= value the client connects with, character for character, and the client has to be connected before calls arrive. Check ari show apps, and put a fallback after every Stasis() line so a crashed app sends callers to a queue instead of a hangup.

Failed to find outbound websocket per-call config for app ‘ivr-app’

You can easily misread this one, because the API call that triggers it succeeds. An originate to an app that is not registered still returns HTTP 200 with a channel object.

curl -s -u "ivr-app:${ARI_PASS}" -X POST "http://127.0.0.1:8088/ari/channels?endpoint=Local/100@ari-test&app=ivr-app"

Then the call fails a moment later in the log, first while Asterisk looks for an outbound websocket definition with that name, then with the usual missing-app warning.

[Nov 14 09:16:58] WARNING[55271] ari/ari_websockets.c: Local/100@ari-test-00000008;1: Failed to find outbound websocket per-call config for app 'ivr-app'
[Nov 14 09:16:58] WARNING[55271] app_stasis.c: Local/100@ari-test-00000008;1: Stasis app 'ivr-app' doesn't exist

You don’t need outbound websockets for the setup in this guide, so read the first line as “no app by that name is connected”. Start the client, confirm it with ari show apps, and treat a 200 from POST /channels as “channel created”, never as “call delivered”. Your code should wait for StasisStart on the websocket before it assumes anything.

ModuleNotFoundError: No module named ‘client’

You get that traceback from ari-py on Python 3, shown in full in the Python section above. No setting fixes it, since the package uses Python 2 imports. Remove it and use requests plus websocket-client as the script above does, or an actively maintained client for your language.

Harden the setup for production

We kept the lab config loose on purpose, so tighten it before real callers hit it. Start with the ARI password and store a hash instead of plain text. Asterisk generates one for you.

sudo asterisk -rx "ari mkpasswd ChangeMe-2026"

It prints the two lines to paste into the user’s section of ari.conf, replacing the plain ones. After you restart Asterisk, the new password is the one you hashed, so update ARI_PASS and restart the app or every request returns 401.

; Copy the following two lines into ari.conf
password_format = crypt
password = $6$fiv99bMzPGSMxMOu$t11q4XY.K8wHymT3hGR3o4NWmpYU49pVHmKVcCpU9IelPHUNVpt4bkcccR2y.GexJnqKS/Pmls7Xcud8j9cii1

The rest of the list is short:

  • HTTP server on 127.0.0.1 only, with TLS in front if ARI leaves the host
  • One ARI user per application, read_only = yes for dashboards
  • The ARI app under systemd with Restart=always
  • A fallback priority after every Queue() and Stasis()

If you would rather manage queues and agents from a web panel than from config files, the FreePBX install guide puts a GUI over the same app_queue engine. Large deployments often put a SIP proxy in front of several Asterisk boxes; the Kamailio setup guide is a good starting point for that layer. The full ARI reference lives in the official Asterisk ARI documentation.

To sum up: let app_queue and Directory() handle the routing they were built for, set joinempty so nobody waits in an empty queue, and use ARI only for the decisions the dialplan can’t make. Hand the call back with /continue once the decision is made. At 3 ms per round trip, ARI is never the slow part of a call, but an unregistered app is the most common way to lose one, so watch ari show apps the same way you watch queue show.

Keep reading

Free CCNA 200-301 Practice Questions with Answers Networking Free CCNA 200-301 Practice Questions with Answers Configure Samba File Share on Debian 13 / 12 Debian Configure Samba File Share on Debian 13 / 12 WireGuard VPN Setup: Ubuntu 26.04/24.04, Debian 13, Rocky 10 Debian WireGuard VPN Setup: Ubuntu 26.04/24.04, Debian 13, Rocky 10 Best Networking Books: TCP/IP, Routing and Troubleshooting Books Best Networking Books: TCP/IP, Routing and Troubleshooting Omada Fusion Pro Behind a Router: Port Forwarding for LAN Access Networking Omada Fusion Pro Behind a Router: Port Forwarding for LAN Access Create and Use Bridged Networks in OpenNebula VMs Cloud Create and Use Bridged Networks in OpenNebula VMs

Leave a Comment

Press ESC to close