Best Practices for Reducing Call Latency with Twilio Voice API
Twelve engineering fixes for slow Twilio voice agents: pick the right edge, stream STT, LLM and TTS, tune endpointing, and measure p50, p90 and p99 before you change anything.
Want a faster Twilio voice agent?
Book a callOn this page 0% read
Short answer: The best practices for reducing call latency with Twilio Voice API: host near Twilio's media edge, keep STT, LLM and TTS in one region, use a bidirectional stream or ConversationRelay instead of
<Gather>, stream every stage, tune endpointing, stay in mu-law 8 kHz, and track p50, p90 and p99 per hop.
A slow voice agent is rarely one big problem. It is ten small delays in a row. This guide gives you a sourced latency budget, 12 fixes with code, and a benchmark plan to prove each fix worked. It comes from how we build production voice agents at Octacer.
The 12 practices at a glance
- Pick the right edge, and know what the REST
edgesetting does not do. - Co-locate your app server, STT, LLM and TTS in one region.
- Use bidirectional Media Streams or ConversationRelay, not
<Gather>round trips. - Stream everything: STT partials, LLM tokens, TTS chunks.
- Tune endpointing and handle barge-in.
- Keep mu-law 8 kHz end to end.
- Pre-connect sockets and remove cold starts from the audio loop.
- Keep prompts short and models fast for the first reply.
- Cache common TTS phrases.
- Keep webhooks fast and push heavy work off the audio path.
- Trim network overhead and watch your send buffer.
- Choose SIP codecs and edges on purpose.
Why latency kills voice calls
People take turns fast. A study of conversation across 10 languages found that speakers everywhere avoid overlapping talk and keep the silence between turns short, with language averages falling within 250 ms of the cross-language mean (Stivers et al., PNAS 2009). Typical gaps sit around a couple of hundred milliseconds. Callers bring that expectation to the phone.
A phone agent cannot hit 200 ms. Audio crosses a carrier network, a Twilio media edge, three AI services and the same path back. Twilio's own guidance is blunt about what callers notice: delays over one second feel slow, and over two seconds can break the flow of the conversation. Its ConversationRelay dashboard flags any turn where the agent takes longer than 1.2 seconds to start speaking (Twilio Conversation Relay Insights).
Miss that window and callers say "hello?" and talk over the bot. Twilio notes that high customer interruption counts can mean latency made the caller impatient (Twilio call summary).
Where latency comes from: the end-to-end budget
Twilio counts at least ten network traversals per response in a cascaded agent: two voice legs and eight inter-service handoffs (Twilio core latency guide). Here is where the time goes.
| Stage | Typical or published figure | Good target | Source or label |
|---|---|---|---|
| PSTN and carrier leg | Varies by carrier and network. In Cozzo's phone tests the phone line added 0.28 s to 0.69 s compared with a browser connection, for the four platforms tested both ways | Measure on your own calls | Cozzo; Twilio's own metrics exclude this last mile (call summary) |
| Twilio media edge | About 40 ms ingress, 30 ms buffering, 25 ms decode | Same | Twilio core latency guide |
| Each service hop | About 10 ms when services sit together; Deepgram lists network transit of 20 to 200 ms depending on geography | About 10 ms, Twilio's figure | Twilio core latency guide, Deepgram |
| Endpointing (end of turn) | Fixed silence defaults near 500 ms; Deepgram Flux end-of-turn 100 to 500 ms | Lowest you can reach without cutting callers off | Twilio guide, Deepgram |
| STT | Deepgram transcription latency 150 to 300 ms | 350 ms target, 500 ms upper limit | Deepgram; Twilio guide |
| LLM time to first token | Depends on model, prompt and region; Twilio gives no single typical figure | 375 ms target, 750 ms upper limit | Twilio core latency guide |
| TTS time to first byte | ElevenLabs Flash about 100 ms median, model only; 100 to 150 ms over WebSockets from North America, Europe and South East Asia, 150 to 200 ms from South Asia and North East Asia | 100 ms target, 250 ms upper limit | ElevenLabs; Twilio guide |
| Re-encode, buffer and return path | Twilio folds this into its roughly 1.1 s total and publishes no separate figure | Measure on your own calls | Twilio core latency guide |
Best practices for reducing call latency with Twilio Voice API: 12 fixes
1. Pick the right edge, and know what the REST setting does
Problem: Media enters Twilio far from your servers, so every packet pays extra round-trip time.
Fix: Twilio says that for Voice SDKs and SIP the chosen edge location "directly influences media latency and call quality" (Understanding Edge Locations). For PSTN calls, Twilio's guide says media enters at the edge nearest the caller, so what matters is the distance from that edge to your services. Its advice is to colocate at a Twilio edge location or use Twilio Interconnect (core latency guide).
// REST client in the Ireland region. Needs IE1 API keys.
const client = require('twilio')(process.env.IE1_API_KEY, process.env.IE1_API_SECRET, {
accountSid: process.env.TWILIO_ACCOUNT_SID,
region: 'ie1',
edge: 'dublin', // builds api.dublin.ie1.twilio.com; does not move media
});
Where edge does move media:
<!-- SIP: set the edge on the URI -->
<Response><Dial><Sip>sip:alice@example.com;edge=frankfurt</Sip></Dial></Response>
// Voice JavaScript SDK: an array enables automatic edge fallback
const device = new Device(token, { edge: ['dublin', 'frankfurt'] });
Public edge IDs are sydney, sao-paulo, dublin, frankfurt, tokyo, singapore, ashburn, umatilla and roaming (Global Low Latency, not available for SIP) (Understanding Edge Locations). The SIP URI can take an edge parameter, and the Voice JavaScript SDK accepts an array of edges for automatic fallback (Understanding Edge Locations).
2. Co-locate app server, STT, LLM and TTS
Problem: Audio lands in Virginia, STT runs in Oregon, TTS in Europe. Every crossing adds round-trip time.
Fix: Twilio's guidance is to keep services close together and close to the customer, and to spend your first effort on the orchestration server, STT and TTS, because audio is heavier and more fragile than text. LLM delays are easier to mask with fillers. Twilio also warns against running STT and TTS on the same machine: interruptions can push both workloads into phase and cause tail spikes (core latency guide).
Check real connect times from the box that runs your audio loop, as Deepgram suggests:
# Run 20 times from your app server and compare regions.
curl -o /dev/null -s -w 'connect=%{time_connect}s tls=%{time_appconnect}s\n' https://api.deepgram.com/
3. Use a bidirectional stream, not <Gather> round trips
Problem: <Gather> waits for speech to end, sends an HTTP request, waits for TwiML and plays it. Every turn pays for that webhook cycle.
Fix: Open one persistent WebSocket per call. You have two choices.
| `<Connect><Stream>` (Media Streams) | `<Connect><ConversationRelay>` | |
|---|---|---|
| You manage | STT, TTS, VAD, barge-in, orchestration | Your LLM logic over text messages |
| Control | Full raw audio, any provider | Twilio-supported STT and TTS providers |
| Published latency | Depends on your stack | Median under 0.5 s, p95 under 0.725 s, Twilio internal benchmarks (Twilio) |
| Pick it when | You need custom audio models | You want managed STT, TTS and turn-taking |
<Connect><Stream> creates a bidirectional stream. It only receives the inbound track, the URL must be wss:// and cannot carry a query string, so pass values with <Parameter> (TwiML Stream).
<!-- Media Streams: raw audio, you own the pipeline -->
<Response><Connect>
<Stream url="wss://voice.example.com/media">
<Parameter name="from" value="+15550000000" />
</Stream>
</Connect></Response>
<!-- ConversationRelay: managed STT and TTS, you own the text logic -->
<Response><Connect>
<ConversationRelay url="wss://voice.example.com/relay"
transcriptionProvider="Deepgram" speechModel="flux"
ttsProvider="ElevenLabs" interruptible="speech"
welcomeGreeting="Hi, how can I help?" />
</Connect></Response>
All attributes above are in the ConversationRelay reference. The ConversationRelay figures are vendor numbers measured inside Twilio's network. Run the same test script against both options.
4. Stream everything
Problem: Waiting for a full transcript, a full LLM answer and a full audio file serializes work that could overlap.
Fix: Stream audio to STT, stream LLM tokens, flush text to TTS at the first clause boundary, and forward audio to Twilio as soon as it lands. Twilio's ConversationRelay guidance is to stream tokens as soon as they are available, rather than waiting for the full response (ConversationRelay). ElevenLabs offers a WebSocket TTS endpoint built for LLM output, and warns that a large chunk schedule can stall generation when text arrives slowly (ElevenLabs).
// ConversationRelay: forward tokens as they arrive, mark the last one.
for await (const token of llmStream) ws.send(JSON.stringify({ type: 'text', token, last: false }));
ws.send(JSON.stringify({ type: 'text', token: '', last: true }));
5. Tune endpointing and handle barge-in
Problem: Wait too long and the bot feels slow. Cut too early and it talks over callers.
Fix: Twilio notes that fixed end-of-turn defaults sit around 500 ms, that smart endpointing can lower the median but cause tail spikes, and that aggressive thresholds interrupt users (core latency guide). Deepgram's default endpointing is 10 ms, built for short commands; it recommends 300 to 500 ms for conversations with natural pauses. Note that is_final is not the end of the turn; wait for speech_final (Deepgram endpointing).
Deepgram Flux puts turn detection in the model (about 260 ms end of turn, default eot_threshold 0.7). Setting eager_eot_threshold gives you EagerEndOfTurn events so you can start the LLM early and cancel on TurnResumed (Deepgram). It costs extra LLM calls. In ConversationRelay, speechModel="flux" uses Flux turn detection instead of Twilio's, and interruptSensitivity defaults to high.
On raw Media Streams, send clear when your VAD hears the caller during bot speech. Twilio empties its buffer and returns mark messages for audio that never played (Media Streams messages). Also cancel your LLM and TTS, and tag each response with a generation ID so late chunks from a cancelled reply get dropped.
{ "event": "clear", "streamSid": "MZ..." }
6. Keep mu-law 8 kHz end to end
Problem: Resampling and transcoding add CPU time, buffering and artifacts.
Fix: Media Streams always sends audio/x-mulaw, 8000 Hz, mono. Audio you send back must be base64 mu-law 8 kHz with no file headers, can be any size, and plays in the order received (Media Streams messages). Twilio warns that provider APIs often convert audio silently to what the model expects, which adds latency (core latency guide). Ask providers for mu-law directly: Deepgram Flux accepts mulaw at 8000 Hz and recommends 80 ms chunks (Flux quickstart), and ElevenLabs can return mu-law 8 kHz audio (ElevenLabs).
wss://api.deepgram.com/v2/listen?model=flux-general-en&encoding=mulaw&sample_rate=8000
At 8 kHz mu-law, 20 ms of audio is 160 bytes. Deepgram's general advice is 20 to 100 ms buffers (Deepgram).
7. Pre-connect sockets and remove cold starts
Problem: Opening STT and TTS sockets on first use puts connection setup inside turn one. Serverless cold starts are worse.
Fix: Open provider sockets when Twilio's start message arrives. Deepgram's advice for high connection latency is to pool and reuse WebSocket connections (Deepgram). Keep the audio loop on always-on compute with minimum instances. Serverless is fine for work outside the loop.
8. Short prompts, fast first replies
Problem: Long prompts and big models push up time to first token.
Fix: Twilio calls LLM time to first token the key metric, because TTS can start as soon as the first token lands (core latency guide). Trim the system prompt, move reference data into tool calls, use a fast model, and say "Let me check that" when a tool call runs long. Never run irreversible actions from an eager, unconfirmed transcript.
9. Cache common TTS phrases
Problem: Greetings and confirmations get synthesized on every call.
Fix: Render them once at deploy time as mu-law 8 kHz and replay the bytes. Include voice, model and phrase version in the cache key, and never cache personal data. With ConversationRelay, welcomeGreeting plays right after answer, and setting elevenlabsTextNormalization to off gives lower latency (ConversationRelay best practices).
10. Keep webhooks fast
Problem: A slow voice webhook leaves the caller in dead air before the stream even opens.
Fix: Return TwiML at once and do CRM lookups, logging and n8n workflows after the stream is open. Twilio caps call-related HTTP requests at 15 seconds, and you can tune behavior with URL fragment overrides: ct (connect timeout, default 5,000 ms), rt (read timeout, default 15,000 ms), rc (retry count), rp (retry policy) and e (webhook edge, default ashburn). Leave the fragment out of signature validation (Twilio webhook connection overrides).
https://voice.example.com/twiml#ct=1000&rt=3000&rc=1&rp=ct,rt
These timeout values are starting points to adjust, not Twilio defaults (5,000 ms and 15,000 ms). Set yours from measured response times.
11. Trim network overhead and watch your send buffer
Problem: Extra proxies, repeated TLS handshakes and compression on tiny frames add hops and CPU. A slow consumer lets audio pile up.
Fix: Terminate TLS once, skip layered proxies, reuse connections, and turn off per-message compression for audio. Watch ws.bufferedAmount and event-loop delay; a growing queue means you are behind real time.
const wss = new WebSocketServer({ server, path: '/media', perMessageDeflate: false });
12. Choose SIP codecs and edges on purpose
Problem: Codec mismatches force transcoding, and a distant SIP edge adds path length.
Fix: Elastic SIP Trunking supports PCMU and PCMA by default. Opus, G.729 and AMR-NB are Limited Availability and "not supported end to end" (Twilio Elastic SIP Trunking codec docs). For PSTN-facing agents, PCMU matches Media Streams audio and avoids a transcode. Set the SIP edge close to your PBX or media server.
Benchmarking: measure before you tune
Metrics
| Metric | Definition |
|---|---|
| Turn latency (mouth to ear) | Caller's last word to the first bot audio the caller hears |
| Platform turn latency | End of caller speech at the platform to outbound response audio |
| Time to first audio (TTFA) | Twilio uses it for the time from the end of caller speech to agent speech; write down your trigger |
| LLM TTFT, TTS TTFB | Request to first token; request to first audio bytes |
| p50, p90, p99 | Percentiles over many turns; p99 is what callers remember |
| Jitter, packet loss | Network health from Voice Insights |
How to measure
- Timestamp every hop on one monotonic clock: speech end, STT final, LLM request, first token, TTS request, first byte, first audio sent. Take speech end from the audio timeline or VAD, not from the endpoint event, or the endpointing delay disappears from your data.
- Use Media Streams fields. Each
mediamessage carriestimestamp, a presentation time in ms from stream start. It is not a Unix time. Twilio echoes amarkwhen the audio sent before it has finished playing, so a mark after your first chunk gives an upper bound on first audio. It is not the first audible sample (Media Streams messages). - Use Voice Insights. The ConversationRelay summary splits response time into Network, STT, Application and TTS, with an event timeline and waveforms. It measures from Twilio's network and excludes the last mile. STT timing is typically accurate within 100 ms for English and up to 250 ms for other languages (call summary).
- Record both legs of a test call and measure the gap between the caller's last word and the bot's first sound. This is your ground truth.
- Report percentiles, not averages, over a representative sample, as Deepgram also advises.
Code: per-turn timer, stream server, percentiles
Smoke-tested against a stub pipeline.
latency.js
// latency.js: per-turn timestamps on one monotonic clock, logged as JSON lines.
const fs = require('fs');
const now = () => Number(process.hrtime.bigint()) / 1e6; // ms
class TurnTimer {
constructor(callSid, turn) { this.callSid = callSid; this.turn = turn; this.t = {}; this.done = false; }
mark(name, at = now()) { if (!(name in this.t)) this.t[name] = at; return this; } // first write wins
summary() {
const d = (a, b) => (a in this.t && b in this.t ? +(this.t[b] - this.t[a]).toFixed(1) : null);
return {
callSid: this.callSid, turn: this.turn,
endpointing_ms: d('speech_end', 'stt_final'),
llm_ttft_ms: d('llm_request', 'llm_first_token'),
tts_ttfb_ms: d('tts_request', 'tts_first_byte'),
server_turn_ms: d('speech_end', 'first_audio_sent'),
mark_echo_ms: d('speech_end', 'first_mark_echo'), // upper bound on first audio
};
}
flush(file = 'turns.jsonl') {
if (this.done) return; this.done = true;
fs.appendFileSync(file, JSON.stringify(this.summary()) + '\n');
}
}
module.exports = { TurnTimer, now };
server.js
// server.js: bidirectional Media Streams server with per-hop timestamps and barge-in.
// Plug your STT, LLM and TTS into the `pipeline` hooks.
const http = require('http');
const express = require('express');
const { WebSocketServer } = require('ws');
const twilio = require('twilio');
const { TurnTimer, now } = require('./latency');
const app = express();
app.use(express.urlencoded({ extended: false }));
// Voice webhook: return TwiML at once. No database or LLM calls here.
app.post('/twiml', (req, res) => {
const vr = new twilio.twiml.VoiceResponse();
const stream = vr.connect().stream({ url: `wss://${req.headers.host}/media` }); // wss only, no query string
stream.parameter({ name: 'from', value: req.body.From || '' }); // arrives in start.customParameters
res.type('text/xml').send(vr.toString());
});
const server = http.createServer(app);
const wss = new WebSocketServer({ server, path: '/media', perMessageDeflate: false });
function attach(pipeline) {
wss.on('connection', (ws) => {
let streamSid = null, callSid = null, turn = 0, timer = null, generation = 0;
const send = (o) => ws.readyState === ws.OPEN && ws.send(JSON.stringify(o));
ws.on('message', (raw) => {
const msg = JSON.parse(raw);
switch (msg.event) {
case 'start':
streamSid = msg.start.streamSid; callSid = msg.start.callSid;
pipeline.warm?.(); // open STT and TTS sockets now, not on the first turn
break;
case 'media':
pipeline.onAudio(msg.media.payload); // base64 mu-law 8 kHz, inbound track
break;
case 'mark':
if (timer && msg.mark.name === `t${turn}-first`) { timer.mark('first_mark_echo'); timer.flush(); }
break;
case 'stop':
ws.close();
break;
}
});
// Called by your STT/VAD when the caller's turn ends.
pipeline.onTurnEnd(async (transcript, speechEndAt) => {
const gen = ++generation;
timer = new TurnTimer(callSid, ++turn);
timer.mark('speech_end', speechEndAt ?? now()).mark('stt_final');
let first = true;
for await (const chunk of pipeline.respond(transcript, timer)) {
if (gen !== generation) return; // a barge-in started a newer turn; drop stale audio
send({ event: 'media', streamSid, media: { payload: chunk } });
if (first) {
timer.mark('first_audio_sent');
send({ event: 'mark', streamSid, mark: { name: `t${turn}-first` } });
first = false;
}
}
const t = timer; setTimeout(() => t.flush(), 5000); // fallback if no mark echo
});
// Called by your VAD when the caller speaks over the bot.
pipeline.onBargeIn?.(() => {
generation++; // invalidate the running response
send({ event: 'clear', streamSid }); // Twilio drops buffered audio and returns pending marks
pipeline.cancel?.();
});
});
}
module.exports = { app, server, attach };
percentiles.py
# percentiles.py: p50/p90/p99 per metric from turns.jsonl (nearest-rank method).
import json, math, sys
from collections import defaultdict
def pct(vals, p):
return vals[max(0, math.ceil(p / 100 * len(vals)) - 1)]
data = defaultdict(list)
for line in open(sys.argv[1] if len(sys.argv) > 1 else "turns.jsonl"):
for k, v in json.loads(line).items():
if k.endswith("_ms") and v is not None:
data[k].append(v)
print(f"{'metric':<18}{'n':>5}{'p50':>9}{'p90':>9}{'p99':>9}")
for k, v in sorted(data.items()):
v.sort()
print(f"{k:<18}{len(v):>5}{pct(v,50):>9.1f}{pct(v,90):>9.1f}{pct(v,99):>9.1f}")
In production, also validate the X-Twilio-Signature header on the webhook and on the WebSocket upgrade.
Benchmark test plan
This is the test design we recommend. It is not an industry standard.
- Volume: 50 calls per configuration, 10 scripted turns each, so every row rests on 500 turns. Collect more for a stable p99.
- Fixed script: the same recorded caller audio each run: a short answer, a long answer, a number read-back, a tool-call turn, a hesitation and a barge-in.
- One change per run: edge, region, STT model, endpointing, LLM or TTS voice.
- Callers: your real users' regions, including one mobile network.
- Separate runs for cold and warm sessions, and for idle and concurrent load.
- Log per turn: config ID, call SID, turn number, every hop timestamp, transcript and response length. Report failures and timeouts separately.
Your results sheet
Fill in one row per configuration with your own measurements.
| Config | Calls | p50 turn | p90 turn | p99 turn | TTFA | Notes |
|---|---|---|---|---|---|---|
Baseline (<Gather>, default setup) |
||||||
| Bidirectional stream, co-located region | ||||||
| Plus full streaming | ||||||
| Plus tuned endpointing | ||||||
| Plus cached phrases and warm sockets |
What published benchmarks show
Use these as reference points, not a league table. Each source measured something different, so compare your own results with the row closest to your setup.
| Source | What was measured | Median | Tail |
|---|---|---|---|
| Twilio ConversationRelay | Twilio's internal benchmarks; Twilio does not say whether the caller's phone line is included | 491 ms (p50) | 713 ms (p95) |
| Twilio starting targets | Target for a plain cascaded agent, mouth to ear | 1,115 ms | 1,400 ms upper limit |
| Cozzo, phone calls | Eight platforms on default setups, 89 scripted calls on 20 Oct 2026, Twilio calling each vendor over SIP, end of caller audio to start of agent reply | 1.04 s to 1.86 s | p90: 1.22 s to 2.14 s |
| Cozzo, browser | Four platforms, 41 calls, no phone line | 0.41 s to 1.15 s | Not published |
| Spanish phone-negotiation study (arXiv) | Pipecat, LiveKit Agents and GPT-Live, 77 calls each, measured from the listener's side without a telephone network, tool calls in about 65% of cascade responses | 2,616 ms, 3,090 ms and 2,445 ms | p95: 4,554 ms, 4,630 ms and 4,814 ms |
Target benchmarks
| Rating | Mouth-to-ear turn latency | Basis |
|---|---|---|
| Good | At or under about 1,100 ms | Twilio's 1,115 ms starting target |
| Acceptable | Up to 1,400 ms | Twilio's upper limit |
| Poor | Above 1,400 ms | Above Twilio's upper limit; Twilio's dashboard already flags 1.2 s |
Managed stacks can go lower: ConversationRelay publishes a p50 of 491 ms and p95 of 713 ms in Twilio's internal benchmarks, which Twilio does not say include the caller's phone line (Twilio). Compare like with like.
Reference architecture
Caller -> PSTN/carrier -> nearest Twilio media edge -> Twilio region
-> wss:// <Connect><Stream> or <ConversationRelay>
-> App server: same metro as that edge, always on, no cold starts
|-- STT socket (pre-connected, mu-law 8 kHz in)
|-- LLM stream (fast model, short prompt)
|-- TTS socket (pre-connected, ulaw_8000 out, cached phrases)
'-- TurnTimer -> JSONL -> p50/p90/p99
<- base64 mu-law frames <- Twilio <- caller
Async workers (CRM, n8n, logging) sit outside the audio loop.
Common mistakes
Nine mistakes are worth ruling out first. Each one has a symptom you can hear on a call and a fix. Where Twilio, Deepgram, ElevenLabs or an independent study publishes a number, it is quoted with a link.
| Mistake | What you will notice | Fix |
|---|---|---|
Expecting the REST client edge to move call media |
You change the edge and nothing changes on the call. Twilio's docs say the edge label on a REST request only selects where the request is processed, and that Twilio cannot guarantee where REST traffic enters (Understanding Edge Locations). | Place your servers near the media edge. Use the SIP or Voice SDK edge settings where media latency is the goal. |
| STT, LLM and TTS in different regions | A slow turn that gets worse for callers far from your stack. Twilio counts at least ten network traversals per response and budgets about 10 ms per hop. Deepgram puts network transit at 20 to 200 ms depending on geography, and ElevenLabs lists 100 to 150 ms to first byte from North America and Europe but 150 to 200 ms from South Asia and North East Asia (Twilio, Deepgram, ElevenLabs). | Run the app server, STT, LLM and TTS in one region, next to the media edge. |
| Waiting for the full LLM answer before calling TTS | A long answer means a long silence, because the caller hears nothing until the last word is written. Twilio's budget counts only the time to the first token (375 ms target, 750 ms upper limit), not the full answer (Twilio). | Stream LLM tokens into a TTS WebSocket and start audio at the first clause (ElevenLabs). |
Treating is_final as the end of the turn |
The bot either jumps in mid-sentence or waits too long. Twilio says fixed end-of-turn defaults sit around 500 ms and that interrupting a caller feels far worse than a little extra latency (Twilio). In one external test, LiveKit's end-of-turn detector waited its full 2.5 s in 31.2% of responses, against a usual 578 ms (arXiv study). | Use real end-of-turn detection (Deepgram's Flux reports it in 100 to 500 ms) and tune against false interruptions, not the median alone (Deepgram). |
| Opening provider sockets on first use | The first turn is much slower than the rest, because the caller waits while DNS, TCP, TLS and the WebSocket upgrade finish. Deepgram calls this a one-time cost per session (Deepgram). | Open the STT and TTS sockets when the call starts, and reuse them. |
| Resampling mu-law to PCM and back for no reason | Extra work on every audio frame for no gain. Twilio's budget already spends 30 ms on buffering and 25 ms on decoding at its edge and warns that each extra encode, decode or jitter buffer adds delay (Twilio). No vendor publishes a figure for a resample step, so time yours. | Ask Deepgram for encoding=mulaw and ElevenLabs for ulaw_8000, and stay in mu-law 8 kHz. |
| Database lookups before returning TwiML | Dead air before the call even starts. Twilio's webhook defaults wait up to 5 s to connect and 15 s for a response (webhook overrides), and its dashboard flags any turn slower than 1.2 s (Twilio). In one external test, a single tool call added 0.9 to 1.1 s to the median response in all three architectures (arXiv study). | Return TwiML at once. Move lookups off the audio path, or run them while the caller hears a short filler. |
| Treating the mark echo as the first audible sample | Your logs look fast, but callers say it feels slow. A mark comes back when the audio before it has finished playing, so it is only an upper bound on first audio (Media Streams messages), and Voice Insights excludes the last mile (call summary). In an external test, the frameworks' own latency figures fell short of the listener's real wait by 9% (Pipecat) and 22% (LiveKit) (arXiv study). |
Record both legs of a test call and measure from the caller's last word to the bot's first sound. |
| Reporting averages instead of p90 and p99 | A healthy-looking dashboard and unhappy callers. In one external test, Pipecat's median response was 2,616 ms but its 95th percentile was 4,554 ms (arXiv study). In Cozzo's phone tests the p90 sat above the median on every platform, from 1.04 s median and 1.22 s p90 for Retell AI to 1.52 s and 2.14 s for LiveKit Agents (Cozzo). | Report p50, p90 and p99 for every hop, as Deepgram also advises. |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Long silence before the first reply | Cold sockets, slow webhook, uncached greeting | Pre-connect at start, return TwiML at once, cache the greeting |
| Every reply starts late | Long endpointing or slow first token | Time endpointing and TTFT separately; tune the larger one |
| Bot talks over the caller | No barge-in, no clear, sensitivity too low |
Send clear and cancel LLM and TTS; review interruptible and interruptSensitivity |
| Bot cuts the caller off | Endpointing too aggressive | Raise the silence threshold or eot_threshold |
| Choppy or robotic audio | Packet loss or jitter | Check Voice Insights; fix the network path or edge |
| Latency grows during a call | Audio backlog or a growing prompt | Watch bufferedAmount and queue depth; summarize old turns |
| Spiky p99 | Co-hosted STT and TTS, cold instances, rate limits | Separate hosts, keep instances warm, check provider limits |
FAQ
What is a good latency for a Twilio voice AI agent?
Twilio's starting target is a mouth-to-ear turn gap of about 1,115 ms, with 1,400 ms as the upper limit, and its dashboard flags turns over 1.2 seconds. ConversationRelay advertises a median under 0.5 seconds in Twilio's internal tests. In independent phone-call tests, median replies ranged from 1.04 s to 1.86 s across eight platforms (Cozzo). Treat these as numbers to beat in your own tests.
Does the Twilio edge location affect call latency?
Yes, for Voice SDK and SIP connections, where the edge directly influences media latency. For PSTN calls, media enters near the caller, so put your servers close to that edge. The REST client edge setting only picks the processing region and does not move call media.
Is ConversationRelay faster than Media Streams?
ConversationRelay runs STT and TTS inside Twilio and publishes a p50 of 491 ms in internal tests. A well-tuned Media Streams pipeline can compete, but you own every hop. Run the same script against both and compare p50 and p90 before you decide.
How do I measure Twilio call latency?
Log a timestamp at every hop on one monotonic clock, from speech end to first audio sent. Add Voice Insights for the Network, STT, Application and TTS breakdown, and record both legs of a test call to check the real gap. Report p50, p90 and p99.
Why is there a long pause before my voice bot replies?
Usually a long endpointing wait, a slow first LLM token, STT or TTS sockets opened on first use, or servers far from Twilio's media edge. Timestamp each hop on a few calls; the biggest gap shows where to start.
What audio format should I use with Twilio Media Streams?
Use mu-law at 8 kHz, mono. Media Streams sends that format and expects it back as base64 with no file headers. Ask your STT and TTS providers for mu-law directly, such as Deepgram encoding=mulaw and ElevenLabs ulaw_8000, to avoid hidden resampling.
Why does my voice bot talk over callers?
Barge-in is missing or too slow. Detect caller speech during bot audio, send a clear message to flush Twilio's buffer, and cancel your LLM and TTS. In ConversationRelay, review interruptible and interruptSensitivity, and turn on echoPromptFiltering if the bot is hearing itself.
Conclusion
Reducing call latency with Twilio Voice API comes down to a short list: servers next to the media edge, one region for the whole audio loop, streaming at every stage, careful endpointing, and measurement you trust. Start with the budget table, instrument one call, and change one thing at a time.
If you want a second pair of eyes, Octacer builds and tunes production voice agents and the AI workflow automation around them. Book a call and bring your latency logs.
Take this article with you
Free PDF of this article. Unlock it with your email.
Written by
Octacer Team
Octacer
Written from real client builds at Octacer: the systems, the trade-offs, and what we would do again.
Get new posts by email
Practical automation and engineering notes. No spam.