---
title: Real-time speech-recognition API
url: https://gurkanozkan.ai/learn/design/mle-real-time-speech-recognition-api-09/
markdown: https://gurkanozkan.ai/learn/design/mle-real-time-speech-recognition-api-09.md
kind: design
role: ML engineering
json: https://gurkanozkan.ai/api/learn/design/mle-real-time-speech-recognition-api-09.json
---

# Real-time speech-recognition API

Design a multi-language streaming transcription service with partial and final transcripts and a configurable latency/accuracy trade-off.

## Constraints

- 50k concurrent streams
- partial results every ~300 ms
- finals within ~1 s
- 50 languages

## What to cover

- **Requirements**: Design a multi-language streaming transcription service with partial and final transcripts and a configurable latency/accuracy trade-off.
- **Estimates**: 50k concurrent streams; partial results every ~300 ms; finals within ~1 s; 50 languages.
- **API**
- **Data model**
- **Architecture**: WebSocket ingestion; voice-activity detection; streaming encoder (conformer with chunked attention) plus transducer or CTC decoding with beam search.; Optional LM fusion, custom vocabulary, punctuation and diarisation post-processing.; GPU batching across streams; language ID; self-supervised pre-training for low-resource languages.; Model registry per language.
- **Deep dives**
- **Trade-offs**: look-ahead vs latency (a max-delay knob); model size vs cost per audio hour; partial-result stability (flicker) vs speed; on-prem vs cloud deployment.
- **Evaluation**: Offline: WER by language, accent and domain, on held-out sets free of benchmark contamination (public test sets may have leaked into training data).; Latency percentiles and partial-to-final edit rate.; Online: customer error reports, cost per hour.

## Reference design

### Requirements

**Functional**: clients stream audio over a WebSocket and receive partial transcripts (fast, may change) and final transcripts (stable) with word timings and confidences; 50 languages plus automatic language identification; optional diarisation, punctuation, number formatting and custom vocabulary; a configurable latency/accuracy knob (`max_delay`).

**Non-functional**: 50k concurrent streams at peak; partials every ~300 ms; finals within ~1 s of the word being spoken at the default setting; regional processing (UK/EU/US) and an on-prem container option; availability ≥ 99.9%, with graceful reconnection.

**Quality**: WER competitive per language, robust across accents and domains (call centres, media, meetings), strong on names and numbers.

**Assumptions to confirm**: input formats (16 kHz PCM, 8 kHz telephony, Opus); a long tail of low-resource languages with little labelled data; enterprise customers need custom vocabulary and data not used for training without consent; billing per audio second.


### Estimates

- **Streams**: 50k concurrent. Partials every 0.3 s → 50k / 0.3 ≈ **167k partial messages/s**.
- **Ingress**: 16 kHz × 16-bit = 32 KB/s per stream → 1.6 GB/s (~13 Gbps) if all raw PCM; Opus at ~32 kbps cuts that ~8×.
- **GPU fleet**: a mid-size chunked conformer-transducer serves ~300 streams per GPU with batching → 50k / 300 ≈ 170 GPUs, ~220 with headroom, split by region and language group.
- **Per-stream state**: cached left context, e.g. 18 layers × 64 frames × 512 dims × 2 (K and V) × 2 bytes ≈ 2.4 MB → 300 streams ≈ 0.7 GB per GPU — small next to model weights.
- **Cost**: 220 GPUs × ~$2/h ≈ $440/h. At full load that is 50k audio-hours per hour ≈ $0.009 per audio hour; at ~40% average utilisation ≈ **$0.02 per audio hour** of compute, far below typical list prices.
- **Latency budget (default)**: audio chunk 160 ms + right-context lookahead ~320 ms + queueing to the next batch tick ≤ 100 ms + compute ~30 ms + network ~50 ms ≈ 660 ms to a stable partial; finals are emitted at endpoint or when `max_delay` (e.g. 1 s) expires.
- **50 languages**: if each had its own model, many would be under-utilised; a few multilingual models plus dedicated models for the top ~10 languages keeps pools large enough to batch well.


### API

```
WS /v1/realtime
  client → {"message": "StartSession", "audio_format": {"type": "raw", "encoding": "pcm_s16le",
            "sample_rate": 16000}, "config": {"language": "en" | "auto", "max_delay": 1.0,
            "enable_partials": true, "diarisation": "speaker", "domain": "finance",
            "additional_vocab": [{"content": "Vodafone", "sounds_like": ["voda phone"]}]}}
  client → binary audio frames … {"message": "EndOfAudio", "last_seq_no": 812}
  server → {"message": "SessionStarted", "id"}
           {"message": "PartialTranscript", "results": [{word, start, end, confidence}]}
           {"message": "FinalTranscript", "results": [...], "speaker": "S1"}
           {"message": "EndOfUtterance"} · {"message": "Warning"|"Error", "reason"}
POST /v1/jobs  (batch file transcription, same config)
```
Sequence numbers on audio frames let a reconnecting client resume without losing or duplicating audio; usage is metered per audio second.


