Live Multi-Speaker Transcription and Resilient LLM Chat

Medium · ML System Design · Machine Learning Engineer · Onsite

Prompt

You are tackling a two-part real-time ML infrastructure problem:

  1. Low-latency multi-speaker speech transcription: Replace an existing offline batch speech-to-text pipeline with an incremental streaming pipeline that transcribes live audio in real time while attributing utterances across multiple talkers.
  2. Resilient multi-model LLM chat platform: Architect a conversational AI backend that streams generated tokens through stateless load balancers, fails over across LLM deployments when rate or context-window ceilings are hit, and persists dialogue history durably and securely.

Operating Constraints & Clarifying Dimensions

  • Network audio frames may arrive out of sequence, show up more than once, or cut off abruptly in the middle of a spoken word or phrase.
  • Provisional transcript segments are mutable and can be refined or relabeled as additional acoustic context is decoded.
  • Switching to a fallback LLM deployment must never weaken content-safety policies, regional residency rules, or tool-execution permissions.
  • Load-balanced web servers cannot depend on a single process holding in-flight stream state exclusively in local RAM.
  • State explicit assumptions for caption latency vs. final word accuracy, split-channel vs. single-microphone mixed diarization, and quota scopes (per request, deployment, tenant, and rolling window).

Part 1 — Incremental Speech Transcription

Specify audio chunk framing, sequence numbering and bounded jitter reordering, provisional vs. finalized segment state transitions, voice-activity endpointing and multi-speaker diarization, overload/backpressure strategies when live talkers cannot pause, and operational/accuracy diagnostics.

Part 2 — Multi-Model Streaming Chat

Specify stateless stream delivery and resumption behind load balancers using externalized state, capability- and policy-locked model routing and fallback, rate-limit reservation, idempotent request and tool handling, durable message persistence, and per-attempt token usage accounting.

Scope & Expectations

  • Clarify latency, word-error-rate, speaker-channel, and quota assumptions up front and translate them into bandwidth, GPU, and token-per-minute capacity estimates.
  • Design the audio ingestion protocol, bounded reorder buffer, versioned partial/final segment model, online diarization, and graceful overload degradation.
  • Architect stateless LLM token streaming across load-balanced pods, capability- and compliance-preserving model fallback, and upfront token-bucket rate limiting.
  • Cover worker crash recovery with fencing, idempotent external tool calls, database write timing, and auditable token accounting.

