My Obsession with Voice Agents: What ElevenLabs Taught Me About Latency, Turn-Taking and Interruption

Dark diagram of a voice agent pipeline from microphone through VAD, speech to text, LLM and TTS to the speaker, with a barge-in arrow and a speech waveform above
Six stages, one number that matters: time from the end of your sentence to the first sound back.

I worked on voice before it was fashionable. At Amazon Alexa I spent my days on the plumbing behind "Alexa, turn off the lights": high-throughput services where a few hundred milliseconds decided whether a product felt magic or broken. Then for a few years voice felt solved and boring. Then, at the end of 2024, I heard an ElevenLabs agent breathe in before answering a question, and I lost most of 2025 to it.

I already wrote about the voice generation side, the models and algorithms and my local experiments, in an earlier post. This one is about voice agents: systems you talk to and that talk back, in real time, and why the hard part is not the voice at all.

What ElevenLabs got right

Everyone talks about how good ElevenLabs voices sound. They do sound good. But the voice quality is not what hooked me. Plenty of TTS sounded fine in 2023. What hooked me was timing:

  • The agent answered fast enough that I did not notice waiting.
  • When I interrupted, it stopped talking. Immediately, mid-word, the way a person does.
  • It did not jump in during my pauses when I was thinking, but it did not leave me hanging when I was done either.

That is turn-taking, and it is the whole game. Conversation research has measured the gap between one person finishing and the next starting at around 200 milliseconds on average, across very different languages. We start planning our reply while the other person is still talking. A voice agent that takes two seconds to answer does not feel slow. It feels like something is wrong with it, or with you.

ElevenLabs advertises around 75 ms of model latency for its Flash TTS model. That number alone tells you where they think the battle is. So I set out to understand the battle, by building the pipeline myself.

The pipeline everyone builds

Diagram of a voice agent pipeline on a dark background: microphone, VAD for endpointing, speech to text, LLM first token, TTS first audio and speaker playback, with a dashed barge-in arrow from playback back to the microphone and a target of under 800 milliseconds from end of speech to first audio
The cascaded voice agent. Six stages, and the user only experiences the sum of their delays, from the moment they stop talking to the first sound back.

Every voice agent I have built or taken apart has these stages:

  1. Capture the microphone, usually 48 kHz in the browser.
  2. VAD (voice activity detection): decide when the user is speaking and, much harder, when they have finished.
  3. STT: turn speech into text.
  4. LLM: decide what to say.
  5. TTS: turn text back into speech.
  6. Playback, with the ability to stop instantly.

There are speech-to-speech models that skip the text in the middle, and they are impressive. But the cascade is still what most production agents run, because you can swap any stage, log every stage, and put guardrails on the text. It is also where all the lessons are, so it is what I built.

The latency budget

The number that matters is the time from the user stops talking to the first sound of the reply:

T_response = T_endpoint + T_stt + T_llm_first_token + T_first_sentence + T_tts_first_audio + T_network

My first version ran each stage to completion before starting the next. Wait for the user to finish, transcribe the whole clip, wait for the full LLM answer, synthesise the full answer, play it. It worked, and it was unusable:

Two horizontal stacked bar charts of response latency: when every stage waits for the one before, endpointing 600, STT 450, LLM first token 700, first sentence 900, TTS 650 and network 150 milliseconds add up to 3,450 ms; when every stage streams, 250, 120, 350, 0, 180 and 80 add up to 980 ms
The same pipeline, waiting versus streaming. The budget I designed against. Every stage that can start on partial input should.

The fix is not a faster model. It is streaming every stage, so each one starts on partial input from the one before:

  • STT streams partial transcripts while the user is still speaking, so the final transcript is ready almost as soon as they stop.
  • The LLM streams tokens.
  • TTS starts on the first sentence, not the full answer.
  • Audio plays as soon as the first chunk arrives.

The "first sentence complete" row drops to zero because it overlaps with everything else. That one change took my agent from about three and a half seconds to under one.

Endpointing: the hardest 300 milliseconds

The most underrated stage is the first one. The agent cannot answer until it decides you are finished, and every way of deciding is wrong some of the time:

  • Wait too long after silence and the agent feels slow.
  • Wait too little and it interrupts you every time you pause to think.

