LearnSystem design

Low-latency streaming TTS and dubbing API

Design a public text-to-speech API with a streaming mode for conversational agents (first audio in well under a second) and a batch mode for dubbing long videos into 20 languages.

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. Requirementslatency target and percentiles; voices (stock vs cloned); languages; peak concurrency; pricing tiers; quality tiers; consent/safety requirements
  2. Estimates
  3. API
  4. Data model
  5. ArchitectureAPI gateway with auth, quotas and token/character-based rate limits; text normalisation; model routing (fast vs high-quality tiers); GPU inference pool with continuous batching, regional placement and warm pools; chunked audio streaming over WebSocket/SSE; caching of repeated phrases; batch pipeline (job queue, segmenting, translation, alignment, parallel synthesis, retries, idempotent re-runs, progress); voice-consent and moderation services; metering/billing; quality monitoring (ASR-based intelligibility, MOS sampling)
  6. Deep divesp99 TTFA doubles at peak — what do you do?; How do you resume a 2-hour dubbing job that failed at 80%?; How do you prevent misuse of cloned voices?
  7. Trade-offschunk size vs prosody; batching vs TTFA; fast vs quality model tiers; GPU utilisation vs warm capacity for spikes
  8. Evaluationseparates interactive and batch paths; latency measured end-to-end with tails; idempotent, resumable batch jobs; safety as a first-class component; cost per character/minute estimated

Reference design

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

Requirements

Two products, one platform

  • Streaming: text in (possibly token-by-token from an LLM), audio out; time to first audio (TTFA) p50 < 250 ms and p95 < 500 ms server-side for the fast tier, measured in each region; real-time factor comfortably above 1 under load.
  • Batch dubbing: upload a video, get it dubbed into up to 20 languages, preserving each speaker’s voice and timing; hours, not seconds; resumable; progress and webhooks.

Assumptions to confirm

  • Voices: a stock library of a few hundred voices; instant clones from ~1 minute of audio; professional clones fine-tuned from ~30 minutes.
  • Languages: ~30 for synthesis, 20 dubbing targets.
  • Peak concurrency: ~20k simultaneous streaming sessions (conversational agents), steady batch backlog.
  • Pricing tiers: free, starter, pro, enterprise — per-character billing with concurrency caps per tier; enterprise gets reserved capacity and an SLA.
  • Quality tiers: “flash” (lowest latency, smaller model) and “studio” (best prosody, higher latency, used for dubbing).
  • Consent and safety: cloning only with verified consent of the voice owner; blocked voices (public figures); text moderation for fraud and impersonation; output watermarking; AI-disclosure support.
  • Non-goals: on-device synthesis; real-time speech-to-speech translation.

Estimates

CalculatorFast-tier TTFA budget

Non-network budget = Gateway and auth + Moderation + Normalisation + Queue wait + First chunk inference + Encoding

Total at network low = Non-network budget + Network low

Total at network high = Non-network budget + 80

Headroom to 250 ms = 250 − Total at network high

Worked cases
CaseGateway and auth (ms)Moderation (ms)Normalisation (ms)Queue wait (ms)First chunk inference (ms)Encoding (ms)Network low (ms)Non-network budgetTotal at network lowTotal at network highHeadroom to 250 ms
Default1020520100530160 ms190 ms240 ms10 ms
The fast-tier budget sums the listed components and adds network 30–80 ms, so the reader can see where the ~200–250 ms target comes from.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
  • Streaming load: 20k sessions × ~40% of time speaking ≈ 8k concurrent synthesis streams. Assume a small fast model batched on an H100 serves ~150 real-time streams (measure it in a load test) → 8k / 150 ≈ 54 GPUs, +30% headroom ≈ 70, spread over three regions ≈ ~90 GPUs.
  • Characters: speech ≈ 15 characters/s. Peak 8k × 15 = 120k chars/s; average ~40% of peak ≈ 48k chars/s ≈ 4.1B chars/day.
  • Streaming cost: 90 GPUs × 24 h × ~$2.5 ≈ $5.4k/day ÷ 4.1B chars ≈ $1.3 per million characters — leaves room for list prices one or two orders of magnitude higher, which fund headroom, R&D and free tiers.
  • Dubbing: assume 2,000 source hours/day × 3 target languages = 6,000 output hours. Studio model at ~5× real time per GPU → 1,200 GPU-hours/day ≈ 50 GPUs continuously, ≈ $3k/day ÷ 360k output minutes ≈ $0.008/min for synthesis; with separation, ASR, translation and mixing, ~$0.03/min.
  • TTFA budget (fast tier): gateway and auth 10 ms, moderation 20 ms (in parallel), normalisation 5 ms, queue wait ≤ 20 ms, first chunk inference 100 ms, encoding 5 ms, network 30–80 ms → ~200–250 ms.
  • Bandwidth: 8k streams × 64 kbps (PCM 16 kHz would be 256 kbps) ≈ 0.5 Gbps egress at peak with compressed formats.

