AI Summary: This article covers how to architect a real-time voice pipeline that hits sub-100ms voice agent latency, written for backend and API integration engineers building AI phone agents in 2026. The Opus audio codec (RFC 6716) supports frame sizes from 2.5 ms to 60 ms and sampling rates from 8 to 48 kHz, which directly shapes the latency budget at every hop. Engineers must decide where media terminates, how to stream STT, LLM, and TTS in parallel, and how to handle barge-in without queued audio leaking through. Teler targets sub-100ms packet delivery and exposes configurable chunk sizes and a {"type": "clear"} flush command that makes interruption handling tractable.
Scope: This walkthrough covers the end-to-end media path from PSTN carrier through Teler’s WebSocket transport to an AI model and back, verified against the API specification documented in September 2026. It does not cover SIP-side PBX configuration or client-side WebRTC browser integration.
Quick Answer: To hit sub-100ms voice agent latency in 2026, stream all three pipeline stages (STT, LLM, TTS) concurrently, start TTS synthesis on the first sentence fragment rather than waiting for a complete LLM response, colocate your services in the same cloud region, and configure your transport layer to send audio chunks of 20 to 2000 ms with at least 500 ms returned per write.
Voice agent latency is the elapsed time between a caller finishing a sentence and hearing the first word of the agent’s response. Keeping that gap under 100 milliseconds requires every stage of the STT-LLM-TTS pipeline to stream concurrently rather than completing sequentially.
What is voice agent latency?
Voice agent latency is the measurable delay between the end of a caller’s utterance and the first audio sample of the agent’s reply reaching the caller’s ear. It occupies the application layer of a real-time voice pipeline, sitting above the transport protocol (WebSocket or RTP) and below the conversational logic of the LLM. It does not include the time a caller spends waiting on hold or in a queue. What a developer must supply themselves: end-of-turn detection, a streaming bridge between the telephony transport and the model API, and a mechanism to cancel queued TTS audio when the caller interrupts.
Why is low voice agent latency hard to achieve?
The core constraint is that three high-latency operations, speech-to-text (STT), large language model inference, and text-to-speech (TTS) synthesis, sit in series on the critical path. Run them sequentially and the floor is the sum of all three. One practitioner reported end-to-end times of 3.8 to 7.3 seconds before optimization, dropping to sub-500ms after streaming all three stages and colocating services.
Time to first token (TTFT) from the LLM dominates the perceived experience. A caller does not hear silence as “the model is thinking”; they hear it as a broken connection. Voice is a turn-taking problem, not a transcription problem. The two transitions that define the experience are: cancel instantly on barge-in, and respond instantly on end-of-turn. Both require the pipeline to be event-driven, not batch-driven.
Geography compounds the problem. Cross-region placement between the telephony gateway, the STT endpoint, and the LLM inference cluster adds round-trip time before any model work starts. A streaming pipeline with services spread across three cloud regions can still miss the 100ms target even if each individual component is fast.
How does audio travel from carrier to model and back?
Understanding where each hop adds delay is the prerequisite for cutting it. The table below maps the full path for a PSTN call routed through a programmable voice API.
| Hop | Format | Sample rate | Transport | Owner |
|---|---|---|---|---|
| PSTN carrier to telephony gateway | G.711 PCM (mu-law or a-law) | 8 kHz | SIP/RTP (RFC 3550) | Carrier + gateway |
| Gateway to application server | Raw PCM or Opus (RFC 6716) | 8 kHz or 16 kHz | WebSocket (RFC 6455) | Telephony API (e.g., Teler) |
| Application server to STT engine | PCM or Opus | 16 kHz preferred | WebSocket or HTTP streaming | Developer |
| STT to LLM | Text tokens | N/A | HTTP/2 or WebSocket | Developer |
| LLM to TTS | Text tokens (streamed) | N/A | HTTP/2 or WebSocket | Developer |
| TTS to application server | PCM or MP3 | 24 kHz (OpenAI Realtime) | WebSocket | Developer + TTS provider |
| Application server back to caller | PCM (resampled if needed) | 8 kHz | WebSocket to gateway | Developer + telephony API |
The resampling hop between TTS output and the telephony gateway is where many teams lose 20 to 40 ms without realizing it. If your TTS provider outputs 24 kHz (as OpenAI Realtime does) and your telephony transport runs at 8 kHz, you must resample before injecting audio back into the call. That conversion is not free, and it belongs in your latency budget.
What do you need before you start?
- A Teler account with an API key and at least one provisioned phone number (E.164 format, e.g., +91xxxxxxxxxx)
- A server with a public WebSocket endpoint reachable by Teler’s infrastructure (ngrok works for local development)
- Python 3.11 or later, with
websockets>=12.0andnumpyinstalled (pip install websockets numpy) - An STT provider account (Deepgram, AssemblyAI, or equivalent) with a streaming WebSocket endpoint
- An LLM provider account with a streaming completion endpoint
- A TTS provider account that supports streaming synthesis (ElevenLabs, OpenAI, or equivalent)
- All three AI services deployed in the same cloud region as your application server
- Familiarity with async Python and WebSocket framing
How to implement a sub-100ms voice agent latency pipeline
Step 1: Configure the Teler media stream
When Teler connects a call to your WebSocket endpoint, it begins sending audio frames immediately. Configure the stream sample rate and chunk size to match your STT engine’s preferred input. Teler accepts “8k” or “16k” (default “8k”), though the start message currently always reports 8000. Audio you send back must be 8 kHz and chunk sizes from 20 to 2000 ms in multiples of 20 ms (default 400 ms). A 20 ms chunk at 8 kHz is 320 bytes of 16-bit PCM; at 16 kHz it is 640 bytes. Set the chunk size to 20 ms. With the 400 ms default, Teler collects 400 ms of caller audio before forwarding it, which delays everything downstream. See the Teler streaming configuration reference for the full parameter list.
import asyncio
import websockets
import json
async def handle_call(websocket):
audio_queue = asyncio.Queue()
transcript_queue = asyncio.Queue()
stt_task = None
try:
async for message in websocket:
event = json.loads(message)
if event["type"] == "start":
stt_task = asyncio.create_task(
stream_to_stt(audio_queue, transcript_queue))
elif event["type"] == "audio" and stt_task:
await audio_queue.put(
base64.b64decode(event["data"]["audio_b64"]))
finally:
# No stop message: Teler closes the socket when the call ends
await audio_queue.put(None) Watch the event["type"] field: Teler sends a “start” message first, then “audio” messages for the rest of the call. There is no stop message; when the call ends, Teler closes the WebSocket.
Step 2: Stream STT without waiting for end-of-utterance
Send audio chunks to your STT engine as they arrive from Teler rather than buffering a complete utterance. Most streaming STT APIs return partial transcripts (interim results) and a final transcript flagged with an end-of-utterance marker. Your pipeline should forward interim results to the LLM for speculative processing, but only commit to a response on the final transcript. This approach cuts the STT contribution to latency from hundreds of milliseconds to near zero on the hot path.
async def stream_to_stt(audio_queue, transcript_queue):
# Connect to your STT provider's streaming WebSocket
async with websockets.connect(STT_WS_URL, additional_headers={"Authorization": f"Token {STT_KEY}"}) as stt_ws:
async def send_audio():
while True:
chunk = await audio_queue.get()
if chunk is None:
break
await stt_ws.send(chunk)
async def receive_transcripts():
async for msg in stt_ws:
result = json.loads(msg)
if result.get("is_final"):
await transcript_queue.put(result["transcript"])
await asyncio.gather(send_audio(), receive_transcripts()) The is_final field name varies by STT provider; check your provider’s documentation for the exact field and confirm it signals true end-of-utterance, not just a pause.
Step 3: Start TTS on the first sentence fragment
Do not wait for the LLM to finish generating a complete response before starting TTS. Instead, buffer LLM output tokens until you have a complete sentence (ending with a period, question mark, or exclamation point), then send that fragment to TTS immediately. The TTS provider begins synthesizing while the LLM continues generating the next sentence. This pipeline overlap is the single largest latency reduction available after switching to streaming.
async def llm_to_sentences(transcript, sentence_queue):
buffer = ""
async for token in stream_llm(transcript):
buffer += token
stripped = buffer.rstrip()
# Flush on sentence boundaries, skipping very short fragments
if stripped.endswith((".", "?", "!")) and len(stripped) >= 20:
await sentence_queue.put(stripped)
buffer = ""
if buffer.strip():
await sentence_queue.put(buffer.strip())
await sentence_queue.put(None)
async def tts_worker(sentence_queue, tts_audio_queue):
# Runs concurrently, so the LLM keeps generating while TTS synthesizes
while (sentence := await sentence_queue.get()) is not None:
await synthesize_and_enqueue(sentence, tts_audio_queue)
# Run both together:
# await asyncio.gather(llm_to_sentences(t, sq), tts_worker(sq, aq)) Sentence boundary detection on raw token streams is imprecise; a period inside a number like “3.8” will trigger a premature flush. Add a minimum fragment length guard (e.g., skip flush if len(buffer) < 20) to avoid synthesizing single-word fragments.
Step 4: Inject audio back into the call and handle barge-in
Send synthesized audio back to Teler over the same WebSocket connection. Teler requires you to send at least 500 ms of audio per write to avoid choppy playback. When the caller interrupts (barge-in), cancel your own LLM and TTS work, then send {“type”: “interrupt”, “chunk_id”: “”} using the first chunk_id of the current response. Without this flush, the caller hears the tail of the previous response after they have already started speaking. See the Teler call control documentation for the full set of live call control commands.
import base64
async def inject_audio(websocket, pcm_bytes, chunk_id):
# pcm_bytes must be 16-bit linear PCM at 8 kHz
payload = base64.b64encode(pcm_bytes).decode("utf-8")
await websocket.send(json.dumps({
"type": "audio",
"audio_b64": payload,
"chunk_id": chunk_id,
}))
async def handle_barge_in(websocket, response_task, tts_audio_queue, first_chunk_id):
# 1. Cancel in-flight LLM and TTS work
response_task.cancel()
# 2. Drop audio queued locally that hasn't been sent yet
while not tts_audio_queue.empty():
tts_audio_queue.get_nowait()
# 3. Stop playback on Teler's side from this response's first chunk onward
await websocket.send(json.dumps({"type": "interrupt", "chunk_id": first_chunk_id})) The {"type": "clear"} message must arrive at Teler before the next {"type": "media"} write; ordering matters because Teler processes these messages sequentially on the connection.
What the engineers who built this say
Most teams discover their voice agent latency problem is not the model. It is the resampling hop they added between the carrier and the STT engine, or the fact that they are waiting for a full LLM response before touching TTS. Fix the pipeline shape first, then tune the model.
– Subhash Kalluri, Founder & CEO, FreJun
What breaks voice agent latency in production?
The table below summarizes the failure modes observed in production deployments, drawn from GitHub issues and practitioner reports.
| Symptom | Root cause | Fix | Frequency |
|---|---|---|---|
| Response arrives 3 to 7 seconds late | Pipeline runs STT, LLM, TTS sequentially; TTFT dominates | Stream all three stages concurrently; start TTS on first sentence fragment | Reported multiple times |
| Caller cannot interrupt the agent | Barge-in not implemented or clear message not sent on detection | Send {"type": "clear"} immediately on VAD trigger; treat interruption as a first-class control path | Reported multiple times |
| VAD fires when nobody is speaking | Over-sensitive or misconfigured semantic VAD | Tune VAD sensitivity threshold; add a minimum energy floor before triggering | Reported once |
| Agent randomly switches language mid-call | Unresolved in source thread | No confirmed fix reported | Reported once |
| Latency doubles in telephony contexts | Unresolved in source thread (LiveKit agents issue #3685) | No confirmed fix reported | Reported once |
| Streaming pipeline still misses budget | Services deployed across multiple cloud regions | Colocate STT, LLM, TTS, and application server in the same region | Reported once |
The failure that catches most teams is the sequential pipeline. Engineers prototype with a request-response pattern because it is simpler to reason about, then discover in load testing that the floor is 3 to 4 seconds. Switching to concurrent streaming is not a micro-optimization; it is a structural change to the pipeline shape.
One honest limitation of Teler worth stating: the sub-100ms packet delivery target is a specification for the transport layer, not a measured end-to-end benchmark. The actual latency a caller experiences depends on the STT, LLM, and TTS providers you choose, the cloud region you deploy in, and how efficiently your application server bridges the three stages. Teler controls the media path; it does not control model inference time.
Which transport approach fits your voice agent latency target?
Three distinct architectures appear in production deployments. Each makes a different trade-off between where media terminates, operational burden, and latency floor.
| Approach | Media terminates at | Latency cost | Operational burden | Lock-in |
|---|---|---|---|---|
| WebSocket media streaming (e.g., Teler) | Application server | Low, if colocated | Medium: developer owns bridging logic | Low: model-agnostic |
| SIP trunk into RTP media server | Media server | Low to medium | High: developer owns SIP signaling (RFC 3261) and RTP/RTCP (RFC 3550) | Low: standard protocols |
| Managed all-in-one platform | Platform | Medium to high | Low: platform owns the media path | High: proprietary APIs |
WebSocket media streaming is the right choice when you need model flexibility and want to own the pipeline without building SIP signaling from scratch. The SIP trunk approach is right when you are integrating with existing PBX infrastructure or need direct PSTN interconnect at the carrier level. Managed platforms are right when shipping speed matters more than latency optimization, but one practitioner’s data suggests a custom STT-LLM-TTS pipeline can hit 2x lower latency than all-in-one platforms when built correctly.
Voice is a turn-taking problem, not a transcription problem. VAD alone fails; you need semantic end-of-turn detection. TTFT dominates everything. In voice, the first token is the critical path.
– Nick Tikhonov, author of the sub-500ms voice agent build (news.ycombinator.com, March 2026)
Frequently asked questions
What audio format does Teler send over WebSocket?
Teler streams raw PCM audio encoded as base64 inside JSON frames. The sample rate is configurable at 8k or 16k (default 8k), and chunk size runs from 20 to 2000 ms in multiples of 20 ms. If you connect to OpenAI Realtime, which outputs at 24 kHz, you must resample before injecting audio back into the call at 8 kHz.
Why does barge-in still let audio through after I detect the interruption?
You are likely sending the VAD trigger to your application logic but not flushing queued audio on the telephony side. Send {"type": "clear"} to Teler immediately when your VAD fires. This flushes all audio buffered in the transport layer. If you only stop sending new audio without clearing the buffer, the caller hears the tail of the previous response.
Should I use WebSocket media streaming or a SIP trunk for a new voice agent?
WebSocket media streaming is simpler to start with and gives you model flexibility without building SIP signaling (RFC 3261). Use a SIP trunk when you need to integrate with existing PBX infrastructure or require direct carrier interconnect. The latency floors are comparable when both are colocated, but the operational burden of SIP is significantly higher for teams without telephony experience.
What happens to voice agent latency under high call volume?
Latency under load is primarily a function of LLM inference throughput and STT streaming capacity, not the telephony transport. The transport layer scales horizontally. The bottleneck at scale is typically the LLM provider’s token generation rate per concurrent request. Profile your LLM provider’s P95 TTFT under your expected concurrency before committing to a latency SLA.
Does Teler handle end-of-turn detection, or must I build that myself?
You must build end-of-turn detection yourself. Teler delivers raw audio frames and call control events; it does not perform VAD or semantic end-of-turn classification. You can use a VAD library on your application server, or use the interim and final transcript signals from your STT provider as a proxy for turn boundaries. Semantic VAD (detecting intent to yield the floor) is more reliable than energy-based VAD alone.
What is the minimum chunk size I should send back to Teler?
Teler requires you to send back at least 500 ms of audio per write to avoid choppy playback. The configurable chunk size (20 to 2000 ms) controls how Teler delivers audio to your server, but the return path has its own minimum. Buffer your TTS output until you have at least 500 ms before writing it back over the WebSocket connection.
Can I use Opus instead of raw PCM on the Teler WebSocket?
The Teler documentation specifies PCM over WebSocket for the media stream. Opus (RFC 6716) is the codec used in WebRTC and RTP paths, where it supports 8 to 48 kHz sampling and frame sizes from 2.5 to 60 ms. If your STT engine prefers Opus, you would transcode from the PCM stream Teler delivers. Check the Teler audio format documentation for any updates to supported input formats.
What should I measure to know if my pipeline is actually hitting sub-100ms?
Instrument four timestamps: end-of-utterance detection, first STT final transcript, first LLM token, and first audio byte injected back into the call. The gap between end-of-utterance and first audio byte is your end-to-end voice agent latency. Log P50, P95, and P99 separately; P95 is what callers experience on a bad day, and it is the number that matters for production readiness. For more on testing voice agents for latency and quality, see the linked guide.
What you can build once you control voice agent latency
With voice agent latency under 100ms, the conversation stops feeling like a demo and starts feeling like a phone call. The one decision that matters most is pipeline shape: concurrent streaming across STT, LLM, and TTS is not optional at this target, it is the architecture. If your deployment constraints force sequential processing or cross-region service placement, budget for a higher latency floor and communicate that honestly to stakeholders. For teams ready to build on a transport layer designed for this target, the Teler programmable voice API exposes the raw media stream, barge-in control, and the low-latency media streaming infrastructure needed to hit this target without building telephony from scratch. Check current Teler pricing before committing to a build.