The simplest endpointer is energy based. Split audio into 20 ms frames, measure energy, track the noise floor, and declare end of turn after enough consecutive quiet frames. The "enough" is called the hangover.

Two plots sharing a time axis: a speech-like waveform with seven bursts, and below it frame energy in decibels with an orange dashed threshold line twelve decibels above the noise floor and a red vertical line marking the end of turn after 300 milliseconds below threshold
Energy-based endpointing. The red line fires only after 300 ms below the threshold, so the short gaps between words do not end the turn.
import numpy as np


class EnergyEndpointer:
    """Frame-energy VAD with an adaptive noise floor and a hangover before end of turn."""

    def __init__(self, sample_rate=16000, frame_ms=20, margin_db=12.0, hangover_ms=300):
        self.frame = sample_rate * frame_ms // 1000
        self.margin_db = margin_db
        self.hangover_frames = hangover_ms // frame_ms
        self.noise_db = -60.0
        self.speaking = False
        self.quiet = 0

    def feed(self, pcm: np.ndarray) -> str | None:
        """Feed one frame of float32 audio. Returns 'start', 'end' or None."""
        energy_db = 10 * np.log10(np.mean(pcm ** 2) + 1e-10)
        if not self.speaking:
            # Follow the room slowly while nobody is talking.
            self.noise_db = 0.95 * self.noise_db + 0.05 * energy_db
        loud = energy_db > self.noise_db + self.margin_db
        if loud:
            self.quiet = 0
            if not self.speaking:
                self.speaking = True
                return "start"
        elif self.speaking:
            self.quiet += 1
            if self.quiet >= self.hangover_frames:
                self.speaking = False
                self.quiet = 0
                return "end"
        return None

Three things I learned the hard way:

  • Only adapt the noise floor while nobody is speaking. My first version adapted always, and in a long sentence the floor crept up until the user's own voice counted as noise.
  • The hangover is a product decision, not a constant. 300 ms feels snappy for short commands. For a tutoring or interview agent, where people think out loud, I use 700 ms or more.
  • Energy is not enough on its own. A fan, a keyboard or a second speaker fools it. I moved to a small neural VAD (Silero VAD runs in a few milliseconds per frame on a CPU) and kept energy as a cheap first gate. The best agents go further and look at the words: "I want to book a table for" is not a finished turn no matter how long the pause is.

Streaming the LLM into TTS

Once tokens stream out of the LLM, you need to decide when you have enough text to start speaking. Too little and the TTS has no context for intonation. A sentence is the sweet spot. A clause is acceptable for the very first chunk if the sentence is long.

import re

SENTENCE_END = re.compile(r"([.!?…]+[\"')\]]?\s)|(\n)")
CLAUSE_END = re.compile(r"[,;:—]\s")


def speakable_chunks(token_stream, first_chunk_min=24, max_chunk=220):
    """Group streamed LLM tokens into chunks a TTS can say naturally.

    The first chunk may end at a clause, to start talking early. Later chunks end at sentences.
    """
    buf, first = "", True
    for token in token_stream:
        buf += token
        while True:
            match = SENTENCE_END.search(buf)
            if not match and first and len(buf) >= first_chunk_min:
                match = CLAUSE_END.search(buf, first_chunk_min)
            if not match and len(buf) >= max_chunk:
                cut = buf.rfind(" ", 0, max_chunk)
                match = re.compile(r"\s").search(buf, cut if cut > 0 else max_chunk)
            if not match:
                break
            chunk, buf = buf[: match.end()].strip(), buf[match.end():]
            if chunk:
                first = False
                yield chunk
    if buf.strip():
        yield buf.strip()

The max_chunk guard matters more than it looks. LLMs love long sentences with no full stop, and without a cap the agent goes silent for two seconds while a 60-word sentence finishes generating.

Calling ElevenLabs, and measuring it honestly

Here is the streaming TTS call, timed the way the user experiences it: to the first byte of audio, not to the end of the file.

import os
import time

import requests

VOICE_ID = os.environ["ELEVEN_VOICE_ID"]