API

POST /v1/tts                      → chunked audio (one-shot, short text)
  {voice_id, model: "flash"|"studio", text, language?, output_format: "pcm_16000"|"mp3_44100"|"ulaw_8000",
   voice_settings: {stability, style}, seed}

WS /v1/tts/stream?voice_id=&model=&output_format=
  client → {"text": "Hello, how", "flush": false} ... {"text": "", "flush": true}
  server → {"audio": "<base64>", "alignment": {"chars": [...], "start_ms": [...]}, "final": false}

POST /v1/dubbing   {source_url | upload_id, source_lang?, target_langs: [...], voice_mode: "clone"|"stock",
                    webhook_url, idempotency_key}            → {job_id}
GET  /v1/dubbing/{job_id}       → {status, progress per language, segment counts, output URLs}
POST /v1/voices                 {samples[], consent_recording, name}  → {voice_id, status: "pending_verification"}
GET  /v1/usage?from&to

Errors carry retry_after for 429s; streaming sessions return a concurrency error before any audio if the tier cap is reached.

Data model

  • Organisation / ApiKey: tier, character quota, concurrency cap, region pin, enterprise reservations.
  • Voice: voice_id, owner, type (stock | instant | professional), speaker embedding or adapter reference, consent_record_id, languages, status (active | blocked | pending), similarity-to-protected-set score.
  • ConsentRecord: consent audio, random phrase read, verification score against samples, timestamp, IP, account.
  • UsageEvent: org, request_id, model, voice, characters, audio seconds, region, TTFA, cache hit → Kafka → billing aggregates.
  • DubbingJob: job_id, org, source media, target languages, status, DAG state, idempotency key.
  • Segment: job_id, index, start/end, speaker, source text, translation per language, artefact URIs per step, content hash (text + voice + model version + settings), attempt count, status.
  • PhraseCache: hash(voice, model version, normalised text, settings) → audio object.
  • WatermarkRecord: output id → org, voice, timestamp (for provenance lookups).

Architecture

Flow · 4 stepsStreaming request path

Streaming request pathThe diagram shows the interactive streaming path: a client sends text over HTTPS/WS to the regional edge and API gateway, where auth, quotas and token buckets apply. Moderation and voice-consent checks run before normalisation; repeated text can short-circuit through the phrase cache, while misses route to the flash GPU pool for continuous batching. The chunker and encoder add watermark and stream audio back to the client.Clienttoken-by-token textRegional edgeTLS, LBAPI gatewayauth, quotas, token bucketsModeration + consentfast text classifierText normalisationnumbers, dates, currenciesPhrase cacheRedis + object storeRoutertier, language, regionGPU poolflash, continuous batchingChunker + encoderPCM/μ-law/MP3/Opus + watermarkHTTPS/WShitmissaudio1234ClientGatewayInferenceOutput
  1. Request enters Client text reaches the regional edge and gateway for auth and quotas.
  2. Safety and normalise Moderation and voice-consent checks run, then text is normalised and checked against the phrase cache.
  3. Route and infer Router sends the request to the flash GPU pool for continuous batching.
  4. Stream audio Chunker and encoder add watermark and stream audio back; cache hits skip inference.

