LearnSystem design

Real-time phone voice agent

Design a voice agent that answers restaurant and hotel phone lines: it books, changes and cancels reservations by calling the business’s booking system, handles interruptions, and transfers to staff when stuck.

Applied LLM8 parts

Contents

What to cover

Sketch your own design first. A complete answer has these parts; the notes say what each should settle.

  1. Requirementscall volume and peak concurrency; languages and accents; latency target (turn gap); booking-system APIs and their latency; escalation rules; recording/consent requirements
  2. Estimates
  3. API
  4. Data model
  5. ArchitectureSIP/telephony ingress (regional); streaming ASR + VAD/turn detection (or audio-native model); dialogue manager/state machine + LLM with tools; booking integration with timeouts and caching; streaming TTS with phrase chunking and response cache; barge-in handling (cancel TTS + generation); transfer to staff; per-stage tracing; eval sets from real calls; containment/resolution/caller-experience metrics
  6. Deep divesbooking API takes 3 s — what does the caller hear?; How do you measure and reduce p95 turn gap?; How do you test changes without risking live calls?
  7. Trade-offscascaded ASR→LLM→TTS vs speech-native models (control, logging, guardrails vs latency); endpointing aggressiveness; reasoning per turn vs latency; generic vs per-customer tuning
  8. Evaluationexplicit latency budget per stage with distributions; streaming and cancellation; graceful degradation; eval from real call recordings; telephony realities (codecs, regions, echo)

Reference design

One way to answer it, part by part. Open a part once you have your own version of it.

Requirements

Functional: answer inbound calls for restaurants and hotels; check availability, book, change and cancel reservations; answer venue FAQs (hours, parking, dietary options); handle interruptions; transfer to staff with a summary; send an SMS confirmation.

Assumptions to confirm

  • Volume: 5,000 venues × ~60 calls/day = 300k calls/day, average 2.5 minutes; Friday 17:00–19:00 peak.
  • Languages and accents: UK English first with strong regional and non-native accent coverage; French, Spanish and German per venue later; narrowband 8 kHz phone audio.
  • Latency target: caller-perceived turn gap (end of speech → first agent audio) p50 < 800 ms, p95 < 1.3 s.
  • Booking systems: restaurant reservation platforms (e.g. ResDiary, OpenTable, SevenRooms) and hotel property-management systems (e.g. Opera, Mews), each integrated through whatever partner API it offers. Assume latency of 300 ms–3 s, rate limits and occasional outages.
  • Escalation rules: caller asks for a person; two failed understanding attempts; parties above the venue’s limit; complaints; allergies needing a guarantee; anything payment-related (no card details over the agent — send a payment link instead, keeping us out of PCI scope).
  • Recording and consent: announce recording at call start; UK GDPR lawful basis and retention (e.g. 30 days audio, 90 days transcripts) set per venue; redact PII in stored transcripts; opt-out path to staff.
  • Non-goals: outbound calling; taking payments.

Estimates

Stack · 5 layersTurn-gap latency budget

  1. End of speech detection before the turn starts.

  2. Final ASR result after partials.

  3. First clause generated before the rest.

  4. First audio byte from streaming TTS.

  5. Media path and jitter buffer to the caller.

The caller-perceived turn gap is split across five stages, totalling about 830 ms against a p50 target of under 800 ms and p95 under 1.3 s.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
  • Concurrency (Little’s law): peak hour ≈ 12% of 300k = 36k calls/h = 10 calls/s × 150 s ≈ 1,500 concurrent calls; provision for 2,500.
  • Turns: ~12 caller turns per call → 3.6M LLM turns/day; at peak 1,500 calls ÷ ~12.5 s per turn ≈ 120 turns/s.
  • ASR: 1,500 streams at ~200 streams/GPU ≈ 8 GPUs.
  • TTS: agent speaks ~40% of the time → ~600 concurrent synthesis streams at ~100/GPU ≈ 6 GPUs.
  • LLM: ~3k-token context (2.5k cached venue/system prefix), ~60 output tokens. Peak prefill 120 × 500 uncached ≈ 60k tokens/s, decode 120 × 60 ≈ 7k tokens/s → a mid-size model on ~4–8 GPUs.
  • Fleet: ~20–25 GPUs at peak, doubled across two London zones ≈ 40–50 GPUs. At ~$2.5/GPU-hour: 45 × 24 × 2.5 ≈ $2.7k/day ÷ 750k call-minutes ≈ $0.004/min, plus an assumed ~$0.004/min for the SIP trunk (check the carrier’s rate) → ~$0.008/min, under 1p per minute before margin.
  • Turn-gap budget: semantic endpointing 250 ms + ASR final 80 ms + LLM first clause 250 ms + TTS first audio 150 ms + telephony and jitter buffer 100 ms ≈ 830 ms.
  • Storage: 750k min/day of 8 kHz audio at ~8 KB/s ≈ 360 GB/day; 30-day retention ≈ 11 TB.

