Design a Spoken Role-Play Tutor for Many Languages
System DesignModel answerLast updated
Design a real-time multilingual voice role-play practice feature: content model, session state machine, low-latency audio pipeline, offline mode, personalization, scaling and privacy.
You are designing a feature for a language-learning app where a learner can pick any real-world scenario — ordering at a restaurant, a job interview, checking into a hotel — and hold a spoken, multi-turn dialog with an AI partner in their target language. The AI plays the other role; the learner speaks their lines and gets live hints plus an end-of-session report on pronunciation, grammar, vocabulary and whether they accomplished the scenario's goals.
In a design interview, walk through:
- Clarify and size it. Functional requirements, non-functional targets (latency, availability, cost), and back-of-the-envelope load estimates for sessions, turns and audio volume at millions of users.
- User flows from discovery through briefing, the dialog loop, wrap-up and progress.
- Content modeling — how scenarios, roles, dialog steps, objectives and localized text/audio are represented, versioned and authored.
- Session orchestration — the state machine per session, what state is held where, and how reconnects and pod failures are survived.
- Audio pipeline and latency — capture, voice activity detection, streaming speech recognition, dialog generation, speech synthesis, and a concrete end-to-end latency budget with the techniques that make it fit.
- Offline / degraded mode, personalization and adaptive difficulty, progress tracking, and localization for many locales.
- Service architecture, storage choices, APIs, rate limiting, and how it scales cost-effectively.
- Privacy and security of voice data, plus how you would experiment with and roll out new scenarios.
State your assumptions, justify trade-offs, and call out the edge cases you would protect against.
Hints
Hint 1
Anchor the whole design on one number: ended-speech-to-first-AI-audio latency. Every component choice (streaming vs. batch, cached vs. generated audio) should be justified against that budget.
Hint 2
Separate "conversation" from "assessment." Scoring pronunciation and grammar is expensive and does not need to be on the critical path — run it asynchronously after the turn.
Hint 3
Pre-rendered audio and speculative responses only work because most early-level dialog is predictable; say explicitly where scripted content gives way to open generation as proficiency rises.
Hint 4
Voice is sensitive data: decide retention, consent and deletion up front rather than bolting them on.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and sizing
Functional. Browse a catalog of scenarios filtered by target language and proficiency level; get a short briefing (goal, key phrases); hold a multi-turn spoken dialog with an AI partner voiced in the target language; request hints or fall back to typed/suggested replies; receive an end-of-session report (per-objective completion, pronunciation highlights, corrected sentences, new vocabulary); see progress over time with adaptive difficulty; degraded functionality when offline.
Non-functional. Conversational latency — under roughly one second from the end of the learner's speech to the first AI audio, because that pause is the product. 99.9% session availability. Per-session cost low enough for freemium. Voice is sensitive, biometric-adjacent data, so minimize retention.
Assumptions and load. 10M MAU, 2M DAU. Each active user does ~1.5 sessions of ~5 minutes → ~3M sessions/day. Ten learner turns per session → ~30M turns/day, about 350 turns/second average and ~1,500/second at peak. Concurrency: 3M sessions × 5 min / 1,440 min ≈ 10k average, ~40k peak. Audio: 16 kHz mono Opus at ~24 kbps ≈ 3 KB/s; a 10-second turn is ~30 KB, so ~0.9 TB/day if every byte were kept — which it should not be by default. Total speech volume is on the order of 80k+ hours/day, so inference (recognition, dialog model, synthesis) dominates cost, not storage. That single fact should drive the design: use the cheapest model that clears the quality bar per turn type, and cache aggressively.
2. Content model
Represent a scenario as a directed graph of steps, not a linear script, so conversations can branch.
Scenario(id, slug, version, cefr_range, tags, objectives[], roles[])Role(id, scenario_id, name, persona_prompt, voice_per_locale)Step(id, scenario_id, kind ∈ {scripted, open, branch}, prompt_template, expected_intents[], success_criteria, next_step_ids[])Objective(id, scenario_id, description, rubric)— e.g. "successfully requested a vegetarian option."LocalizedAsset(entity_id, locale, text, audio_url, glossary[], reviewed_by)
Two design decisions matter. First, scripted steps give beginners guardrails (the response is known, so it can be pre-rendered and selected instantly), while open steps let the dialog model improvise inside a persona and objective constraints for advanced learners. Second, version scenarios immutably: a live session and historical analytics both reference scenario_version, so editing content never corrupts an in-flight session or a completed report. Templates with slots (dish names, prices, currency) keep content culturally plausible per locale — yen in Tokyo, euros in Madrid.
3. Architecture
- Client (iOS/Android/Web): microphone capture, on-device voice activity detection, Opus encoding, playback jitter buffer, local cache of downloaded scenario bundles, offline queue.
- Edge/API gateway: auth, rate limiting, WebSocket termination, regional routing, sticky sessions.
- Catalog service: read-heavy, serves bundles from object storage through a CDN.
- Session orchestrator: stateful per session; owns the dialog state machine and calls recognition, dialog generation, synthesis and assessment.
- Assessment service: pronunciation scoring (forced alignment against reference phonemes) and grammar error detection, run asynchronously.
- Personalization service: reads the learner model, returns level, recommendations and difficulty knobs.
- Event bus (Kafka): session events flow to analytics, progress aggregation and experimentation.
APIs: GET /v1/scenarios?lang=es&level=A2, GET /v1/scenarios/{id}/bundle?lang=es (graph + assets + signed audio URLs for offline), POST /v1/sessions → {session_id, ws_url, token}, a bidirectional WS /v1/sessions/{id}/stream (audio up; transcript, AI text, synthesized audio, hints down), idempotent POST /v1/sessions/{id}/turns for offline sync keyed by client-generated turn_id, POST .../complete for the report, GET /v1/users/me/progress. Rate-limit per user and per IP on session creation and on concurrent streams; degrade to text mode rather than dropping users.
4. Session orchestration
The orchestrator holds hot state in memory — current step, recent transcript window, objectives met — and checkpoints to Redis after every turn with a one-hour TTL. A reconnect or pod failure resumes from the last turn instead of restarting. Turns are processed as: final transcript arrives → intent classification → advance or hold the step → generate the reply → stream it. Each turn is appended to an event log so the session is replayable for debugging and for the post-session report.
5. Latency budget and audio pipeline
Target ~800 ms end of speech to first AI audio:
| Stage | Budget |
|---|---|
| Voice activity detection / endpointing | 250 ms |
| Recognition finalization | 100 ms |
| Dialog model first token | 250 ms |
| Synthesis first chunk | 120 ms |
| Network | 80 ms |
Techniques: client-side voice activity detection so only voiced frames are sent (cuts bandwidth and recognition cost); speculative work on partial transcripts — classify intent and prefetch context before the user finishes, and for scripted steps select the response early; stream the dialog output into synthesis sentence by sentence so playback starts on the first clause; pre-render scripted lines into the downloaded bundle so they play in ~0 ms; sticky routing and regional inference pools; barge-in — if the learner starts speaking, stop playback immediately. Capture at 16 kHz mono, ~20 ms Opus frames, with OS echo cancellation and noise suppression; check loudness and clipping locally and prompt "move closer" rather than sending garbage to recognition.
6. Offline, personalization, localization
Offline, run scripted mode only: a small on-device recognizer or keyword spotting advances the graph, reference-phoneme comparison gives a rough pronunciation score, and open-ended steps are hidden or replaced with multiple-choice prompts. Queued turns sync idempotently and are re-scored server-side later.
Personalization keeps a learner model (CEFR estimate per skill, error patterns, mastered scenarios) and adjusts three knobs: step mix (scripted vs. open), speaking rate and vocabulary in the AI's persona prompt, and hint frequency. Localization means per-locale voice, culturally correct slots, right-to-left support, and human-reviewed content — machine translation alone will produce unnatural dialog.
7. Privacy, security, rollout
Store audio only with explicit consent — default to a short retention window (or discard after scoring) and keep transcripts plus scores; offer delete-my-data; encrypt at rest and in transit; scope access tightly; strip identifiers before analytics. For rollout, ship new scenarios behind flags to a small cohort, measure completion rate, turns-to-goal, hint usage, latency p95 and cost per session, then ramp. Common mistakes: putting assessment on the critical path, treating every turn as open-ended generation (cost explodes), forgetting immutable versioning, and designing retention as an afterthought.