A streaming request moves from client to regional edge, gateway, safety and normalisation, router and flash GPU pool, then back as watermarked audio.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
1Request entersClient text reaches the regional edge and gateway for auth and quotas.
2Safety and normaliseModeration and voice-consent checks run, then text is normalised and checked against the phrase cache.
3Route and inferRouter sends the request to the flash GPU pool for continuous batching.
4Stream audioChunker and encoder add watermark and stream audio back; cache hits skip inference.

Source: This page's text

Boxes
BoxGroupDetail
ClientClienttoken-by-token text
Regional edgeGatewayTLS, LB
API gatewayGatewayauth, quotas, token buckets
Moderation + consentGatewayfast text classifier
Text normalisationGatewaynumbers, dates, currencies
Phrase cacheInferenceRedis + object store
RouterInferencetier, language, region
GPU poolInferenceflash, continuous batching
Chunker + encoderOutputPCM/μ-law/MP3/Opus + watermark

Source: This page's text

Flow · 4 stepsHow a dubbing job moves through the pipeline

How a dubbing job moves through the pipelineThe figure shows the batch dubbing path left to right: source media enters object storage, the Temporal orchestrator runs the DAG, and segments pass through separation, ASR, diarisation, segmentation, translation, per-speaker cloning, parallel studio synthesis, time alignment, background mixing and QA before outputs and webhooks are sent.Source videoupload or source_urlObject storecontent-hashed artefactsOrchestratorTemporal DAG, persisted stateAnalysisseparation, ASR, diarisation,segmentationTranslation LLMduration constraintsParallel synthesisper-speaker clone, studio poolAlignment and mixtime alignment, mix withbackgroundQAOutputs + webhookprogress and output URLs1234InputOrchestrationSynthesisOutput
  1. Ingest and separate Source media lands in object storage; the Temporal DAG starts and vocals and background are separated.
  2. Analyse and translate ASR and diarisation segment the audio; the translation LLM applies duration constraints.
  3. Synthesise and align Per-speaker clones feed parallel segment synthesis in the studio pool, then time alignment and background mixing.
  4. Check and deliver QA runs, then outputs and webhooks are sent with progress.

A dubbing job moves from source media through a Temporal DAG of separation, analysis, translation, synthesis, alignment, mixing and QA to outputs and webhooks.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
1Ingest and separateSource media lands in object storage; the Temporal DAG starts and vocals and background are separated.
2Analyse and translateASR and diarisation segment the audio; the translation LLM applies duration constraints.
3Synthesise and alignPer-speaker clones feed parallel segment synthesis in the studio pool, then time alignment and background mixing.
4Check and deliverQA runs, then outputs and webhooks are sent with progress.

Source: This page's text

Boxes
BoxGroupDetail
Source videoInputupload or source_url
Object storeInputcontent-hashed artefacts
OrchestratorOrchestrationTemporal DAG, persisted state
AnalysisOrchestrationseparation, ASR, diarisation, segmentation
Translation LLMOrchestrationduration constraints
Parallel synthesisSynthesisper-speaker clone, studio pool
Alignment and mixSynthesistime alignment, mix with background
QAOutput
Outputs + webhookOutputprogress and output URLs

Source: This page's text

Client ─HTTPS/WS─► Regional edge (TLS, LB) ─► API gateway: auth, quotas,
   character-based token buckets, concurrency caps per tier, priority class
   ─► Moderation service (fast text classifier) + voice-consent service
      (is this voice verified, not blocked, and usable by this account?)
   ─► Text normalisation (numbers, dates, currencies, abbreviations; per language)
   ─► Router: tier, language, region, voice type
   ─► GPU pools  [flash]  [studio]   continuous batching per decoding step,
        warm replicas per region, speaker embeddings cached on GPU
   ─► Chunker + encoder (PCM/μ-law/MP3/Opus) + watermark ─► stream to client
   Phrase cache (Redis + object store) short-circuits repeated text