API

Telephony ingress: SIP trunk (or Twilio/Vonage media streams) → WS /calls/{id}/media
                   8 kHz μ-law frames in and out; DTMF events; REFER for transfer

Tools the dialogue manager exposes to the LLM (venue bound from the dialled number):
  check_availability(date, time_window, party_size)      → [{slot_id, time}]
  create_booking(slot_id, name, phone, party_size, notes, idempotency_key) → {booking_ref}
  find_booking(phone | name + date)                      → [{booking_ref, ...}]
  modify_booking(booking_ref, changes, idempotency_key)
  cancel_booking(booking_ref, idempotency_key)
  get_venue_info(topic)                                  → approved FAQ text
  transfer_to_staff(reason, summary)
  send_sms(template_id, params)

Venue admin API:
  GET/PUT /venues/{id}/config   hours, policies, max party, transfer number, voice, languages
  GET     /venues/{id}/calls    outcomes, recordings (role-restricted)

Data model

  • Venue: id, type, booking integration and credentials reference, policies (max party, deposit rules, cancellation window), FAQ entries, transfer rules and hours, voice, languages, custom vocabulary (venue and dish names).
  • Call: id, venue_id, caller number (hashed for analytics), started/ended, consent announced, outcome (booked | changed | cancelled | info | transferred | abandoned), transfer reason, recording URI, retention date.
  • Turn: call_id, index, ASR text and confidence, endpoint timestamps, dialogue state, LLM input hash, tool calls with latencies, spoken text, barge-in flag, per-stage timings.
  • DialogueState: current step (greet, collect, confirm, execute, close) and slots (date, time, party size, name, phone, booking_ref) with confirmation status.
  • AvailabilityCache: venue_id, date → slots, fetched_at, TTL 60 s.
  • EvalCase: caller audio or simulated persona, venue fixture, expected booking end state.

Postgres for venues, calls and bookings audit; Redis for dialogue state and availability cache; object storage for recordings; ClickHouse for per-stage traces.

Architecture

Flow · 4 stepsRequest path for an inbound voice call

Request path for an inbound voice callThe diagram shows one call moving left to right: the caller's audio enters over the SIP trunk and media gateway, VAD and streaming ASR produce partials and finals, and the dialogue manager's state machine plus LLM interpret the turn. The manager calls the booking adapter, which reaches the venue's booking system and returns the result; streaming TTS then speaks the reply back to the caller.Inbound callerPSTNSIP trunkLondon regionMedia gatewayRTP, jitter buffer, echo cancellation,G.711VAD + streaming ASRsemantic turn detection,partials/finalsDialogue manager + LLMstate machine + toolsBooking adaptertimeouts, retries,idempotency, circuitbreakerStreaming TTSfirst clause early,phrase chunkingCalleraudio backBooking systemsResDiary / OpenTable /PMS1234TelephonyUnderstandDialogueAct
  1. Call enters The caller's audio enters over the SIP trunk and media gateway; VAD and streaming ASR produce partials and finals.
  2. Understand and decide The dialogue manager's state machine and LLM interpret the turn and choose the next action.
  3. Book The booking adapter calls the venue's booking system with timeouts, retries and idempotency; the result returns to the dialogue manager.
  4. Speak Streaming TTS speaks the first clause early and sends audio back to the caller.

An inbound call flows from the PSTN through telephony, ASR and the dialogue manager to the booking system, then back through streaming TTS to the caller.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Call entersThe caller's audio enters over the SIP trunk and media gateway; VAD and streaming ASR produce partials and finals.
2Understand and decideThe dialogue manager's state machine and LLM interpret the turn and choose the next action.
3BookThe booking adapter calls the venue's booking system with timeouts, retries and idempotency; the result returns to the dialogue manager.
4SpeakStreaming TTS speaks the first clause early and sends audio back to the caller.

Source: This page's text

Boxes
BoxGroupDetail
Inbound callerTelephonyPSTN
SIP trunkTelephonyLondon region
Media gatewayTelephonyRTP, jitter buffer, echo cancellation, G.711
VAD + streaming ASRUnderstandsemantic turn detection, partials/finals
Dialogue manager + LLMDialoguestate machine + tools
Booking adapterActtimeouts, retries, idempotency, circuit breaker
Booking systemsActResDiary / OpenTable / PMS
Streaming TTSActfirst clause early, phrase chunking
CallerTelephonyaudio back

Source: This page's text