Step-by-step walkthrough

  1. Clarify requirements and the core mental model

    This interview combines two real-time ML systems: live multi-speaker speech transcription (Part 1) and multi-model streaming chat (Part 2). Although one processes audio and the other generates text, both share one foundational design principle: in-progress output is versioned state, not an append-only log.

    Think of each spoken sentence or chat reply like a numbered draft card on a screen rather than ink printed on a paper receipt. Every segment or message gets a stable ID, a lifecycle status (PARTIAL, FINAL, STREAMING, COMPLETED), and a version counter (revision or attempt). Whenever a speech model refines an earlier word, a speaker label changes, or a chat worker restarts after a failure, the server sends a newer version of that same ID so the client cleanly replaces the provisional text instead of showing garbled duplicates.

    Before designing components, settle the open clarifying questions and state explicit assumptions:

    • Latency and accuracy targets. Assume live captions and call-center agent assist: a spoken word should appear as provisional (PARTIAL) text within p95 <= 500 ms (meaning 95% of words appear within half a second of their audio reaching our server), and a finished sentence should become FINAL within p95 <= 1.5 s after the speaker pauses. Word error rate (WER) — the percentage of words inserted, deleted, or substituted compared to a human reference transcript — must stay within 1 percentage point of the existing offline batch pipeline, with an asynchronous second pass allowed to close the remaining accuracy gap.
    • Speaker diarization. Speaker diarization is the task of figuring out who spoke when. In practice, two setups exist: call-center calls provide separate audio channels (channel 0 = caller, channel 1 = agent), while conference-room microphones capture mixed single-channel audio. Our design supports both and treats mixed-audio speaker labels as provisional so they can be revised as more voice data arrives.
    • Provider rate and token limits. Assume LLM providers enforce limits at four scopes: per request (maximum context window and maximum output tokens), per deployment (requests per minute and tokens per minute for one {provider, model, region, API key} endpoint), per tenant (contractual usage quotas), and global (hourly spend safety caps), measured over rolling 1-minute windows.

    Functional requirements summary

    • Part 1 (Streaming transcription): Ingest chunked live audio over unreliable networks (late, reordered, or duplicate chunks, plus streams ending mid-word); emit low-latency PARTIAL and FINAL transcript segments with word timestamps and speaker labels; produce one complete, high-accuracy transcript after the session.
    • Part 2 (Multi-model chat): Accept user messages, stream replies token by token behind stateless load balancers, resume interrupted streams seamlessly, fall back across models on rate or context limits without altering safety rules or tool permissions, and persist conversation history and token usage accurately.

    Non-functional targets: Support 10,000 concurrent audio streams and 300 new chat replies/s at peak; tolerate any single web pod or worker crash without losing user input or double-billing; encrypt and isolate tenant conversation history.

  2. Back-of-the-envelope numbers

    Estimating traffic, memory, bandwidth, and rate-limit math up front tells us where the real bottlenecks live before we draw a single box.

    PART 1: STREAMING TRANSCRIPTION (10,000 concurrent streams, 16 kHz mono speech)
      Raw PCM audio      16,000 samples/s * 2 bytes (16-bit) = 32,000 B/s (~32 KB/s per stream)
      Compressed audio   Opus speech codec at 24 kbit/s = 24,000 / 8 = 3,000 B/s (~3 KB/s per stream)
      Chunking           100 ms per chunk -> 10 chunks/s per stream (300 B Opus wire, 3.2 KB decoded PCM)
      Gateway ingest     10,000 * 3 KB/s = 30 MB/s (240 Mbit/s) with Opus
                         (raw PCM would be 320 MB/s = 2.56 Gbit/s -> compress on client with Opus)
      Packet rate        10,000 streams * 10 chunks/s = 100,000 chunks/s across gateways
      Audio archive      10,000 * 3 KB/s * 3,600 s = 108,000,000 KB = ~108 GB/hour compressed
      Reorder RAM        300 ms max wait = 3 decoded PCM chunks * 3.2 KB = ~10 KB/stream -> ~100 MB total
      Transcript events  Partials throttled to <= 5 updates/s/stream -> <= 50,000 events/s (~200 B each)
      GPU fleet          If benchmarks show 1 GPU decodes S = 200 live streams within p95 latency:
                         10,000 / 200 * 1.3 headroom = 65 GPUs for live path (+ batch GPUs for 2nd pass)
    
    PART 2: MULTI-MODEL CHAT SERVING (300 new chat replies/s at peak)
      Stream duration    ~400 output tokens at ~50 tokens/s = ~8 s per streamed reply
      Open streams       Little's law (concurrency = arrival rate * duration):
                         300 replies/s * 8 s = 2,400 concurrent open streams
      Input token rate   300 req/s * 3,000 prompt tokens (system + history + new turn) = 900,000 tokens/s
                         900,000 * 60 s = 54.0M input tokens/min
      Output token rate  300 req/s * 400 output tokens = 120,000 tokens/s
                         120,000 * 60 s = 7.2M output tokens/min
      Total token rate   54.0M + 7.2M = 61.2M tokens/min across all active requests
      Provider pooling   If 1 provider deployment allows 10M tokens/min:
                         61.2M / 10M = 6.12 -> need >= 7 deployments (9-10 with 30% burst headroom)
      Stream log writes  2,400 open streams * 10 batched flushes/s (every 100 ms) = 24,000 appends/s
      New DB text/turn   ~200 new user tokens + ~400 assistant tokens = 600 tokens * ~4 B = ~2.4 KB/turn
                         300 turns/s * 2.4 KB = 720 KB/s (~62 GB/day if peak lasted 24 hours; ~20 GB/day typical)
    

    Two architectural lessons jump right out of these numbers:

    1. Part 1 is constrained by real-time physics and GPU compute. A live human speaker generates 1 second of audio every second and cannot be paused like a file upload. Backpressure must therefore mean archiving raw audio first and gracefully degrading or catching up on decoding, never blocking the microphone.
    2. Part 2 is constrained by provider token-per-minute quotas, not web sockets. Holding 2,400 open HTTP streams takes only a handful of stateless web pods, whereas 61.2M tokens/minute exceeds any single API key's quota. Capability-aware pooling and fallback across multiple deployments is mandatory even during normal peak traffic.
  3. Part 1: Streaming protocol, versioned segments, and architecture

    To handle packet drops, reconnects, and revisions cleanly, we separate transport ordering from audio timeline position on the way up, and give every transcript segment a monotonic revision on the way down.

    • PCM (Pulse-Code Modulation) is uncompressed digital audio represented as raw amplitude samples at a fixed rate (such as 16,000 samples per second), while a codec like Opus compresses speech on the client to cut bandwidth 10x before our worker decodes it back to PCM.
    • A lease is a time-limited ownership lock renewed by heartbeats, and an epoch (also called a fencing token) is an integer that increments every time a new worker takes over a stream so stale messages from a slow or crashed worker can be rejected.
    UPSTREAM (Client -> Ingest Gateway over WebSocket or gRPC stream)
      AudioChunk {
        stream_id,
        seq: 0, 1, 2, ...          // per-stream packet counter for deduplication and ordering
        start_sample: 0, 1600, ... // exact position on the 16 kHz audio timeline (100 ms = 1,600 samples)
        num_samples: 1600,
        channels: 1 | 2,
        codec: "OPUS",
        payload: <bytes>,
        is_last: false
      }
      Ack { stream_id, acked_through_seq }   // sent ONLY after the chunk is safely written to the archive
    
    DOWNSTREAM (Transcript Store -> Client / Subscribers)
      Segment {
        stream_id,
        segment_id: 0, 1, 2, ...             // stable ID for one utterance on the timeline
        revision: 1, 2, 3, ...               // strictly increasing counter per segment_id, assigned by store
        status: PARTIAL | FINAL | REVISED | RETRACTED,
        start_ms, end_ms,
        channel,
        speaker: { label: "S1", confidence: 0.91 },
        text,
        stable_prefix_len,                   // count of leading words unlikely to change (reduces UI flicker)
        words: [{ text, start_ms, end_ms, confidence, speaker }],
        flags: { has_gap, truncated, overlap_speech },
        source: STREAM | SECOND_PASS
      }
      StreamEvent = UPSERT(Segment) | RESET_AFTER { stream_id, epoch, from_ms }
    

    Why this contract makes the client simple: The client maintains a dictionary segments[segment_id]. When UPSERT(seg) arrives, the client overwrites segments[seg.segment_id] if and only if seg.revision > stored.revision, then renders segments sorted by start_ms. Live partial updates, finalization, speaker relabeling, and second-pass fixes all use this single rule. To prevent a zombie live worker from overwriting anything, the segment store checks that any STREAM write carries the current epoch from the session registry before atomically assigning revision + 1.

      Client (mic / call bridge)
         | AudioChunk {seq, start_sample}            ^ Ack, StreamEvents
         v                                           |
     +----------------------+  1. append raw audio   +-----------------------------+
     | Ingest Gateway       |----------------------->| Audio Archive (append log / |
     | (WebSocket, auth,    |                        | object chunks per stream)   |
     |  bounded fwd queue)  |                        +--------------+--------------+
     +----------+-----------+                                       | replay on crash,
                | 2. route by stream_id                             | late gap repair,
                | (Session Registry: owner worker + lease epoch)    v second pass
                v                                         +------------------------+
     +--------------------------------------------------+ | Second-Pass Worker     |
     | GPU Stream Worker (batches many streams on GPU)  | | (full-context ASR +    |
     |  Opus decode -> ReorderBuffer (<= 300 ms)        | |  offline diarization)  |
     |  -> log-mel features -> VAD / Endpointer         | +-----------+------------+
     |  -> Streaming ASR -> Online Diarizer             |             | REVISED
     |  -> Segment Builder (checkpoints on each FINAL)  |             |
     +------------------------+-------------------------+             |
                              | UPSERT (checked vs epoch)             |
                              v                                       v
                    +---------------------------------------------------+
                    | Transcript Event Log + Versioned Segment Store    |
                    +-------------------------+-------------------------+
                                              | coalesced fan-out
                                              v
                            Subscribers (live UI, agent assist, analytics)
    

    Inside the ML pipeline on the worker:

    1. Feature extraction: Converts decoded PCM audio incrementally into log-mel spectrograms (25 ms sliding windows with a 10 ms hop across 80 frequency bands on a human-hearing scale).
    2. Voice Activity Detection (VAD) and Endpointer: VAD is a lightweight neural classifier that distinguishes human speech from background silence or noise so silent audio never wastes GPU decoder compute. The endpointer watches for ~600 ms of continuous non-speech to mark the end of an utterance and trigger a FINAL segment.
    3. Streaming ASR (Automatic Speech Recognition): Uses a causal or chunked-attention Conformer encoder with limited look-ahead (e.g., 160 ms) paired with a CTC (Connectionist Temporal Classification) or neural transducer (RNN-T) decoder that emits word pieces frame by frame across micro-batches of concurrent streams on one GPU.
    4. Second-pass refinement: Once a segment is finalized (or when the call ends), a larger bidirectional model with full left-and-right context re-decodes the archived audio and emits REVISED segments to bring accuracy within 1 WER point of offline batch transcription.
  4. Deep dive 1: Ordering, duplicates, late audio, and mid-utterance cuts

    A streaming neural ASR encoder maintains recurrent or attention cache state across consecutive audio frames, so feeding chunks out of order corrupts its internal state. However, waiting indefinitely for one lost packet freezes live captions for every word spoken afterward.

    We solve this with a bounded reorder buffer (max_wait_ms = 300 ms) in front of each stream's feature extractor. Look at how 5 chunks behave when packet seq=1 is delayed vs. lost:

    Case A: Reordered within 300 ms (repaired cleanly)
      t=0 ms    chunk seq=0 (samples 0..1600) arrives    -> delivered immediately; next_seq = 1
      t=100 ms  chunk seq=2 (samples 3200..4800) arrives -> seq=1 missing! Hold seq=2 in pending buffer
      t=220 ms  chunk seq=1 (samples 1600..3200) arrives -> waited 120 ms (<= 300 ms):
                deliver seq=1, then immediately drain seq=2 -> gap-free audio, next_seq = 3
    
    Case B: Delayed beyond 300 ms (bounded stall + silence fill + second-pass repair)
      t=100 ms  chunk seq=2 (samples 3200..4800) arrives -> hold in pending (arrival = 100 ms)
      t=400 ms  50 ms timer fires: 400 - 100 = 300 ms >= max_wait_ms!
                1. Mark seq=1 as skipped; compute missing gap = 3200 - 1600 = 1600 samples (100 ms)
                2. Feed 1600 samples of silence so all future word timestamps stay aligned
                3. Deliver seq=2 with segment flag has_gap=true; next_seq = 3
      t=950 ms  chunk seq=1 finally arrives -> gateway archives it; buffer returns ("late", chunk)
                -> triggers Second-Pass Worker to re-decode that time range and emit a REVISED segment
    

    Here is the exact buffer logic with clear intermediate variables and comments:

    class ReorderBuffer:
        """Turns out-of-order audio chunks into an ordered timeline without holding any chunk > max_wait_ms."""
    
        def __init__(self, max_wait_ms: int = 300):
            self.max_wait_ms = max_wait_ms
            self.next_seq = 0
            # next_sample tracks the exact sample index where decoded audio ends so far
            self.next_sample = 0
            # pending maps seq -> (chunk, arrival_ms) for future chunks waiting on a gap
            self.pending = {}
            # skipped stores seq IDs we already timed out on and filled with silence
            self.skipped = set()
    
        def push(self, chunk, now_ms: int):
            # If this chunk was previously skipped, the archive now has it; trigger 2nd-pass repair
            if chunk.seq in self.skipped:
                self.skipped.discard(chunk.seq)
                return [("late", chunk)]
    
            # Resends after client reconnects have seq < next_seq or are already buffered; drop them
            if chunk.seq < self.next_seq or chunk.seq in self.pending:
                return [("duplicate", chunk)]
    
            self.pending[chunk.seq] = (chunk, now_ms)
            return self.drain(now_ms)
    
        def drain(self, now_ms: int):
            """Called on every push and by a 50 ms timer so gaps time out even if speech stops."""
            events = []
            while self.pending:
                # Fast path: the exact next sequence number is ready to deliver
                if self.next_seq in self.pending:
                    chunk, _ = self.pending.pop(self.next_seq)
                    events.append(("audio", chunk))
                    self.next_seq += 1
                    self.next_sample = chunk.start_sample + chunk.num_samples
                    continue
    
                # Gap path: check how long the oldest buffered chunk has been waiting
                oldest_arrival_ms = min(arrived_ms for _, arrived_ms in self.pending.values())
                wait_duration_ms = now_ms - oldest_arrival_ms
                if wait_duration_ms < self.max_wait_ms:
                    break
    
                # Wait budget expired: skip missing sequence IDs up to the lowest buffered chunk
                first_available_seq = min(self.pending)
                for missing_seq in range(self.next_seq, first_available_seq):
                    self.skipped.add(missing_seq)
    
                first_chunk = self.pending[first_available_seq][0]
                gap_samples = max(0, first_chunk.start_sample - self.next_sample)
                if gap_samples > 0:
                    # Inject exact-length silence so downstream word timestamps never drift
                    events.append(("silence", gap_samples))
                    self.next_sample += gap_samples
    
                self.next_seq = first_available_seq
            return events
    

    Handling mid-word chunks and mid-utterance disconnects:

    • Chunk cuts mid-word: 100 ms chunks routinely slice right through the middle of a vowel or consonant. Because ReorderBuffer feeds one continuous stream of PCM samples into the feature extractor and decoder, chunk edges are completely invisible to the model — utterances are cut only when the VAD endpointer detects a ~600 ms pause (or at a forced quiet-point cut every ~15–20 s during nonstop monologues so segments stay bounded).
    • Stream ends mid-utterance: If the client sends is_last = true or disconnects cleanly, or if no audio arrives for an idle timeout (e.g., 10 s), the worker pads the decoder's look-ahead window with silence to flush buffered words and emits FINAL with flags.truncated = true. If the client reconnects within a 30 s grace window using the same stream_id, it resends unacknowledged chunks from its 30 s ring buffer, duplicates are dropped by seq, and transcription continues seamlessly.
  5. Deep dive 2: Partial vs. final transcripts and multi-speaker diarization

    Segment lifecycle and flicker control:

      VAD detects speech
             |
             v
      PARTIAL (rev 1) ---> PARTIAL (rev 2) ---> FINAL (rev N) ---> REVISED (rev N+1)
      "let's meet at to"   "let's meet at two"  "Let's meet at 2."  (2nd pass or speaker merge)
             |
             +---> RETRACTED (rev 2)            (throat clear / cough decoded to empty text)
    
    • Throttling and stability: Decoding produces new token hypotheses every 20–40 ms, which would flood the network and make captions jitter wildly. We emit PARTIAL updates only when text changes and at most once every 200 ms (5 updates/s). Words that remain unchanged for 3 consecutive updates and sit more than 1 s behind the live audio edge are counted in stable_prefix_len so the UI renders stable words in solid ink and trailing provisional words in gray.
    • Immutability of live finals: Once the endpointer triggers FINAL, punctuation and capitalization run, the worker checkpoints {last_final_end_sample, next_segment_id, speaker_centroids}, and the live worker never touches that segment again. Only late-audio gap repair, speaker-cluster merges, or the second-pass model can emit REVISED with revision + 1.

    Multi-speaker diarization in both audio modes:

    • Separate channels (call center): Each channel maintains its own VAD and ASR state inside the session, so speaker = channel with near-zero extra latency. The one practical edge case is acoustic cross-talk (the agent's loud voice bleeding into the caller's headset); when identical words appear simultaneously on both channels, we suppress the channel whose signal energy is > 12 dB lower.
    • Mixed single-channel audio (meeting room):
      1. Every 0.5 s over a 1.5 s sliding window of active speech, a speaker-verification network extracts a speaker embedding — a fixed-length vector (e.g., 192 floats) summarizing vocal characteristics such as pitch and timbre.
      2. Online clustering: Each new embedding is compared against active speakers' running average vectors (centroids) using cosine similarity (a score from -1 to 1 measuring how closely two vectors point in the same direction). Above a threshold (e.g., 0.72), we assign that window to the matching speaker and update their centroid; below it, we allocate a new speaker label (S1, S2, capped at e.g. 8).
      3. Provisional labels and merges: In the first 2 seconds of speech, noisy embeddings might split one person into S2 and S3. Once later sentences bring their centroids above the merge threshold, the worker merges S3 -> S2 and publishes REVISED events updating only speaker.label on earlier S3 segments. Overlapping talkers are flagged overlap_speech = true and cleaned up by the offline diarization model in the second pass.
  6. Part 1: Backpressure, diagnostics, offline evaluation, and A/B rollout

    Backpressure when the sender cannot slow down: Because a live speaker always produces 10 chunks/s, our gateway acknowledges every chunk as soon as it lands in the Audio Archive — decoupling durability from GPU speed — and sheds GPU load in four stages:

    1. Admission control: The session registry tracks active streams per GPU worker. Below 20% cluster headroom, newly opened streams either enter "finals-only" mode or receive 503 Service Unavailable with Retry-After.
    2. Progressive degradation by per-stream lag (lag = latest_archived_audio_ms - latest_decoded_audio_ms):
      • lag > 1 s: suppress PARTIAL emissions for that stream (saves downstream fan-out and punctuation work; emit FINAL only).
      • lag > 5 s: migrate the stream to a cooler worker at the next FINAL checkpoint or switch to a smaller, faster ASR model.
      • lag > 30 s: switch to asynchronous catch-up mode reading directly from the Audio Archive faster than real time once GPU capacity frees up.
    3. Bounded forwarding queues: Each gateway holds at most 5 s of audio per stream in memory toward the worker; if full, it drops from the in-memory forwarding queue because the worker can read missed ranges from the Audio Archive.
    4. Slow subscriber coalescing: Each subscriber's outbound buffer is a map keyed by segment_id; if a slow browser tab falls behind, rev 4 simply overwrites unsent rev 2 and rev 3 in O(1) space.

    Diagnostics, offline ML evaluation, and safe rollout:

    • Online operational and ML metrics: Track partial latency (gateway chunk arrival timestamp to first PARTIAL containing that word, p95 <= 500 ms), final latency (pause end to FINAL, p95 <= 1.5 s), real-time factor (RTF) (GPU compute seconds divided by audio seconds; must stay < 0.5 at peak so workers can catch up after bursts), partial instability (fraction of displayed partial words later altered), and transport counters (duplicate rate, reorder rate, silence-filled gap rate).
    • Offline evaluation: Evaluate models on human-transcribed datasets stratified across accents, background noise, domain jargon, channel-split calls, and overlapping meetings. Measure WER for words, diarization error rate (DER) (sum of missed speech, false-alarm speech, and speaker-confusion time divided by total speech duration), and concatenated minimum-permutation WER (cpWER) (WER computed after finding the best one-to-one mapping between predicted speakers S1..Sk and true speakers, testing words and speaker attribution together). Run recorded sessions through a network-chaos replay harness that injects jitter, packet reordering, and 1% packet loss to test ReorderBuffer and model accuracy together.
    • Model rollout: First run shadow mode (mirror 1% of live audio streams to the candidate model, discard its output, verify p95 latency and GPU memory), then run an A/B test randomized by tenant or stream, comparing user manual-edit rates, latency, and human-graded WER on a 0.1% audited sample with crash rate and lag as guardrails.
  7. Part 2: Chat API, durable message lifecycle, and externalized stream state

    Now let's design the streaming multi-model chat service. Behind a stateless L7 load balancer, a client's initial POST and its reconnects after a mobile network blip will hit completely different web pods. We therefore use Server-Sent Events (SSE) — a standard HTTP text stream where browsers automatically reconnect and send a Last-Event-ID header — backed by an externalized Redis Streams log.

    POST /v1/conversations/{cid}/messages
         Headers: Authorization: Bearer <token>, Idempotency-Key: <client-uuid>
         Body:    { content, attachments, tools_requested }
      -> 202 Accepted { user_message_id, assistant_message_id, stream_url }
    
    GET  /v1/messages/{assistant_message_id}/stream
         Headers: Last-Event-ID: <redis-stream-offset>   (optional; resumes mid-stream on any pod)
      -> SSE events:
           meta       { attempt: 1, model: "model-a", notice: null }
           delta      { seq: 14, attempt: 1, text: "Here is " }
           tool_call  { call_id: "tc_1", tool: "search_docs", args: {...} }
           reset      { attempt: 2, reason: "provider_midstream_error" }  // client clears attempt 1 text
           done       { attempt: 2, status: "COMPLETED", finish_reason: "stop", usage: {...} }
    
    POST /v1/messages/{assistant_message_id}/cancel
    GET  /v1/conversations/{cid}/messages?before=<msg_id>&limit=50
    

    Core database schema and message state machine:

    Conversation   { conversation_id, tenant_id, user_id, retention_days, kms_key_id }
    Message        { message_id, conversation_id, role: USER | ASSISTANT | TOOL,
                     status: PENDING | STREAMING | COMPLETED | INCOMPLETE | CANCELLED | BLOCKED | FAILED,
                     attempt, epoch, content_ciphertext, envelope_id, model_used,
                     idempotency_key UNIQUE (conversation_id, idempotency_key) }
    PolicyEnvelope { envelope_id, tenant_id,
                     required_capabilities: { tools, min_context_tokens, json_mode, vision },
                     safety_rules: { moderation_profile, data_region, zero_data_retention,
                                     allowed_tools, tool_scopes } }   // immutable once created!
    Attempt        { message_id, attempt, epoch, deployment_id, started_at, ended_at, outcome }
    ToolCall       { message_id, call_id, tool_name, args_json, status, result_json, idempotency_key }
    UsageLedger    { message_id, attempt, tenant_id, deployment_id, input_tokens, output_tokens,
                     source: PROVIDER | ESTIMATED, cost_micros, UNIQUE (message_id, attempt) }
    

    Architecture with externalized stream state:

    • A transactional outbox is a database table written inside the same SQL transaction as our business data (Message rows), paired with a background relay that publishes jobs to a queue so we never commit a PENDING message without enqueueing its generation job.
      Client                   POST /messages              GET /messages/{id}/stream (SSE)
        |----------------------------------------+    +------------------------------------|
                                                 v    v  (any pod; no sticky sessions)
                                      +--------------------------+
                                      | L7 Load Balancer         |
                                      +------------+-------------+
                                                   v
                                      +--------------------------+  1 SQL txn: user msg +
                                      | Stateless Chat API Pods  |  assistant PENDING + outbox
                                      | (XREAD Redis -> SSE out) +----------------------------+
                                      +------------+-------------+                            |
                                                   ^ XREAD from Last-Event-ID                 v
                                                   |                              +-----------------------+
                                      +------------+-------------+                | Conversation DB       |
                                      | Redis Streams            |                | (sharded by conv_id:  |
                                      | msg:{id}:events (TTL 1h) |                |  messages, envelope,  |
                                      | msg:{id}:epoch           |                |  attempts, ledger)    |
                                      +------------+-------------+                +-----------+-----------+
                                                   ^ Lua epoch-checked XADD                   | outbox job
                                                   |                                          v
                                      +------------+------------------------------------------------------+
                                      | Stateless Generation Workers (claim lease + bump epoch)           |
                                      |  build prompt -> input moderation -> capability-aware router      |
                                      |  -> provider stream -> output moderation -> tool executor         |
                                      +------------+------------------------------------------------------+
                                                   |
                            +----------------------+----------------------+
                            v                      v                      v
                     Deployment A (US)      Deployment B (US)      Self-Hosted vLLM (US)
    
  8. Deep dive 3: Capability-aware model fallback, rate limits, and token accounting

    Why naive fallback is dangerous: If a user's request requires EU data residency, zero provider data retention, and read-only access to calendar_read, blindly switching on a 429 Too Many Requests error to a cheaper US-hosted model or dropping the system policy prompt silently violates security and compliance.

    We prevent this with two hard invariants:

    1. Immutable PolicyEnvelope: At admission, the API pod computes and stores a PolicyEnvelope recording required model capabilities (tools, vision, json_mode, min_context_tokens) and non-negotiable safety rules (data_region, zero_data_retention, moderation_profile, allowed_tools, tool_scopes). Every routing and fallback attempt filters exclusively for deployments satisfying that exact envelope.
    2. Externalized safety and tool enforcement: Models only propose tool calls as JSON; our own worker checks envelope.safety_rules.allowed_tools and tool_scopes before executing anything, and runs our own model-independent input/output moderation classifiers. Switching models can change prose style or latency, never permissions.
    def choose_deployment(envelope, prompt_messages, max_output_tokens: int, registry, rate_limiter):
        """Selects the highest-priority healthy deployment meeting all capability, safety, and quota rules."""
        candidates = registry.ordered_deployments_for_tenant(envelope.tenant_id)
    
        for deployment in candidates:
            # 1. Hard capability check (e.g., tool calling, vision, structured JSON)
            if not deployment.supports_capabilities(envelope.required_capabilities):
                continue
    
            # 2. Hard safety and compliance check (data region, zero retention)
            if not deployment.satisfies_safety(envelope.safety_rules):
                continue
    
            # 3. Count tokens with THIS model's tokenizer (token counts vary 10-25% across families)
            prompt_tokens = deployment.count_tokens(prompt_messages)
            worst_case_tokens = prompt_tokens + max_output_tokens
            if worst_case_tokens > deployment.context_window_tokens:
                continue
    
            # 4. Skip deployments whose circuit breaker is open due to recent 5xx timeouts
            if not deployment.is_healthy():
                continue
    
            # 5. Reserve worst-case tokens upfront in Redis token bucket; reconcile actuals at end
            reserved = rate_limiter.try_reserve(
                deployment_id=deployment.id,
                requests=1,
                tokens=worst_case_tokens,
            )
            if reserved:
                return deployment
    
        # Never weaken the PolicyEnvelope; caller waits briefly, then fails cleanly with retry_after
        return None
    

    Handling rate limits and mid-stream failures cleanly:

    • Reserve worst-case, then refund unused tokens: A token bucket is a shared rate-limit counter in Redis that refills at a steady rate (e.g., 10M tokens / 60 s). Before calling a deployment, the worker reserves prompt_tokens + max_output_tokens; when the reply ends after only 180 tokens instead of max_output_tokens = 1,000, it refunds the unused 820 tokens. Reserving only input tokens would let simultaneous long answers blow past the provider's tokens-per-minute ceiling.
    • Error before the first token (429 or 503): Mark the deployment cooling for its Retry-After header, refund the reservation, and immediately call the next deployment from choose_deployment on attempt + 1. Because zero text was streamed yet, no reset event is needed.
    • Error after tokens were already streamed: Because LLM APIs cannot resume an internal KV-cache mid-stream on another provider, the worker starts attempt + 1 on the next valid deployment, emits meta { attempt: 2, notice: "model_switched" } and reset { attempt: 2 } so the client cleanly replaces the partial text from attempt 1 (or, if > 150 tokens were already streamed and the backup model supports assistant prefill, continues from the streamed prefix).
    • Exact token accounting: Each attempt writes one UsageLedger row keyed uniquely by (message_id, attempt). Completed attempts record PROVIDER-reported token counts; interrupted streams count streamed text with the model's tokenizer and tag source = ESTIMATED so provider costs and tenant quotas reconcile against monthly invoices.
  9. Failure recovery, persistence timing, and privacy

    Recovering from crashes on both systems:

    PART 1: GPU STREAM WORKER CRASH
      1. Worker W1 checkpoints {last_final_sample: 48000, next_seg_id: 6, centroids} on FINAL seg 5, then dies.
      2. Session Registry sees W1's 3 s lease expire -> assigns stream to W2 with epoch = 2.
      3. W2 emits RESET_AFTER {epoch: 2, from_ms: 3000} -> clients drop uncommitted partials after 3.0 s.
      4. W2 replays raw audio from Audio Archive starting at sample 32000 (1 s context overlap before 48000)
         at 4x real-time speed while Gateway routes live chunks to W2; seq deduplication merges the seam.
    
    PART 2: CHAT API POD OR GENERATION WORKER CRASH
      - Chat API pod dies: Client's SSE socket drops -> browser auto-reconnects with Last-Event-ID to
        another pod -> new pod runs XREAD from that offset in Redis Streams -> zero lost tokens.
      - Generation worker W1 dies: W1's 10 s lease expires -> W2 claims job in DB with epoch = 2 ->
        W2 runs ONE atomic Redis Lua script that sets msg:{id}:epoch = 2 AND appends reset {attempt: 2, epoch: 2}.
        Any late token from zombie W1 (epoch 1) is rejected by the Lua epoch check on XADD and by
        WHERE epoch = 2 on the final SQL UPDATE, so stale tokens can NEVER appear after the reset!
    

    Preventing duplicate tool side effects: Before executing any tool (such as create_support_ticket), the worker writes a ToolCall row with a deterministic idempotency key (hash(message_id, call_index, tool_name, args)) — a unique token that lets the receiving API recognize a retry and return the original result without repeating the action. On crash recovery, Worker 2 sees completed ToolCall rows in Postgres and feeds their saved result_json straight back into the prompt rather than calling the tool again.

    Database write timing, privacy, and streaming safety:

    Lifecycle moment              Where data is written               Why
    ----------------------------  ----------------------------------  -----------------------------------------
    1. POST /messages accepted    Postgres (1 txn: USER + PENDING)    Never lose user input; deduplicate retries
    2. Before & after tool call   Postgres (ToolCall args / result)   Prevent duplicate external side effects
    3. Every ~100 ms of tokens    Redis Streams only (NOT Postgres!)  Keep 24,000 appends/s off primary SQL DB
    4. Reply finishes / cancels   Postgres (1 txn: final text, usage) Durable history + exact billing record
    
    • Privacy and multi-tenant isolation: Encrypt content_ciphertext at rest using per-tenant KMS envelope keys (revoking a tenant's key cryptographically shreds their history), scope every SQL query by (tenant_id, conversation_id), keep raw prompt/reply text out of application logs, and pin storage and model routing to envelope.safety_rules.data_region.
    • Streaming output moderation: Run lightweight moderation classifiers every ~20 generated tokens while holding a tiny ~20-token look-ahead buffer before flushing to Redis; if a policy violation triggers, halt the provider stream, mark the message BLOCKED, and emit a new attempt with a safe refusal so the client replaces any partial text.
  10. Scaling, monitoring, and summary of trade-offs

    Horizontal scaling:

    • Part 1: WebSocket ingest gateways scale horizontally on open socket count; GPU workers scale on active streams per GPU (RTF < 0.5 target); the Audio Archive partitions by stream_id; second-pass refinement runs on separate spot/batch GPU pools so spikes never starve live captions.
    • Part 2: Chat API pods scale on open SSE connections; generation workers scale on queue depth and open provider streams; Redis Streams shards by message_id (keys expire 1 hour after done); Postgres shards by conversation_id so every conversation's history and idempotency index sit on a single shard.

    Production monitoring and chat A/B testing:

    • Key alerts: Alert on Part 1 p95 partial/final latency, stream lag > 2 s, silence-filled gap spikes, and WER/DER drift on audited samples; alert on Part 2 time-to-first-token (TTFT), per-deployment 429 rates, fallback/reset rates, stuck STREAMING leases, and daily UsageLedger vs. provider-invoice discrepancies.
    • A/B testing chat routing or models: Randomize by conversation_id or user_id (never per turn, which causes jarring personality shifts mid-chat), enforce identical PolicyEnvelope rules in both arms, and evaluate user regeneration rate, thumbs-down rate, TTFT, and cost per resolved conversation.

    Summary of key trade-offs:

    • 300 ms reorder bound vs. waiting longer: Caps live caption delay to <= 300 ms during packet jitter while relying on silence padding plus the asynchronous second pass to fix rare late packets.
    • Versioned upserts vs. append-only streams: Requires clients to store a small map of segments or track attempt numbers, but unifies partial updates, speaker merges, second-pass edits, slow-consumer coalescing, and crash recovery.
    • Redis Streams + admission/completion SQL writes vs. per-token SQL writes: Shields Postgres from 24,000 token updates/s while still surviving any API pod or worker crash.
    • Strict PolicyEnvelope vs. maximum availability: Refusing to fall back to non-compliant models occasionally returns FAILED with retry_after when all compliant deployments are saturated, trading marginal availability for hard security guarantees.

Intuition & how it works

Imagine watching a live court reporter type on a shared screen instead of printing onto a paper receipt tape. On a paper tape, once a word is printed, you can never erase a misheard syllable, fix a speaker's name, or cleanly restart a sentence if the typist's machine crashes. On a screen made of numbered draft cards, each spoken sentence or chat reply has a stable ID, a status (PARTIAL, FINAL, STREAMING, COMPLETED), and a version number (revision or attempt), so any newer version cleanly replaces provisional text in place.

A naive design treats live audio and streamed LLM tokens as simple append-only byte pipes tied to a single server's memory. That breaks immediately in production: out-of-order audio packets garble stateful neural speech models, a single lost packet stalls every caption behind it if you wait forever, and restarting one web server behind a load balancer drops hundreds of active chat streams. Even worse, naively falling back to "whichever backup LLM has spare quota" when a provider returns a rate-limit error can silently route confidential tenant prompts to the wrong geographic region or allow unauthorized tool calls.

Walk through a tiny concrete trace of both halves working together:

  1. Out-of-order audio arrives (t = 0..220 ms): A caller says "Let's meet at two." Audio chunk seq=0 arrives, then seq=2 arrives before seq=1. The gateway archives every chunk immediately, while the GPU worker's bounded reorder buffer holds seq=2 for 120 ms (within its 300 ms cap) until seq=1 arrives, feeding a gap-free audio timeline to the speech model.
  2. Provisional caption refines in place (t = 350..1,400 ms): The worker emits Segment(id=0, status=PARTIAL, rev=1, text="let's meet at to"). As the speaker pauses, voice activity detection (VAD) — a small classifier that spots speech vs. silence — marks the end of the sentence, and the worker emits Segment(id=0, status=FINAL, rev=2, text="Let's meet at two."), replacing rev=1 cleanly on the client screen.
  3. Chat request admits safely (t = 1,500 ms): The user sends a chat question. Any stateless API pod writes the user message, a PENDING assistant placeholder, and an immutable PolicyEnvelope (locking EU data residency and allowed tools) in one database transaction, then streams updates from Redis Streams over Server-Sent Events (SSE) — an HTTP stream that automatically resumes from Last-Event-ID on any pod.
  4. Mid-stream fallback without weakening safety (t = 2,800 ms): Deployment A fails partway through attempt=1. The worker picks Deployment B (which satisfies the exact same PolicyEnvelope), appends reset {attempt: 2} to Redis Streams so the client wipes the half-sentence from attempt=1, streams the complete answer on attempt=2, and commits the final reply and per-attempt token usage to the database.

Key trade-offs

  • Bounded 300 ms reorder window vs. waiting longer for missing audio. Every millisecond the reorder buffer waits for a delayed packet delays every spoken word after it. Capping the wait at 300 ms and filling any timed-out gap with exact-length silence keeps live captions responsive while letting the asynchronous second pass repair rare late packets from the audio archive.
  • Versioned state (revision / attempt) vs. append-only text streams. Requiring clients to key segments by segment_id and honor reset events adds a few lines of client state management, but handles partial text revisions, speaker-cluster merges, second-pass corrections, crash recovery, and slow-subscriber coalescing with one unified mechanism.
  • Throttled partials with a stable prefix vs. raw frame-by-frame updates. Emitting every decoder step feels slightly faster (~30 ms sooner) but causes distracting UI text flicker and high event fan-out; throttling partials to every 200 ms and marking leading unchanged words via stable_prefix_len trades tiny latency for calm readability.
  • Separate-channel vs. embedding-based speaker diarization. Separate call-center channels give cheap, exact speaker attribution, whereas single-microphone meetings require clustering neural speaker embeddings (fixed-size voiceprint vectors) whose early speaker labels must be treated as provisional and revised as centroids stabilize.
  • Externalized Redis stream log vs. in-process memory streaming. Writing batched token deltas every 100 ms to Redis Streams adds ~1 ms of internal hop latency and a short-lived cache cluster to run, but lets any stateless web pod behind a load balancer serve or resume any stream and keeps 24,000 token writes/s off the primary SQL database.
  • Locked PolicyEnvelope vs. maximum fallback availability. Refusing to fall back to models that lack required tool controls, moderation profiles, or regional residency occasionally yields a FAILED response with retry_after during severe multi-provider outages, which is far safer than silently leaking regulated data or widening permissions.
  • Upfront worst-case token reservation vs. input-only counting. Reserving prompt_tokens + max_output_tokens in Redis token buckets (shared counters that refill at each provider's per-minute quota) and refunding unused tokens at completion temporarily holds extra quota during generation, but prevents concurrent long replies from overshooting provider tokens-per-minute limits.

Common mistakes

  • Treating live captions or chat streams as append-only strings. Without segment IDs, revisions, and reset events, revising a misheard word or restarting a failed generation produces duplicated, half-finished sentences on the user's screen.
  • Ordering audio by network arrival time or waiting indefinitely on a gap. Arrival order scrambles speech frames during network jitter, while an unbounded reorder buffer turns a single dropped UDP/TCP packet into a frozen transcript.
  • Splitting speech utterances on fixed 100 ms chunk boundaries. Fixed time slices chop words in half; chunks are purely for transport, while utterance boundaries must come from pause detection in the VAD endpointer.
  • Trying to apply TCP-style "slow down the producer" backpressure to a live microphone. Humans keep speaking at 1x real time; backpressure must archive raw audio immediately and shed GPU work cleanly (dropping partials, migrating streams, or catching up asynchronously from the archive).
  • Relying on sticky load-balancer sessions to hold chat stream state in one API pod. Rolling deploys, autoscaling, or mobile Wi-Fi-to-cellular handoffs immediately break streams when state lives only inside one web process.
  • Falling back to any reachable LLM without enforcing an immutable policy envelope, or trusting the LLM itself to enforce tool permissions. Always filter candidate deployments against the locked envelope and enforce allowed_tools and tool_scopes inside your own tool-executor code.
  • Fencing crashed workers only when reading streams instead of when writing. A reconnecting client reading from Last-Event-ID past an earlier reset would still see zombie tokens unless Redis Lua scripts and SQL updates reject stale epoch numbers at write time.
  • Writing every single streamed token to the primary relational database. Updating a SQL row 50 times per second across 2,400 concurrent streams creates massive lock and write-amplification contention; stream deltas belong in an ephemeral log like Redis Streams, with SQL writes reserved for admission, tool calls, and completion.

Follow-up questions

  • If an active speech-decoding or LLM-generation worker crashes mid-response, how do you fail over without emitting duplicate or stale text? Both systems combine short heartbeat leases, monotonically increasing epoch fencing tokens, and durable inputs so a replacement worker can take over cleanly without zombie writes. In Part 1, each GPU worker checkpoints {last_final_end_sample, next_segment_id, speaker_centroids} on every FINAL segment; when its 3-second lease expires, a new worker claims epoch + 1, sends RESET_AFTER so clients drop uncommitted partials, and replays archived audio from 1 second before the checkpoint at 4x real-time speed while seq deduplication merges live audio from the gateway. In Part 2, when a generation worker's 10-second lease expires, a new worker claims epoch + 1 in Postgres, executes one atomic Redis Lua script that advances msg:{id}:epoch and appends reset {attempt + 1}, reuses already-persisted ToolCall results so external side effects never repeat, and generates the reply while any late writes from the dead worker fail the epoch check in both Redis and Postgres.
  • At which stages of a chat request's lifecycle should message data be committed to the primary database rather than buffered in an ephemeral stream? Write to the primary SQL database only at state-transition boundaries, never on every streamed token. First, when POST /messages is accepted, insert the USER message, the PENDING assistant placeholder (keyed by client Idempotency-Key), and an outbox job in a single SQL transaction so user input is never lost and retries never double-bill. Second, persist each ToolCall row immediately before and after executing an external tool to guarantee at-most-once side effects across crashes. Third, send the 100 ms token batches only to ephemeral Redis Streams during generation (optionally checkpointing every ~500 tokens on multi-minute answers), and commit the final encrypted text, terminal status (COMPLETED, CANCELLED, INCOMPLETE, or BLOCKED), and UsageLedger row in one SQL transaction when streaming ends.

Follow-up questions

Similar questions

More Distyl interview questions

All 2 Distyl questions →