Batch dubbing: object store ─► Orchestrator (Temporal) DAG:
   vocal/background separation ─► ASR + diarisation ─► segmentation
   ─► translation LLM with duration constraints ─► per-speaker clone
   ─► parallel segment synthesis (studio pool, preemptible) ─► time alignment
   ─► mix with background ─► QA ─► outputs + webhook
Metering ─► Kafka ─► billing · Quality monitor: ASR back-transcription, MOS predictor

Batch synthesis runs as low-priority work on the same GPU fleet, soaking up the headroom kept for streaming peaks.

Deep dives

p99 TTFA doubles at peak. First decompose: gateway → queue wait → first-chunk compute → encoding → network. Usually it is queueing: the scheduler admits too many streams per replica or batch work shares the pool. Fixes: cap batch size and max queue wait (~20 ms) on the flash pool; isolate batch work or make it preemptible; autoscale on concurrent streams and queue depth rather than CPU or GPU utilisation; keep warm replicas and spill to the next region; shed free-tier traffic first via priority classes; shrink the first audio chunk. Verify with synthetic probes per region.

Resuming a 2-hour dubbing job that failed at 80%. The job is a DAG of idempotent steps whose outputs are stored by content hash in object storage; the orchestrator persists step state. On restart, completed segments are cache hits and only the remaining 20% (plus the final mix) run again. Deterministic seeds keep re-synthesised segments consistent; a segment failing three times is flagged for review instead of blocking the job; the API reports partial progress throughout.

Preventing misuse of cloned voices. Cloning requires the speaker to read a random phrase live, and speaker verification must match that recording to the training samples. New clones are compared against a protected set of public-figure voices. Text is moderated for fraud and impersonation patterns; professional clones need identity checks; every output is watermarked and logged with voice and account, a public detection endpoint and takedown process exist, and abusive accounts are rate-limited and banned.

Trade-offs

  • Chunk size vs prosody: small first chunks cut TTFA but sound choppy; condition each chunk on the previous text and audio, keep the first chunk short and later chunks sentence-sized.
  • Batching vs TTFA: larger batches raise throughput per GPU but add queue delay; bound the wait per request and size batches per tier.
  • Fast vs quality tiers: a smaller model for conversational agents, the larger one for dubbing and narration; route by tier and let customers choose explicitly.
  • GPU utilisation vs warm capacity: keeping ~30% headroom for streaming spikes is expensive unless batch dubbing fills it as preemptible work; cold-starting a replica (weights, compilation) takes tens of seconds to minutes, too slow for spikes.
  • Phrase caching vs personalisation: caching greetings and fillers is cheap TTFA gain, but must key on voice, model version and settings to avoid stale audio.

Evaluation

  • Separate interactive and batch SLOs: streaming TTFA p50/p95/p99 from client-side probes per region; dubbing turnaround per audio hour and completion rate.
  • End-to-end latency with tails: dashboards by tier, region, voice type and text length; error and timeout rates; real-time factor under load.
  • Quality: intelligibility via ASR back-transcription (character error rate) on sampled outputs; speaker similarity for clones; MOS/CMOS listening panels for every model release, per language; dubbing timing fit and translation quality (automatic metric plus native reviewers).
  • Batch robustness: resume tests that kill jobs mid-run; idempotency verified (re-runs produce identical outputs and no double billing).
  • Safety: consent verification false-accept rate, protected-voice match rate, abuse reports and time to takedown, watermark detection rate after compression.
  • Cost: GPU cost per million characters and per dubbed minute tracked against price per tier; cache hit rate.

What a strong design shows

  • Separates the streaming and batch paths, with their own SLOs, schedulers and failure handling, but shares the GPU fleet sensibly.
  • Measures TTFA end-to-end with tails and can decompose a latency regression into queueing vs compute.
  • Designs dubbing as idempotent, content-addressed, resumable steps.
  • Treats consent, cloning abuse and watermarking as first-class components, not an afterthought.
  • Puts numbers on GPU count and cost per character and per minute.

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.