PSTN ─► SIP trunk (London region) ─► Media gateway: RTP, jitter buffer,
        echo cancellation, codec handling (G.711), DTMF
   ├─► VAD + semantic turn detector ─► streaming ASR (partials/finals,
   │                                    venue vocabulary boosting)
   ▼
Dialogue manager (state machine: greet → collect → confirm → execute → close)
   + LLM with tools for language understanding and phrasing
   ├─► Booking adapter: timeouts, retries, idempotency, circuit breaker,
   │   availability prefetch at call start ─► ResDiary / OpenTable / PMS
   ▼
Streaming TTS (first clause early, phrase chunking, cached common phrases)
   ─► media gateway ─► caller
Barge-in: caller speech during playback → stop audio within ~100 ms,
          cancel in-flight LLM and TTS, keep heard-text in context
Transfer: warm transfer (REFER or bridge) with a whispered summary to staff
Tracing: OpenTelemetry spans per stage per turn; recordings + transcripts → eval store

The state machine owns the flow and confirmation of every slot; the LLM interprets and phrases, so dates, party sizes and names are always read back before a booking is created.

Deep dives

Sequence · 5 stepsWhat the caller hears during a 3 s booking API

What the caller hears during a 3 s booking APIA caller reaches the dialogue manager, which starts the availability check as soon as date, time and party size are known. The caller hears a cached filler within about 300 ms, a second filler at 1.5 s, and the availability result when the booking API answers at 3 s. The 5 s hard timeout is shown only as the fallback when no answer has arrived.CallerDialogue managerTTSBooking API1date, time, party sizecheck_availability(...)2fillerLet me check that for you3fillersecond filler4slots at 3 savailability resultavailability result5hard timeoutSMS confirmation or transfer
What the caller hears during a 3 s booking APIA caller reaches the dialogue manager, which starts the availability check as soon as date, time and party size are known. The caller hears a cached filler within about 300 ms, a second filler at 1.5 s, and the availability result when the booking API answers at 3 s. The 5 s hard timeout is shown only as the fallback when no answer has arrived.CallerDialoguemanagerTTSBooking API1date, time, party sizecheck_availability(...)2fillerLet me check that for you3fillersecond filler4slots at 3 savailability resultavailability result5hard timeoutSMS confirmation or transfer
  1. Start availability check Availability starts as soon as date, time and party size are known, while the agent is still confirming.
  2. First filler Within about 300 ms, a cached filler is played.
  3. Second filler At 1.5 s, a second, different filler is played.
  4. Availability result At 3 s the booking API answers and the agent speaks the availability result; it never says booked until create_booking confirms.
  5. Hard timeout fallback Only if no answer has arrived by 5 s: offer to text confirmation once it completes, or transfer. Not reached in the 3 s case.

During a 3 s booking API, the caller hears two cached fillers and then the availability result, with the 5 s hard timeout reserved as the no-answer fallback.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Messages
StepFromToMessage
1CallerDialogue managerdate, time, party size
1Dialogue managerBooking APIcheck_availability(...)
2Dialogue managerTTSfiller
2TTSCallerLet me check that for you
3Dialogue managerTTSfiller
3TTSCallersecond filler
4Booking APIDialogue managerslots at 3 s (reply)
4Dialogue managerTTSavailability result
4TTSCalleravailability result
5Dialogue managerTTShard timeout
5TTSCallerSMS confirmation or transfer

Source: This page's text

Flow · 4 stepsTesting changes without live calls

Testing changes without live callsA left-to-right flow from offline testing to live rollout. Simulated callers and replayed recorded audio pass through the real 8 kHz codec with noise and packet loss against sandbox booking systems, then shadow mode listens on live calls without speaking, and finally a canary of opted-in venues runs behind feature flags.Simulated callersLLM personas withgoalsRecorded calleraudiorecorded calleraudioCodec replayreal 8 kHz codec,noise, packet lossSandbox bookingsystemssandbox bookingsystemsShadow modelistens andproposes, neverspeaksCanaryopted-in venues,feature flags1234OfflineLive rollout
Testing changes without live callsA left-to-right flow from offline testing to live rollout. Simulated callers and replayed recorded audio pass through the real 8 kHz codec with noise and packet loss against sandbox booking systems, then shadow mode listens on live calls without speaking, and finally a canary of opted-in venues runs behind feature flags.Simulated callersLLM personas with goalsRecorded caller audiorecorded caller audioCodec replayreal 8 kHz codec, noise, packet lossSandbox bookingsystemssandbox booking systemsShadow modelistens and proposes,never speaksCanaryopted-in venues, feature flags1234OfflineLive rollout
  1. Simulated callers LLM personas with goals, voiced by varied TTS accents, are pushed through the real 8 kHz codec with noise and packet loss against sandbox booking systems.
  2. Replay regressions Recorded caller audio is replayed for ASR and endpointing regressions.
  3. Shadow mode Shadow mode runs on live calls: the new stack listens and proposes, never speaks.
  4. Canary A canary of opted-in venues runs behind feature flags.