def eleven_stream(text: str, model: str = "eleven_flash_v2_5"):
    url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
    started = time.perf_counter()
    with requests.post(
        url,
        params={"output_format": "mp3_44100_128"},
        headers={"xi-api-key": os.environ["ELEVENLABS_API_KEY"]},
        json={"text": text, "model_id": model},
        stream=True,
        timeout=30,
    ) as response:
        response.raise_for_status()
        first = None
        for chunk in response.iter_content(chunk_size=4096):
            if chunk and first is None:
                first = time.perf_counter() - started
                print(f"first audio after {first * 1000:.0f} ms")
            yield chunk

From my desk, Flash usually got me the first audio chunk in roughly 250 to 400 ms, and most of that was the network round trip, not the model. That surprised me, and it shaped everything after: for a cloud voice, where your server sits matters as much as which model you pick. Put the agent server in the same region as the voice API, and keep one connection warm instead of opening a new one per sentence. ElevenLabs also offers a WebSocket input-streaming endpoint where you push text as the LLM generates it, which removes the per-request overhead entirely.

Barge-in: the feature that makes it feel alive

Interruption is what separated the ElevenLabs agent from everything I had built. When the user starts talking while the agent is talking, three things must happen within about 100 ms:

  1. Stop playback.
  2. Cancel the LLM generation and any TTS requests in flight.
  3. Remember what the agent actually managed to say, so the conversation history does not claim it said things the user never heard.

The third one is the subtle one. In the browser it looks like this:

class Speaker {
  constructor() {
    this.ctx = new AudioContext();
    this.queue = [];          // { source, text, startedAt, duration }
    this.controller = null;   // aborts LLM + TTS fetches
  }

  async play(chunkText, audioBuffer) {
    const source = this.ctx.createBufferSource();
    source.buffer = audioBuffer;
    source.connect(this.ctx.destination);
    const startAt = Math.max(this.ctx.currentTime, this.queueEnd ?? 0);
    source.start(startAt);
    this.queueEnd = startAt + audioBuffer.duration;
    this.queue.push({ source, text: chunkText, startedAt: startAt, duration: audioBuffer.duration });
  }

  bargeIn() {
    const now = this.ctx.currentTime;
    this.controller?.abort();
    let heard = "";
    for (const item of this.queue) {
      if (item.startedAt + item.duration <= now) {
        heard += item.text + " ";                        // fully played
      } else if (item.startedAt < now) {
        const share = (now - item.startedAt) / item.duration;
        const words = item.text.split(" ");
        heard += words.slice(0, Math.floor(words.length * share)).join(" ") + "…";
      }
      item.source.stop();
    }
    this.queue = [];
    this.queueEnd = 0;
    return heard.trim();      // write THIS to the assistant turn in history
  }
}

Estimating the heard words by time share is crude. It assumes even speaking speed. But it is far better than the default, where the history says the agent finished a paragraph the user cut off after four words, and the next answer refers to things the user never heard.

One more trap: echo. Without echo cancellation, the agent hears itself through the user's speakers and interrupts itself. Browsers do this for you if you ask: getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } }). On a laptop without headphones, test it. On some devices it is not good enough, and then you need to raise the VAD threshold while the agent is talking.

Going local

ElevenLabs set the bar, and I still use it when a project needs the best voice. But by the middle of 2025 I wanted to know how close I could get with no cloud at all, for privacy, for cost, and because I like knowing what every millisecond is doing. The stack I ended up with:

Stage Cloud version Local version I use
VAD provider's built-in energy gate + Silero VAD
STT streaming cloud STT Vosk small models (English and Russian)
LLM hosted model local model via Ollama or vLLM
TTS ElevenLabs Flash Kokoro-82M, Silero TTS as fallback
Lip sync provider blendshapes audio envelope, computed in the browser

The local voice is not as good. It is good enough for a lot more than I expected, and the whole loop runs on a laptop CPU. How the generation side works, with the algorithms and the experiments, is in my voice generation post.

The other road: speech to speech