### Data model

- **Session**: id, tenant, region, config, language (requested and detected), model version, worker id, start/end, audio seconds, finals count, error codes.
- **TranscriptSegment** (only if the tenant opts in to storage): session, start, end, words with timings and confidences, speaker.
- **Vocabulary**: tenant, terms, sounds-like hints, compiled biasing artefact per model version.
- **ModelRegistry**: language or language group → model versions, size tier (fast | accurate), WER per evaluation set, latency profile, status (canary | live).
- **UsageRecord**: tenant, session, audio seconds, model tier, region → billing.
- **EvalSet**: language, accent, domain, audio, verified reference transcripts, provenance (to keep held-out data out of training).


### Architecture

```
Client ─WS─► Regional gateway (TLS, auth, sticky session routing)
  ─► Session manager: config, vocabulary compilation, metering
  ─► Pre-processing: decode/resample, VAD (skip silence, endpoint hints)
  ─► Language ID on the first ~2–3 s when language = auto
  ─► Stream scheduler: assigns the stream to a GPU worker for that language
     group and size tier; balances by active streams
  ─► GPU worker: every ~100 ms tick, batch new chunks from all its streams
        streaming encoder (chunked-attention conformer, cached left context)
        + transducer/CTC beam search with contextual biasing (custom vocab)
        + optional external LM fusion per domain
  ─► Partial stabiliser (emit only the stable prefix; tail may change)
  ─► Post-processing: punctuation, inverse text normalisation, diarisation
  ─► results back over the same WebSocket
Model registry per language ─► canary deploys per pool
Self-supervised pre-training on unlabelled audio ─► fine-tune per language,
   critical for low-resource languages
```


### Deep dives

**The max-delay knob.** Streaming accuracy depends on how much future audio (right context) the model sees before committing a word. `max_delay` bounds that: small values (0.7 s) give fast finals with higher WER; larger values (2–4 s) let the model use more context and endpointing patience, lowering WER. Implement it as both the encoder's lookahead and a forced-finalisation timer, and publish WER vs delay curves per language so customers can choose.

**Partial stability.** Partials that flicker ("their" → "there" → "they're") annoy captions users and break downstream agents. Commit only a prefix that has been stable across consecutive decodes; measure the partial-to-final edit rate and trade it against partial latency.

**Batching streams on GPUs.** Streams arrive asynchronously, but GPUs need batches. A fixed tick (~100 ms) collects whatever chunks are ready, runs one batched forward, and returns results; the tick length trades latency against utilisation. Keep per-stream caches resident on the worker, which is why sessions are sticky; on worker failure, the client reconnects and the new worker rebuilds context from a short replay buffer.


### Trade-offs

- **Look-ahead vs latency (max-delay knob)**: more right context, better accuracy, slower finals; per-use-case defaults (captions vs analytics) exposed to customers.
- **Model size vs cost per audio hour**: a larger model cuts WER but serves fewer streams per GPU, multiplying cost; offer fast and accurate tiers and price them accordingly.
- **Partial-result stability (flicker) vs speed**: stabilising partials adds a few hundred ms; let clients opt out if they only need finals.
- **On-prem vs cloud deployment**: on-prem satisfies data-sovereignty customers but loses fleet-wide batching efficiency and slows updates; ship the same containers with a smaller model tier and a clear update cadence.
- **Multilingual vs per-language models**: shared models help low-resource languages through transfer and pool capacity; dedicated models win on top languages where data is plentiful.


### Evaluation

- **Offline**: WER by language, accent and domain on held-out sets with verified references, checked free of benchmark contamination — public test sets may have leaked into training data, so maintain private, recently collected sets; entity accuracy (names, numbers); language-ID accuracy including code-switching.
- **Latency**: partial and final latency percentiles (time from the end of a word in the audio to its emission), measured with synthetic clients per region; partial-to-final edit rate.
- **Load and resilience**: 50k-stream load tests, worker-kill tests, reconnect correctness.
- **Online**: customer error reports and correction rates, cost per audio hour per tier, GPU utilisation, sessions dropped; per-language WER on consented sampled audio after model releases, with canary comparison before full rollout.


## What a strong design shows

- Builds on streaming-specific models (chunked attention, cached context, transducer decoding) and explains the max-delay latency/accuracy knob.
- Sizes the fleet and cost per audio hour from streams per GPU and batching ticks.
- Handles partial stability, sticky sessions and reconnection, not only model accuracy.
- Serves 50 languages sensibly with multilingual models, language ID and self-supervised pre-training for low-resource languages.
- Evaluates WER by slice on contamination-free private sets alongside latency percentiles and flicker.

---

*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.*