Changes are tested offline first, then in shadow mode, then on opted-in venues, so live callers are never exposed to untested changes.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Simulated callersLLM personas with goals, voiced by varied TTS accents, are pushed through the real 8 kHz codec with noise and packet loss against sandbox booking systems.
2Replay regressionsRecorded caller audio is replayed for ASR and endpointing regressions.
3Shadow modeShadow mode runs on live calls: the new stack listens and proposes, never speaks.
4CanaryA canary of opted-in venues runs behind feature flags.

Source: This page's text

Boxes
BoxGroupDetail
Simulated callersOfflineLLM personas with goals
Codec replayOfflinereal 8 kHz codec, noise, packet loss
Sandbox booking systemsOfflinesandbox booking systems
Recorded caller audioOfflinerecorded caller audio
Shadow modeLive rolloutlistens and proposes, never speaks
CanaryLive rolloutopted-in venues, feature flags

Source: This page's text

The booking API takes 3 s — what does the caller hear? Start the availability call as soon as date, time and party size are known, while the agent is still confirming. Within ~300 ms play a cached filler (“Let me check that for you”); at 1.5 s a second, different filler. Prefetch today’s and tomorrow’s availability at call start and serve from a 60 s cache. Hard timeout at 5 s: offer to text confirmation once it completes, or transfer. Idempotency keys stop retries double-booking, and the agent never says “booked” until the API confirms.

Measuring and reducing p95 turn gap. Timestamp end of speech, ASR final, LLM first token, first TTS byte and first RTP packet for every turn; chart distributions per stage, venue and time of day. Levers: a semantic endpointer that ends sooner when the utterance is complete; starting the LLM on stable partials; prefix caching of the venue prompt; a small model for routine turns; speaking the first clause before the rest is generated; colocating all stages in one region; keeping tool calls off the critical path through prefetch.

Testing without risking live calls. Simulated callers: LLM personas with goals, voiced by varied TTS accents, pushed through the real 8 kHz codec with noise and packet loss, against sandbox booking systems. Replay recorded caller audio for ASR and endpointing regressions. Then shadow mode on live calls (new stack listens and proposes, never speaks), then a canary of opted-in venues behind feature flags.

Trade-offs

  • Cascaded ASR → LLM → TTS vs speech-native models: cascaded gives text logs, deterministic tool calls, guardrails on text, per-stage upgrades and debugging; speech-native removes stage hand-offs, which can save a few hundred milliseconds, and can sound more natural, but is harder to constrain, audit and evaluate. For bookings, where names, numbers and dates must be exact, start cascaded and A/B a speech-native front end later.
  • Endpointing aggressiveness: aggressive cuts people off while they read out phone numbers; conservative feels slow. Make it state-dependent: longer silence thresholds when collecting digits or names.
  • Reasoning per turn vs latency: the state machine handles flow so most turns need no deliberation; allow a larger model only on rare complex turns, covered by a filler.
  • Generic vs per-customer tuning: one model per vertical (restaurant, hotel) plus per-venue configuration, FAQs and vocabulary; no per-venue fine-tunes, which would not scale to 5,000 venues.

Evaluation

  • Latency: turn gap p50/p95/p99 per stage with distributions, not averages; alert when p95 > 1.3 s.
  • Outcome metrics: containment (handled without transfer), resolution (booking exists and matches the transcript — checked against the booking system), booking slot error rate (date, time, party size, name) < 0.5%, appropriate transfer rate.
  • Caller experience: hang-ups during agent speech, repeated requests, barge-in frequency, post-call SMS rating, venue complaints.
  • Eval from real calls: consented recordings labelled into scenario sets per venue type and accent; WER on names and numbers; regression suite run on every model, prompt or endpointer change.
  • Graceful degradation: ASR or TTS provider failover; smaller LLM fallback; booking system down → take details and send a confirmation once it recovers, or transfer; total outage → calls forward straight to the venue line.
  • Telephony realities: narrowband G.711 audio, echo from our own TTS triggering false barge-ins (needs echo cancellation), packet loss, regional media servers, DTMF fallback for digits.

What a strong design shows

  • Gives an explicit turn-gap budget per stage and measures distributions, not averages.
  • Streams everywhere and implements real barge-in: stop playback and cancel in-flight generation and synthesis.
  • Keeps the booking system off the critical path (prefetch, fillers, timeouts, idempotency) and never claims success before confirmation.
  • Tests with simulated callers through real codecs, shadow mode and per-venue canaries rather than on live callers.
  • Knows telephony realities: 8 kHz audio, echo, regions, consent announcements and PCI avoidance.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.