At the end of the year I tried the opposite of the cascade. A friend needed a voice consultant for a residential complex in Krasnodar: a widget on the website that answers questions about flats, prices and mortgages, in Russian. Instead of building six stages, I gave the whole job to Gemini Live with a native audio model. Audio goes in, audio comes out, and there is no text in the middle for me to chunk.

The browser side is small. Capture the microphone at 16 kHz, convert float samples to 16-bit PCM, and stream it over the live session:

function floatTo16BitPCM(input: Float32Array): ArrayBuffer {
  const output = new Int16Array(input.length)
  for (let i = 0; i < input.length; i++) {
    const s = Math.max(-1, Math.min(1, input[i]))
    output[i] = s < 0 ? s * 0x8000 : s * 0x7fff
  }
  return output.buffer
}

processor.onaudioprocess = (e) => {
  const pcm = floatTo16BitPCM(e.inputBuffer.getChannelData(0))
  session.sendRealtimeInput({ media: { mimeType: 'audio/pcm;rate=16000', data: toBase64(pcm) } })
}

The reply arrives as small chunks of 24 kHz PCM. The trick to playing them without clicks or gaps is to schedule each chunk to start exactly where the previous one ends, on the audio clock rather than when the network message arrives:

let nextStart = 0

function playChunk(ctx: AudioContext, samples: Float32Array) {
  const buffer = ctx.createBuffer(1, samples.length, 24000)
  buffer.getChannelData(0).set(samples)
  const source = ctx.createBufferSource()
  source.buffer = buffer
  source.connect(ctx.destination)
  nextStart = Math.max(nextStart, ctx.currentTime)   // if we fell behind, start now
  source.start(nextStart)
  nextStart += buffer.duration
  playing.push(source)
}

function onServerMessage(msg) {
  if (msg.serverContent?.interrupted) {               // the user talked over the model
    playing.forEach((s) => s.stop())
    playing = []
    nextStart = 0
  }
}

The knowledge base, with prices, deadlines, infrastructure and a phone number for anything it does not know, lives entirely in the system instruction, with one rule I repeat in every voice prompt now: answer briefly, because this is a voice conversation. A model that writes beautifully formatted paragraphs is unbearable to listen to.

My honest comparison after building both:

  • Speech to speech gets endpointing, barge-in and natural prosody for free, and the latency is excellent. The model hears tone, not just words.
  • The cascade gives me control. I can log the transcript, check facts before they are spoken, swap the voice, and run it offline. For anything that quotes prices or legal terms, I want the text in the middle where I can see it.

The first version of the widget did not handle the interrupted flag at all, so the model stopped generating but the already-queued audio kept playing for a second. Exactly the barge-in bug from earlier in this post, in a different architecture. Some lessons you learn twice.

What I would tell myself in January

  • Latency is a sum. Shaving 50 ms off the model does nothing if endpointing waits 800 ms. Measure every stage, from the user's last word to the first sound.
  • Stream everything. Partial transcripts, streamed tokens, sentence-level TTS, chunked playback.
  • Endpointing is product design. The right hangover depends on what people do with the agent.
  • Barge-in needs history repair. Record what was heard, not what was generated.
  • Put the server next to the voice API. For cloud TTS, network is often the biggest single term.

My voice repos on GitHub

Everything in this post grew into code that is public on my GitHub:

  • omnitwin: the main one. A walkable 3D DevOps lab with Mark, a talking engineer avatar you can interrupt. It has two voice paths: a Convai character with ARKit blendshape lip sync, and a fully local path with Kokoro and Silero for speech, Vosk for recognition, and the envelope lip sync from the second post. The voice backend is backend/app/voice.py and the lip sync is web/src/lipsync.ts.
  • voice-agent-silero: a Russian-speaking voice consultant for a residential complex, as a website widget. Speech to speech over Gemini Live native audio: 16 kHz PCM from the microphone, 24 kHz PCM back, gapless playback scheduling, and the whole knowledge base in the system instruction.
  • ai-avatar-3d: the 3D avatar experiments that came before Mark, with body movement tracking.
  • ai-insight-hub: avatar rendering driven by motion, posture and visual recognition. The face and body side of the same obsession.
  • chat-bot-ollama: the fully offline chat agent with Ollama and RAG that I use as a local brain when I do not want any cloud in the loop.