Spoken Practice Platform and MVP Auth API
Hard · System Design · Software Engineer · Onsite
Prompt
This system design exercise has two connected halves that share an authentication boundary.
Part A — Interactive Spoken Role-Play Platform: Design the backend architecture for a language-learning product where users browse and select real-world speaking situations (such as picking up a rental car at an airport or scheduling a dental checkup), respond aloud to a sequence of conversational prompts, receive live coaching plus a numerical grade, track long-term mastery, and resume unfinished sessions across devices. Define the core services and APIs (catalog, session orchestration, speech recognition, LLM coaching, grading, personalization, and telemetry), schemas and indexes for Scenario, Turn / Prompt, UserSession, Attempt, and UserProgress, model selection and prompt guardrails, latency and per-session token/cost budgets, provider-failure fallbacks, per-learner difficulty/pace adaptation, capacity planning (QPS, concurrency, storage growth, streaming backpressure, retries, and idempotency), voice privacy/compliance, localization, poor-network resilience, and A/B testing of prompt/feedback changes.
Part B — Single-Process MVP Identity & Profile API: Design a clean, fast-to-ship MVP service supporting account registration (email and password), sign-in authentication, profile lookup, profile updates, and account deletion using in-memory data structures. Specify endpoint routes, payloads, and HTTP status codes; compare opaque session tokens against JWTs alongside token lifetimes, refresh handling, header vs. cookie transport, and password hashing; detail dictionary keys and thread-safety/concurrency control; cover rate limiting, input validation, idempotent registration/deletion, structured errors, and baseline observability; and outline how this MVP evolves into a horizontally scaled production service.
Scope & Expectations
- Part A architecture & data design: Clear service boundaries, streaming/REST contracts, and indexed schemas for scenarios, turns/prompts, sessions, spoken attempts, and learner progress, backed by concrete traffic, storage, and token-cost estimates.
- Part A AI quality, resilience & experimentation: Grounded ASR/LLM orchestration, repeatable rubric scoring, adaptive difficulty, strict latency and provider-failover paths, voice privacy/localization/offline handling, and statistically valid experimentation.
- Part B API & security fundamentals: Well-typed REST endpoints and status codes, sound token/cookie/password-hashing choices, idempotent account lifecycle semantics, throttling, validation, and safe logging.
- Part B in-memory concurrency & growth path: Race-free locking around in-memory user, profile, and token maps without blocking unrelated requests, paired with a pragmatic migration plan to durable distributed stores.
Step-by-step walkthrough
Scope the two parts and budget the 45 minutes
This interview packs two distinct exercises into one session: Part A is a large-scale, real-time AI speaking architecture, while Part B is a crisp, single-process MVP authentication and profile service testing API hygiene, concurrency, and security fundamentals. The #1 trap is spending 43 minutes on Part A and rushing Part B. State your time split out loud up front: ~30 minutes on Part A, ~15 minutes on Part B, connected cleanly because Part A's API gateway authenticates learners using Part B's tokens.
Part A requirements & targets - Functional: Browse/search scenarios ("Picking up a rental car", "Scheduling a dental checkup") by target language and level; practice a sequence of prompts (turns) where a learner can retry multiple spoken attempts per turn; stream live transcription, an in-character spoken reply, grounded grammar/phrasing feedback, and a repeatable 0–100 score; track skill progress and resume unfinished sessions on any device. - Non-functional: End of speech to first reply audio
p50 <= 1.2 s,p95 <= 2.0 s; feedback cardp95 <= 2.5 s; deterministic scoring (identical answers should not swing wildly between 62 and 84); graceful degradation when cloud AI providers slow down or rate-limit; strict voice privacy.Part B requirements & targets - Functional:
Register,Login(+Refresh/Logout),Get profile,Update profile,Delete accountusing thread-safe in-memory data structures in a single process. - Non-functional: Proper HTTP status codes, safe password hashing outside locks, rate limiting + hash-pool backpressure, optimistic concurrency on profile edits, and idempotentregisteranddelete.Back-of-the-envelope numbers (Part A & Part B)
Part A scale (assumed: 1,000,000 daily active learners, ~10 target languages) Sessions / day: 1.5 per learner 1,500,000 sessions/day (avg 8 min = 480 s) Attempts / session: 10 turns x 1.3 retries 13 attempts/session -> 19,500,000 attempts/day Attempt rate avg: 226/s peak (3x): ~680 attempts/s Concurrent open sessions avg: 8,333 peak (3x): ~25,000 WebSockets Concurrent ASR streams (91s speech / 480s = 19%) peak: ~4,750 active audio streams REST API traffic (catalog, progress, profile) avg: ~350 req/s peak: ~1,000 req/s Storage growth Attempt rows (~1.5 KB: text, timings, scores) 29.3 GB/day (~10.7 TB/year across 16 user shards) Session rows (~2 KB) 3.0 GB/day Raw learner audio (7 s x 3 KB/s Opus @ 24 kbps) 410 GB/day if kept -> NOT kept by default (24h temp) Opt-in audio (10% consent, 30-day rolling TTL) ~1.2 TB total LLM token & unit-cost budget per 13-attempt session Assumed prices: ASR $0.006/min; small LLM $0.15/$0.60 per 1M in/out; large LLM $2.50/$10; TTS $15/1M chars - Streaming ASR (13 x 7 s = 91 s trimmed speech) $0.0091 - Partner reply (13 x [1,800 in + 60 out] on small LLM) $0.0040 - Feedback JSON (13 x [900 in + 200 out] on small LLM) $0.0033 - TTS (~600 chars/session, 60% pre-rendered on CDN, 40% live) $0.0036 - End-of-session report (3,000 in + 400 out): Small LLM: $0.0007 vs. Large LLM: $0.0115! Total per session (with small-LLM report): ~$0.021/session (~$0.93M/month for 45M sessions) Peak LLM input throughput: 680 attempts/s x 2,700 tokens = ~1.84M input tokens/sThree immediate takeaways from the math: 1. A single large-LLM session report (
$0.0115) would cost more than all 26 per-attempt LLM calls combined ($0.0073)! Default everything to fast small models unless an A/B test proves a larger model improves measurable learning. 2. Part B CPU math: Token verification runs ~1,000 times/s at peak (an O(1) dictionary lookup), token refreshes run ~23/s, and password logins/registrations average ~1/s (~70k/day). However, each password hash intentionally burns~0.15 sof CPU — meaning a 1,000 req/s credential-stuffing attack would demand 150 CPU cores unless stopped by rate limits and a bounded hashing worker pool.Part A: service architecture, APIs, and attempt data flow
Mobile Client (Mic -> On-device VAD -> 20 ms Opus frames; local CDN packs; offline queue) | HTTPS (REST) | WSS (1 per active session) v v [ API Gateway: Part B Token Auth + Rate Limits ] [ Session Orchestrator ] (stateless pods) | | per-turn Redis checkpoint | +-------------------+--------------------+----+-------------+---------------+ | v v v v v | [ Speech Svc ] [ Reply & Feedback ] [ Scoring Svc ] [ Personalize ] [ Content Svc ] | streaming ASR + versioned prompts, async phoneme + Elo skills, scenarios, | cached TTS grounding guardrails fluency rubric difficulty recs CDN packs | \ | / | v v v | [ Unified Model Gateway: provider quotas, priority queues, circuit breakers, $/attempt ] +--> REST reads to Content / Progress / Personalize / Part B Auth & Profile | [ Kafka Event Log ] ---> Progress Aggregator, Skill Elo Updater, Data Warehouse, A/B EngineCore Part A endpoints & internal RPCs
Content Service GET /v1/scenarios?target=en-US&level=A2&q=rental&tag=travel&page_token=... GET /v1/scenarios/{id}?target=en-US -> metadata, prompt overview, immutable CDN pack_url Session Orchestrator POST /v1/sessions (Idempotency-Key; {scenario_id, target}) -> 201 {session_id, ws_url, ...} (returns existing in_progress session for that scenario if one is already open) GET /v1/sessions?status=in_progress -> resumable sessions across devices, newest first GET /v1/sessions/{id} -> current turn, attempts, feedback & scores so far WSS /v1/sessions/{id}/stream -> 20 ms Opus frames up; transcripts, reply, score down POST /v1/sessions/{id}/attempts -> store-and-forward audio upload fallback on bad networks POST /v1/sessions/{id}:complete -> triggers final summary & progress rollup Internal gRPC (Speech / Reply+Feedback / Scoring) Speech.StreamingRecognize(audio, lang, hints) -> partials, final {text, words[start_ms, end_ms, conf]} Speech.Synthesize(text, voice, rate) -> streamed Opus chunks (cached by sha256(text,voice,rate)) Dialog.StreamReply(context) -> streamed character reply + intent + off_topic flag Dialog.GenerateFeedback(context, attempt) -> JSON {task_label, errors[], tip, ui_explanation} Scoring.ScoreAttempt(attempt_id) -> async {pronunciation, fluency, total, status}Why split
StreamReplyandGenerateFeedbackinto two parallel LLM calls? The spoken character reply sits directly on the<= 2.0 sconversational critical path and needs to be tiny (<= 60output tokens), whereas grammar feedback can arrive half a second later (<= 2.5 s) and changes frequently during A/B prompt experiments. Decoupling them keeps voice latency ultra-low and isolates feedback experiments from breaking dialog flow, for only ~900 extra input tokens (~$0.00014) per attempt.Part A: relational data model and indexing strategy
Content tables are small, global, and read-mostly; learner tables (
user_session,attempt,user_progress,user_skill) grow by ~32 GB/day and are hash-sharded byuser_idacross 16 PostgreSQL shards so every single-learner query hits exactly one shard.-- Global content tables (immutable published versions) CREATE TABLE scenario ( scenario_id uuid PRIMARY KEY, slug text UNIQUE NOT NULL, -- e.g., 'airport-car-rental' category text NOT NULL, tags text[] NOT NULL DEFAULT '{}', level_min smallint NOT NULL, -- 1 (A1) .. 6 (C2) level_max smallint NOT NULL, est_minutes smallint NOT NULL, status text NOT NULL -- draft | published | retired ); CREATE TABLE scenario_version ( scenario_id uuid NOT NULL REFERENCES scenario, target_language text NOT NULL, -- BCP 47: 'en-US', 'es-MX', 'ja-JP' version int NOT NULL, title_i18n jsonb NOT NULL, -- {"en": "...", "ko": "..."} role_card text NOT NULL, pack_url text NOT NULL, -- immutable CDN bundle is_current boolean NOT NULL DEFAULT false, PRIMARY KEY (scenario_id, target_language, version) ); -- Enforce at most one active published version per (scenario, target_language) CREATE UNIQUE INDEX idx_one_current_ver ON scenario_version (scenario_id, target_language) WHERE is_current; CREATE TABLE turn_prompt ( scenario_id uuid NOT NULL, target_language text NOT NULL, version int NOT NULL, turn_index smallint NOT NULL, mode text NOT NULL, -- scripted | generated prompt_text text NOT NULL, audio_url text, -- pre-rendered CDN URL for scripted prompts expected_intents jsonb NOT NULL, rubric jsonb NOT NULL, difficulty real NOT NULL, -- Elo-calibrated prompt difficulty PRIMARY KEY (scenario_id, target_language, version, turn_index) ); -- Learner tables (sharded by user_id) CREATE TABLE user_session ( session_id uuid PRIMARY KEY, user_id uuid NOT NULL, scenario_id uuid NOT NULL, target_language text NOT NULL, version int NOT NULL, -- pinned pack version at session start status text NOT NULL, -- in_progress | completed | abandoned current_turn smallint NOT NULL DEFAULT 0, notch smallint NOT NULL, -- adaptive difficulty setting experiment_arms jsonb NOT NULL DEFAULT '{}', -- {"feedback_prompt": "fb-v7-b"} score smallint, started_at timestamptz NOT NULL, updated_at timestamptz NOT NULL ); -- Fast "Continue where you left off" shelf CREATE INDEX idx_sessions_recent ON user_session (user_id, updated_at DESC); -- Prevent duplicate open sessions when a user double-taps Start CREATE UNIQUE INDEX idx_one_open_session ON user_session (user_id, scenario_id, target_language) WHERE status = 'in_progress'; CREATE TABLE attempt ( attempt_id uuid PRIMARY KEY, -- client-generated UUID = idempotency key! session_id uuid NOT NULL, user_id uuid NOT NULL, turn_index smallint NOT NULL, attempt_no smallint NOT NULL, -- 1, 2, 3... retries on the same turn status text NOT NULL, -- received | transcribed | feedback_ready | scored | scored_partial transcript text, asr_words jsonb, -- [{"w", "start_ms", "end_ms", "conf"}] feedback jsonb, scores jsonb, -- {"task", "grammar", "pronunciation", "fluency", "total"} model_versions jsonb NOT NULL, -- exact ASR, LLM, and prompt IDs for audit/A-B latency_ms jsonb, created_at timestamptz NOT NULL, UNIQUE (session_id, turn_index, attempt_no) ); CREATE TABLE user_progress ( user_id uuid NOT NULL, target_language text NOT NULL, scenario_id uuid NOT NULL, completions int NOT NULL DEFAULT 0, best_score smallint, last_practiced_at timestamptz, PRIMARY KEY (user_id, target_language, scenario_id) );Fast scenario discovery runs against a dedicated search index (OpenSearch/Elasticsearch, updated whenever
scenario_versionpublishes), storing one document per(scenario_id, target_language)with per-UI-language text analyzers, level/tag filters, and popularity scores; the Personalization Service re-ranks the top 50 hits for the learner in memory. Attempts older than 13 months are stripped of PII text and archived to Parquet in object storage.Part A deep dive 1: ASR pitfalls, LLM guardrails, and fallback ladder
Solving the "ASR auto-corrects learner mistakes" trap: Standard speech recognizers include an internal language model trained to output grammatically correct native text — so if a learner says "She book the car yesterday", ASR may silently "fix" the transcript to "She booked the car yesterday", hiding the exact grammar error we need to teach! Conversely, ASR may mishear an accented word with low confidence (
conf = 0.42) and cause the LLM to scold the user for something they never meant to say. We handle both: 1. Benchmark and route ASR vendors per language on accented learner speech, keeping phrase hints light so they don't over-bias grammar. 2. Mark words belowconf < 0.65asunclearin the LLM prompt (<learner_speech unclear="yesterday">...) and instruct the feedback model never to flag grammar errors on low-confidence words. 3. Score pronunciation with a dedicated acoustic phoneme-alignment model directly on the 24-hour temp audio clip rather than guessing pronunciation from text.Prompt structure (ordered for provider prefix caching) & grounded corrections: Static system rules, JSON schema, and scenario
role_cardsit in the first ~900–1,100 tokens (reused from provider prefix cache across turns), followed by learner level/UI language, a rolling 6-turn window + summary, and the XML-delimited<learner_speech>. Prompts live in a versioned prompt registry (fb-v7-b), never hardcoded.The worst trust-destroyer in AI tutoring is hallucinating a correction for words the learner never spoke. Code verifies every correction quote before displaying it:
import unicodedata def words_only(text): """Normalize Unicode, lowercase, and turn punctuation/symbols into spaces.""" chars = [] for ch in unicodedata.normalize("NFKC", text).casefold(): if unicodedata.category(ch)[0] in ("P", "S"): chars.append(" ") else: chars.append(ch) return " ".join("".join(chars).split()) def keep_grounded_corrections(transcript, corrections): """Discard any LLM correction whose quoted 'said' span is absent from the actual transcript.""" padded_transcript = " " + words_only(transcript) + " " verified = [] for item in corrections: quoted = words_only(item.get("said", "")) if quoted and (" " + quoted + " ") in padded_transcript: verified.append(item) return verifiedStage deadlines & priority fallback ladder - Per-stage p95 budgets / hard deadlines: Final ASR after speech ends
400 ms(deadline1.0 s-> ask learner to repeat); Reply first token600 ms(deadline1.2 s-> play pre-authored scripted follow-up line); Reply first audio<= 2.0 s; Feedback card2.5 s(deadline4.0 s-> defer to end-of-session summary). - Proactive quota & failover ladder: The Unified Model Gateway mirrors vendor RPM/TPM quotas locally with priority scheduling (1: live replies,2: turn feedback,3: session summaries,4: offline evals), retries once only if sufficient deadline remains, fails over to a pre-validated secondary vendor via 30-second circuit breakers, and caps any runaway session at60,000tokens (switching remaining turns toscriptedmode).Part A deep dive 2: repeatable scoring and adaptive personalization
If you ask an LLM "Give this spoken attempt a score from 0 to 100", identical transcripts score
68on Monday and83on Tuesday — and changing a prompt shifts everyone's grades. Instead, the LLM outputs categorical rubric labels (temperature = 0), acoustic tools measure speech signals, and deterministic code computes the number (including clean weight renormalization if async pronunciation scoring times out):WEIGHTS = {"task": 0.40, "grammar": 0.25, "pronunciation": 0.20, "fluency": 0.15} TASK_POINTS = {"achieved": 100, "partial": 60, "not_achieved": 10} ERROR_PENALTY = {"minor": 5, "major": 15} def grammar_points(errors): total_penalty = sum(ERROR_PENALTY[e["severity"]] for e in errors) return max(0, 100 - total_penalty) def compute_attempt_score(task_label, errors, pronunciation_score, fluency_score): """Deterministic 0-100 score; gracefully renormalizes weights if pronunciation is pending/None.""" parts = { "task": TASK_POINTS[task_label], "grammar": grammar_points(errors), "pronunciation": pronunciation_score, # 0..100 from acoustic phoneme model, or None if unavailable "fluency": fluency_score, # 0..100 from ASR word-timing WPM & >1s pause count } weighted_sum = 0.0 available_weight = 0.0 for key, weight in WEIGHTS.items(): if parts[key] is not None: weighted_sum += weight * parts[key] available_weight += weight status = "scored" if available_weight == 1.0 else "scored_partial" final_score = round(weighted_sum / available_weight) return final_score, status, partsPersonalization & logged ML signals - Within a session:
notchsteps down after 2 struggling turns (slowing TTS speech rate, shortening replies, auto-showing hints) and steps up after 3 smooth turns. - Across sessions: Per-skill Elo ratings (task,grammar,vocabulary,pronunciation,fluency) update against eachturn_prompt.difficulty, recommending scenarios in the 70%–85% expected-success zone while feeding corrected words into spaced repetition and tuning VAD silence thresholds to each user's natural pause pace. - Logged features: Attempt timings (time-to-first-word, WPM, >1s pauses, mean ASR word confidence), hint usage, rubric labels, phoneme scores, retry count,notchtrajectory, and exactmodel_versions.Part A: reliability, safety, localization, offline, and experimentation
- Scale, backpressure & idempotency:
25,000peak WebSockets run comfortably on3–4orchestrator pods per region across 3 regions (~5,000sockets/pod). When global model quota headroom dips below10%, admission control starts new free-tier sessions inscriptedmode; if a slow mobile client's WebSocket send buffer fills, drop supersededpartial_transcriptframes while preserving finals, replies, and feedback. Client-generatedattempt_id(primary key onattempt),Idempotency-Key+idx_one_open_sessionon session creation, andevent_idon progress rollups make every retry double-count-proof. - Safety, PII, & localization: Input/output moderation classifiers intercept unsafe turns (routing self-harm signals to fixed crisis-support copy); raw audio expires in 24 hours by default (30-day opt-in only), zero voiceprints are extracted, PII is scrubbed before analytics, COPPA (
13+US) / GDPR (13–16EU) age gates apply, and localization separates native-adaptedscenario_versionpacks from UI string translations. Downloaded packs support key-phrase offline practice, while lossy networks fall back toPOST /attemptsclip uploads. - Experimentation: Gate prompt updates (
fb-v7-b) on a 2,000-example offline golden set first (>= 99.5%valid JSON, no rise in ungrounded corrections). In online A/B tests, randomize byuser_id(detecting a+1 percentage pointlift on 40% D7 retention at 80% power, alpha 5% takes2 * (1.96 + 0.84)^2 * 0.4 * 0.6 / 0.01^2 ≈ 38,000learners/arm), run>= 2weeks, monitor weekly human-audited false-correction guardrails, and judge true pedagogical quality via 4-week standardized speaking checks so making prompts easier cannot masquerade as better learning.
- Scale, backpressure & idempotency:
Part B: MVP authentication and profile API design
Now shift crisply to Part B (~15 minutes). All endpoints speak JSON and return a uniform error envelope:
{"error": {"code": "EMAIL_TAKEN", "message": "...", "request_id": "req-91a"}}.POST /v1/auth/register (Optional header: Idempotency-Key: <uuid>) body: {"email": "maya@example.org", "password": "...", "display_name": "Maya", "interface_language": "ko", "target_language": "en-US"} -> 201 Created {"user": {...}, "access_token": "...", "refresh_token": "...", "expires_in": 3600} -> 400 VALIDATION_FAILED | 409 EMAIL_TAKEN | 422 IDEMPOTENCY_MISMATCH | 429 RATE_LIMITED POST /v1/auth/login body: {"email": "...", "password": "..."} -> 200 OK {"access_token": "...", "refresh_token": "...", "expires_in": 3600} -> 401 INVALID_CREDENTIALS (identical message & timing whether email is missing or password wrong!) POST /v1/auth/refresh body: {"refresh_token": "..."} -> 200 OK (rotates: issues new access + refresh pair; marks old refresh token used) -> 401 INVALID_TOKEN | TOKEN_REUSED (revokes entire session immediately on replay!) POST /v1/auth/logout Header: Authorization: Bearer <access> -> 204 No Content GET /v1/me Header: Authorization: Bearer <access> -> 200 OK {id, email, display_name, interface_language, target_language, version: 4} + ETag: "4" -> 401 INVALID_TOKEN | TOKEN_EXPIRED | ACCOUNT_DELETED PATCH /v1/me Headers: Authorization: Bearer <access>, If-Match: "4" body: {"display_name": "Maya Lin", "daily_goal_minutes": 15} -> 200 OK (updated profile with version: 5) | 412 PRECONDITION_FAILED | 428 PRECONDITION_REQUIRED DELETE /v1/me Header: Authorization: Bearer <access> (no request body -> clean RFC 9110!) -> 204 No Content (idempotent: retrying with the same non-expired token still returns 204) -> 401 INVALID_TOKEN | TOKEN_EXPIRED | REAUTH_REQUIRED (if login is older than 5 minutes)Key AuthN/AuthZ choices for the MVP: - Opaque 256-bit tokens over JWTs for MVP: Because our MVP runs in one process (and Part A calls it or runs monolithically at launch), random 256-bit tokens stored as SHA-256 hashes give instant revocation on logout, account deletion, or refresh-token theft with zero signing-key rotation ceremony. Access tokens live
1 hour; refresh tokens live30 dayswith single-use rotation (reusing an already-rotated refresh token proves a token was copied and revokes the whole session). - Bearer headers vs. cookies: Mobile clients store tokens in iOS Keychain / Android Keystore and sendAuthorization: Bearer <access>. When adding a browser client, keep the access token in JS memory and store the refresh token in anHttpOnly; Secure; SameSite=Strict; Path=/v1/auth/refreshcookie paired with CSRF protection. - Password security: Hash with standard-libraryPBKDF2-HMAC-SHA256at600,000iterations + 16-byte random salt (zero external dependencies for MVP velocity; upgrade toArgon2idin production). Require12–128characters (supporting long passphrases, aligned with NIST SP 800-63B guidance without frustrating mobile signups via arbitrary symbol rules) and reject top breached passwords. - CleanDELETE /v1/mewithout a body: Putting a JSON password body onDELETEbreaks HTTP proxies (RFC 9110 leavesDELETEbodies undefined) and breaks retry idempotency oncepw_hashis wiped! Instead, require a fresh login (now - session.authenticated_at <= 300 s, standard "sudo mode") when deleting an active account, and keep arevoked = "ACCOUNT_DELETED"session marker so network retries still get204 No Content.Part B: thread-safe in-memory storage and concurrency
We keep all MVP state in plain Python dictionaries guarded by a single
threading.Lockfor compound state transitions — while carefully running slowPBKDF2hashing outside the lock so logins never stall other users!import hashlib import hmac import secrets import threading import time import uuid PBKDF2_ITERATIONS = 600_000 ACCESS_TTL_S = 3600 REFRESH_TTL_S = 30 * 24 * 3600 SUDO_WINDOW_S = 300 def hash_password(password, salt): return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS) def token_key(raw_token): """Store only SHA-256 digests so a memory dump or log leak never exposes usable bearer tokens.""" return hashlib.sha256(raw_token.encode("utf-8")).hexdigest() class AuthStore: """Thread-safe single-process store for users, profiles, and rotating opaque tokens.""" def __init__(self): self.lock = threading.Lock() # users[user_id] -> {"email", "salt", "pw_hash", "status": "active"} OR {"status": "deleted", "deleted_at"} self.users = {} # user_by_email[normalized_email] -> user_id (enforces case-insensitive uniqueness) self.user_by_email = {} # profiles[user_id] -> {"display_name", "version", ...} self.profiles = {} # sessions[session_id] -> {"user_id", "auth_at", "revoked": None | "LOGGED_OUT" | "TOKEN_REUSED" | "ACCOUNT_DELETED"} self.sessions = {} self.sessions_by_user = {} # access[sha256] -> (user_id, session_id, expires_at) self.access = {} # refresh[sha256] -> (user_id, session_id, expires_at, used_bool) self.refresh = {} # Precompute a real 32-byte dummy hash so unknown-email logins do identical work self.dummy_salt = secrets.token_bytes(16) self.dummy_hash = hash_password("dummy-baseline-password", self.dummy_salt) def register(self, email, password, display_name, ui_lang="en", target_lang="en-US"): norm_email = email.strip().lower() salt = secrets.token_bytes(16) # Hash OUTSIDE self.lock (~150 ms CPU; hashlib releases the GIL so other threads run freely) pw_hash = hash_password(password, salt) with self.lock: # Atomic check-then-insert prevents duplicate accounts under concurrent signups if norm_email in self.user_by_email: return None, "EMAIL_TAKEN" user_id = str(uuid.uuid4()) self.users[user_id] = {"email": norm_email, "salt": salt, "pw_hash": pw_hash, "status": "active"} self.user_by_email[norm_email] = user_id self.profiles[user_id] = { "id": user_id, "email": norm_email, "display_name": display_name, "interface_language": ui_lang, "target_language": target_lang, "version": 1, } tokens = self.issue_tokens(user_id, str(uuid.uuid4()), fresh_login=True) return {"user": dict(self.profiles[user_id]), **tokens}, None def login(self, email, password): norm_email = email.strip().lower() with self.lock: user_id = self.user_by_email.get(norm_email) user = self.users.get(user_id) if user_id else None salt = user["salt"] if (user and user["status"] == "active") else self.dummy_salt expected_hash = user["pw_hash"] if (user and user["status"] == "active") else self.dummy_hash # Always compute PBKDF2 + 32-byte constant-time compare to prevent email-enumeration timing leaks candidate_hash = hash_password(password, salt) password_ok = hmac.compare_digest(candidate_hash, expected_hash) if user is None or user["status"] != "active" or not password_ok: return None, "INVALID_CREDENTIALS" tokens = self.issue_tokens(user_id, str(uuid.uuid4()), fresh_login=True) if tokens is None: return None, "INVALID_CREDENTIALS" return tokens, None def issue_tokens(self, user_id, session_id, fresh_login=False): access_tok = secrets.token_urlsafe(32) refresh_tok = secrets.token_urlsafe(32) now = time.time() with self.lock: # Re-verify user under lock in case delete_account() ran while PBKDF2 was hashing user = self.users.get(user_id) if user is None or user["status"] != "active": return None if session_id not in self.sessions: self.sessions[session_id] = {"user_id": user_id, "auth_at": now, "revoked": None} self.sessions_by_user.setdefault(user_id, set()).add(session_id) elif fresh_login: self.sessions[session_id]["auth_at"] = now self.access[token_key(access_tok)] = (user_id, session_id, now + ACCESS_TTL_S) self.refresh[token_key(refresh_tok)] = (user_id, session_id, now + REFRESH_TTL_S, False) return {"access_token": access_tok, "refresh_token": refresh_tok, "expires_in": ACCESS_TTL_S} def refresh_tokens(self, refresh_tok): """Single-use refresh rotation; replaying an already-used token revokes the entire session.""" digest = token_key(refresh_tok) now = time.time() with self.lock: entry = self.refresh.get(digest) if entry is None: return None, "INVALID_TOKEN" user_id, session_id, expires_at, already_used = entry session = self.sessions.get(session_id) if session is None or session["revoked"] is not None or expires_at < now: return None, "INVALID_TOKEN" if already_used: session["revoked"] = "TOKEN_REUSED" return None, "TOKEN_REUSED" self.refresh[digest] = (user_id, session_id, expires_at, True) tokens = self.issue_tokens(user_id, session_id, fresh_login=False) if tokens is None: return None, "ACCOUNT_DELETED" return tokens, None def authenticate(self, access_tok): """Validate bearer token -> (user_id, session_id, error_code).""" now = time.time() with self.lock: entry = self.access.get(token_key(access_tok)) if entry is None: return None, None, "INVALID_TOKEN" user_id, session_id, expires_at = entry # Check expiration FIRST so an expired token never acts valid on retry paths if expires_at < now: return None, None, "TOKEN_EXPIRED" session = self.sessions.get(session_id) if session is None: return None, None, "INVALID_TOKEN" if session["revoked"] is not None: return user_id, session_id, session["revoked"] return user_id, session_id, None def logout(self, access_tok): _, session_id, err = self.authenticate(access_tok) if session_id is not None and err is None: with self.lock: self.sessions[session_id]["revoked"] = "LOGGED_OUT" def get_profile(self, user_id): with self.lock: profile = self.profiles.get(user_id) if profile is None: return None, "ACCOUNT_DELETED" return dict(profile), None def update_profile(self, user_id, changes, expected_version): with self.lock: # Guard against concurrent delete_account() between authenticate() and update_profile() profile = self.profiles.get(user_id) if profile is None: return None, "ACCOUNT_DELETED" if profile["version"] != expected_version: return None, "PRECONDITION_FAILED" profile.update(changes) profile["version"] += 1 return dict(profile), None def delete_account(self, access_tok): """Idempotent account deletion: wipes PII/hash immediately, returns 204 on safe retries.""" user_id, session_id, err = self.authenticate(access_tok) if err == "ACCOUNT_DELETED": return True, None # Already deleted via a non-expired session token -> idempotent 204! if err is not None: return False, err now = time.time() with self.lock: session = self.sessions[session_id] if (now - session["auth_at"]) > SUDO_WINDOW_S: return False, "REAUTH_REQUIRED" user = self.users.get(user_id) if user is None or user["status"] == "deleted": return True, None # Wipe email mapping, password hash, salt, and profile immediately self.user_by_email.pop(user["email"], None) self.users[user_id] = {"status": "deleted", "deleted_at": now} self.profiles.pop(user_id, None) for sid in self.sessions_by_user.get(user_id, set()): self.sessions[sid]["revoked"] = "ACCOUNT_DELETED" return True, NonePart B: non-functionals and production evolution
MVP operational hygiene - Idempotent
register: WhenIdempotency-Keyis supplied, store(key -> sha256(body_without_password), user_id, expires_at)for 24h. A retry with the same key, matching body fingerprint, and valid password issues a fresh token pair (201) without storing raw tokens in the idempotency cache; a different body with the same key returns422. - Rate limiting + bounded hash pool: Enforce token buckets (login: 5/min/email & 20/min/IP;register: 5/hr/IP;refresh: 30/min/session; general API: 120/min/user). Because a distributed botnet rotates IPs and emails, also cap concurrent PBKDF2 workers toN = cpu_coreswith a small bounded queue — shedding excess logins with503 Retry-AfterwhileGET /v1/meand Part A traffic stay fast! - Validation, logging & sweeper: Reject unknown JSON fields (400), enforce<= 16 KBbody size, validate BCP 47 language tags, mask emails and never log passwords or tokens, expose/healthz+ route latency / login-failure / 429 counters, and run a 60-second background thread sweeping expired token hashes and 30-day tombstones.5-step evolution from MVP to production 1. Durable storage & multi-instance horizontal scale: Move
usersandprofilesto PostgreSQL (UNIQUE (lower(email))), and movesessions, rotating refresh hashes,idempotency, and rate-limit buckets to Redis with nativeTTLs (using an admin snapshot export during cutover so zero active sessions are logged out). 2. Account recovery & stronger auth: Add email verification, single-use password-reset tokens,Argon2id(transparently re-hashing PBKDF2 hashes on next login), Sign in with Apple / Google, and optional passkeys / MFA. 3. Stateless cross-service auth: Once Part A splits into independent microservices, issue short-lived (5–10 min) asymmetric JWT access tokens (EdDSA/ES256with rotating JWKS keys) so orchestrators verify requests locally with zero network hops, while keeping30-dayrefresh tokens opaque in Redis for instant revocation. 4. Cross-service deletion saga: Emituser.deletedto Kafka onDELETE /v1/meso Part A shards, Redis checkpoints, and S3 audio buckets purge all learner data with verifiable completion receipts (satisfying GDPR and Apple App Store in-app deletion rules).Summary of the trade-offs
- Part A — Separate
ReplyandFeedbackcalls vs. one combined LLM call: Spends ~900 extra input tokens/attempt ($0.00014) to keep spoken replies on a tight<= 2.0 sbudget and isolate feedback A/B tests from breaking dialog flow. - Part A — LLM rubric labels + deterministic Python math vs. direct LLM numeric scores: Requires maintaining a rubric per language, but guarantees repeatable scores, clean
scored_partialfallback when acoustic scoring lags, and calibration against human graders. - Part A — Acoustic phoneme model + confidence masking vs. grading the ASR transcript alone: Adds an async scoring worker, but prevents ASR's internal language model from hiding real grammar errors or punishing accented learners for recognizer mishears.
- Part B — Opaque SHA-256-hashed session tokens vs. JWTs in the MVP: Trades an O(1) dictionary lookup per call for zero key-management overhead and instantaneous logout, theft revocation, and account deletion — deferring short-lived JWTs until microservice fan-out requires local verification.
- Part B — Hashing outside
self.lock+ bounded hash pool vs. coarse-grained locking: Requires re-checking account status underself.lockafter PBKDF2 finishes, but prevents a150 mspassword hash (or a credential-stuffing wave) from freezing every other API call in the process.
- Part A — Separate
Intuition & how it works
This exercise pairs two complementary systems that meet at the API gateway: Part A is a real-time AI language tutor (like practicing an airport car rental or scheduling a dental checkup aloud and getting instant coaching plus a fair grade), while Part B is the single-process authentication and profile vault that guards user accounts. Think of Part A like a live theater rehearsal with two assistants: an improv partner on stage whose only job is replying naturally within 2 seconds so the conversation flows, and a quiet grading coach on the sideline who checks a strict rubric sheet so the exact same spoken answer always earns the exact same score. Think of Part B like a coat-check counter with numbered claim tickets: the heavy security check (hashing a password) happens in a side lane so the main counter never clogs, while handing out, rotating, or canceling a claim ticket happens atomically at the desk.
Naive designs fail rapidly in both halves. In Part A, asking one giant LLM (Large Language Model) to generate the partner's reply, grammar critique, and a raw 0–100 score in a single blocking call stalls audio latency past 4 seconds, produces noisy scores that jump from 64 to 82 on identical retries, and gets fooled when ASR (Automatic Speech Recognition, speech-to-text) silently auto-corrects a learner's broken grammar ("she book yesterday" -> "she booked yesterday"). In Part B, beginners either wrap the entire login function inside a global lock — letting one intentionally slow 150 ms password hash block every other user — or skip atomic check-then-insert and optimistic concurrency (attaching a version number to updates so two devices editing a profile simultaneously don't silently overwrite each other).
Trace one learner request across Part B and Part A to see how both halves click together:
1. Login & token rotation (Part B): Maya logs in (POST /v1/auth/login). Outside the lock, PBKDF2-HMAC-SHA256 hashes her password (~150 ms); inside the lock, the server issues a 1-hour opaque access_token and a single-use 30-day refresh_token, storing only their SHA-256 digests in memory.
2. Streaming speech & ASR confidence tagging (Part A): Authenticated with Bearer <access_token>, Maya streams 20 ms Opus audio frames (a compact speech codec) over a WebSocket using a client-generated attempt_id (idempotency key, a unique request ID ensuring retries never run or bill models twice). Streaming ASR produces word timestamps and confidences, tagging uncertain words (conf < 0.65) so the tutor never invents fake grammar mistakes.
3. Parallel reply, grounded feedback, & repeatable scoring (Part A): Three tasks fire in parallel: a fast small LLM streams the partner's reply into TTS (Text-to-Speech) in < 2.0 s; a second small-LLM call produces rubric labels and quoted corrections (filtered by code so unquoted hallucinations are dropped); and an async acoustic phoneme model scores pronunciation, feeding deterministic Python math that outputs a repeatable 0–100 score (or scored_partial with renormalized weights if pronunciation is still processing).
4. Safe profile update & idempotent deletion (Part B): Updating Maya's daily goal (PATCH /v1/me with If-Match: "4") increments version to 5 atomically, and deleting her account (DELETE /v1/me within 5 minutes of login) wipes her email, salt, password hash, and profile immediately while marking her sessions ACCOUNT_DELETED so network retries still receive 204 No Content.
Key trade-offs
- Budgeting 30 minutes for Part A and 15 minutes for Part B. Part A tests distributed AI system design while Part B tests API craftsmanship, concurrency, and security hygiene; announcing the split explicitly guarantees you finish both cleanly.
- Parallel
ReplyandFeedbackLLM calls vs. one combined call. Splitting them keeps the spoken reply tiny and fast (p95 <= 2.0 s) and lets engineers A/B test new feedback prompts (fb-v7-b) without risking regressions in dialog naturalness, at a negligible~$0.00014extra input-token cost per attempt. - Categorical LLM rubric labels + code math vs. LLM-generated numeric scores. Having the LLM classify
task_labeland error severities attemperature = 0while Python computes weighted points makes scores repeatable, auditable, and resilient viascored_partialweight renormalization when async acoustic scoring lags. - Dedicated acoustic pronunciation model vs. grading the ASR text transcript. Because speech recognizers bias toward fluent native phrasing, text transcripts erase real learner errors and mis-transcribe accents; running an async phoneme-alignment model on a 24-hour temporary audio clip measures what was actually pronounced.
- Small LLM vs. frontier LLM for the end-of-session summary. Under standard token pricing, one large-LLM summary (
$0.0115) costs more than all 26 per-attempt calls in the entire session combined ($0.0073); defaulting to a tuned small model ($0.0007) keeps total cost near$0.021/session. - PostgreSQL hash-sharded by
user_id+ search index vs. unsharded DB or pure NoSQL. Sharding learner tables byuser_idkeeps 10.7 TB/year of attempts fast and local while preserving relational constraints like partial unique indexes (indexes filtered by aWHEREclause, such as enforcing at most onein_progresssession per scenario), while OpenSearch handles multilingual catalog search. - Opaque server-side tokens in the MVP vs. JWTs (JSON Web Tokens, self-contained signed tokens verified without a central store). Opaque tokens stored by hash give instant logout, refresh-reuse theft detection, and account deletion with zero cryptographic key management in a single-process MVP; short-lived (
5–10 min) JWT access tokens are introduced later when multiple microservices need local verification. - Running
PBKDF2outsideself.lock+ bounded worker pool vs. locking whole handlers. Releasing the lock during password hashing prevents a150 msCPU operation from serializing all traffic, at the small cost of re-verifying insideself.lockthat the user wasn't deleted mid-hash, while a bounded hash queue prevents credential-stuffing waves from starving other endpoints.
Common mistakes
- Spending 42 minutes on Part A and treating Part B as an afterthought. Interviewers specifically grade Part B on status codes (
201,204,401,409,412,429), concurrency races, and password/token storage. - Grading grammar on low-confidence ASR words or letting the LLM invent ungrounded quotes. Always suppress corrections on low-confidence ASR spans and verify in code that every
"said"quote actually appears in the normalized learner transcript. - Crashing score calculation when async pronunciation fails. If
compute_attempt_scoremultipliesweight * Noneinstead of renormalizing weights across available components (scored_partial), one slow model breaks the entire attempt UX. - Putting a JSON password body on
DELETE /v1/me. HTTP proxies routinely stripDELETErequest bodies (undefined in RFC 9110), and wipingpw_hashon the first request makes password verification impossible on a network retry; enforce a 5-minute recent-login window ("sudo mode") onDELETE /v1/meinstead. - Timing and message leaks on
POST /v1/auth/login. Returning"Email not found"or skippingPBKDF2when an email is absent lets attackers enumerate registered users in milliseconds; always hash against a precomputeddummy_salt/dummy_hashand runhmac.compare_digeston equal-length digests. - Unprotected
KeyErrorraces betweenauthenticate()andupdate_profile(). If a user deletes their account on Device A milliseconds after Device B passesauthenticate(), indexingself.profiles[user_id]directly crashes with500 Internal Server Errorinstead of returning401 ACCOUNT_DELETED. - Storing plaintext bearer tokens in memory or idempotency caches. Always key token tables by
sha256(token)so memory dumps or debug snapshots cannot be replayed, and issue fresh token pairs on idempotentregisterretries. - Checking expired tokens after revocation flags on
DELETEretries. Always checkexpires_at < nowbefore checkingrevoked == "ACCOUNT_DELETED", so an access token that expired weeks ago cannot return204onDELETE /v1/me.
Follow-up questions
- How would you detect and mitigate a silent upstream LLM provider update that returns HTTP 200 but degrades grammar-feedback accuracy? Log output-level quality telemetry tagged by exact provider, model, and
feedback_promptversion: the fraction of corrections rejected bykeep_grounded_corrections(), JSON schema validation failure rate, shifts intask_labelor error-severity distributions, and learner "This feedback looks wrong" taps. In addition, run an hourly synthetic canary that replays 200 golden learner transcripts against production endpoints and compares rubric agreement against human-labeled ground truth. If grounding rejections spike or canary agreement drops without a deployment on our side, the Unified Model Gateway automatically shifts that language's traffic to the pre-evaluated secondary provider and pages on-call. - How can you migrate Part B's in-memory user and token dictionaries to PostgreSQL and Redis with minimal downtime and zero forced logouts? Build an authenticated admin snapshot dump (or periodic encrypted disk checkpoint) into the MVP from day one so deploys don't wipe accounts. At cutover, flip auth write endpoints (
register,login,refresh,PATCH /v1/me,DELETE /v1/me) into a ~30-second maintenance window returning503 Retry-Afterwhileauthenticate()reads stay live, dumpusers,profiles,sessions, and SHA-256access/refreshdigests, bulk-load users/profiles into PostgreSQL and sessions/tokens into Redis with remaining TTLs, and route traffic to the new stateless pods. Because clients hold the raw random tokens and Redis now holds the exact same SHA-256 digests andusedflags, every logged-in mobile user stays seamlessly signed in, andPBKDF2password hashes can be upgraded transparently toArgon2idthe next time each user logs in. - If a learner disputes a low score of 61 on a scenario attempt, how does your system audit and explain every point deducted? Every
attemptrow stores the exact transcript, per-word ASR timestamps and confidences, the validated LLM rubric labels and error spans, the raw pronunciation and fluency sub-scores, and the exactmodel_versions(asr,feedback_prompt, scorer version). Becausecompute_attempt_score()is pure deterministic arithmetic over those stored fields, both the learner-facing breakdown UI and support tooling can show the exact point math ("Task: 60 x 0.40 = 24, Grammar: 85 x 0.25 = 21.25...") and highlight which specific high-confidence words triggered deductions. When a learner opted into 30-day audio retention and a human linguist overturns a disputed attempt, that recording and transcript are promoted directly into the offline evaluation golden set so future prompt or model updates are tested against it automatically.
Follow-up questions
- How would you detect and mitigate a silent upstream LLM provider update that returns HTTP 200 but degrades grammar-feedback accuracy?
- How can you migrate Part B's in-memory user and token dictionaries to PostgreSQL and Redis with minimal downtime and zero forced logouts?
- If a learner disputes a low score of 61 on a scenario attempt, how does your system audit and explain every point deducted?
Similar questions
- Interactive Spoken Role-Play Practice
- In-Memory User Authentication and Profile Service
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests