Design a Streaming Conversational AI Assistant
System DesignModel answerLast updated
Design the backend architecture for a multi-turn AI chat product with streaming responses, session history, safety controls, and optional tool integrations.
Design a Streaming Conversational AI Assistant
You are asked to design the backend system for a conversational AI product — think of something like a general-purpose chat assistant users interact with through a web or mobile interface.
Your system must support:
- Multi-turn conversations where the model has access to prior context in the session
- Token-by-token streaming so responses appear progressively rather than all at once
- High availability and low latency under peak traffic conditions
- Basic safety controls including input toxicity checks, PII handling, and prompt injection awareness
- Optional tool use, such as routing the model's request to a search index or a calculator service
Walk through your high-level architecture, key data models, how you would scale the inference layer, and how you would measure quality and safety in production.
What the interviewer is looking for:
- Explicit assumptions and back-of-envelope numbers before diving into design
- A clear API contract that handles streaming and error states
- An honest treatment of GPU inference as the system's primary bottleneck
- Concrete strategies for context truncation, streaming reliability, and graceful degradation
- Safety as a first-class concern rather than an afterthought
Hints
Hint 1
Start with scale: estimate daily messages, peak concurrency, and output token throughput. This math will justify every major architectural decision that follows, especially around inference capacity.
Hint 2
GPU inference is the dominant bottleneck and cost center. Discuss continuous batching, KV-cache management, prefix caching, and autoscaling triggers — these are the details that separate a strong answer from a shallow one.
Hint 3
Think through what happens when a client disconnects mid-stream, when the model produces a partial reply, or when a user edits an earlier message. Reliability at the streaming and persistence layer is easy to overlook but will come up as a follow-up.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A strong answer moves through four phases: clarify and size the problem, define the API, design the data model, then deep-dive on the hardest components. Never skip the sizing step — the numbers justify every decision that follows.
1. Requirements and Scale
Functional scope
- Create and manage conversations; send messages; receive streamed replies
- View and delete history; edit earlier messages (which forks the conversation tree); cancel generation mid-stream
- Optional tool calls: search, calculator, others
Non-functional targets
- Availability: 99.9%+
- Time-to-first-token (TTFT) p95 under 1 second; inter-token latency under 50 ms
- History must be durable; partial or failed replies must render cleanly
- Safety filtering on both input and output
Back-of-envelope
| Metric | Estimate |
|---|---|
| Daily active users | 10M |
| Messages/user/day | 10 |
| Average messages/second | ~1,200 |
| Peak (5× average) | ~6,000/s |
| Avg prompt + history | ~2K tokens |
| Avg reply length | ~500 tokens |
| Peak output throughput | ~3M tokens/s |
| Concurrent open streams | ~60K |
| New text storage | ~200 GB/day |
The critical insight: GPU inference is the bottleneck and the dominant cost driver. Everything else is a standard distributed web system.
2. API Design
Use Server-Sent Events (SSE) for streaming rather than WebSockets. Responses are one-directional (server to client), SSE works over plain HTTP, proxies cleanly, and supports resume via Last-Event-ID.
POST /v1/conversations
-> { conversation_id }
POST /v1/conversations/{id}/messages
body: { content, parent_message_id, idempotency_key, tools_enabled }
SSE events: message_start | token | tool_call | tool_result | message_end | error
POST /v1/conversations/{id}/messages/{mid}/cancel
GET /v1/conversations?cursor=...
GET /v1/conversations/{id}/messages
DELETE /v1/conversations/{id}
parent_message_id is how you support edits and regenerations — each creates a new branch rather than mutating history. idempotency_key prevents a client retry from triggering a second generation.
3. Data Model
Users (PostgreSQL) — user_id, plan tier, quota, preferences.
Conversations (wide-column store, e.g. DynamoDB or Cassandra)
- Partition key:
user_id, sort key:updated_at - Fields:
conversation_id, title, model, deleted flag
Messages (same store)
- Partition key:
conversation_id, sort key:message_id - Fields:
parent_id,role(user/assistant/tool/system),content,token_count,model_version,safety_labels,status(streaming/complete/cancelled/failed),created_at
Storing parent_id turns the message list into a tree, which naturally supports branching from edits. Partitioning by conversation_id makes loading a full conversation a single-partition read.
Supporting stores
- Redis: hot cache of recent turns for active sessions; rate-limit counters
- Object storage: attachments and redacted logs for offline evaluation
- Kafka: fan-out for analytics, feedback, and moderation events
4. Architecture Overview
Client ──SSE──> Edge / LB ──> API Gateway (auth, rate limiting, quotas)
│
v
Chat Orchestrator (stateless, holds open stream)
├─ Context Builder ──> Redis / Message Store
├─ Input Safety ──> toxicity classifier, PII detector
├─ Inference Router ──> GPU Fleet (vLLM / TensorRT-LLM)
├─ Tool Executor ──> search, calculator (sandboxed)
├─ Output Safety ──> streaming moderation
└─ Async Persist ──> Kafka ──> Message Store, analytics
Request flow: authenticate → rate-limit → persist user message → build prompt (system prompt + truncated history + new message) → run input safety in parallel with prefill → stream tokens through output filter → persist assistant message incrementally and on completion.
5. Deep Dives
Inference serving — the hardest part
A naive approach (one request per GPU thread) fails immediately at scale. The key techniques:
- Continuous batching with paged KV-cache (vLLM-style): processes multiple requests in a single forward pass, sharing memory across sequences. This improves throughput by roughly an order of magnitude.
- Prefix caching: the system prompt and early conversation turns are identical across requests for the same session. Route by
conversation_idwith consistent hashing to reuse cached KV state on the same replica. - Disaggregated prefill/decode: prefill (processing the prompt) is compute-bound; decode (generating tokens) is memory-bandwidth-bound. Separate pools let you tune each independently and protect TTFT from long prompts.
- Autoscale on KV-cache utilization and queue depth, not CPU. GPU nodes take minutes to initialize and load weights, so maintain warm spare capacity — cold start is not acceptable mid-traffic spike.
- Capacity math: a mid-size model on an 8-GPU node handles roughly 10K output tokens/s. At peak demand of 3M tokens/s you need ~300 nodes plus headroom. This is why quantization, speculative decoding, and model distillation are major cost levers, not just academic choices.
Graceful degradation under overload: maintain priority queues by plan tier; fall back to a smaller model; shed free-tier traffic before paid; cap max_tokens dynamically. Always choose predictable latency over unpredictable queueing.
Context management
A 32K-token context window does not mean you send 32K tokens every request — that explodes cost. Instead:
- Reserve the full system prompt (~500 tokens) and the most recent N turns verbatim
- Summarize older turns with a lightweight async job; store the summary on the conversation record
- Optionally retrieve semantically relevant older turns via embedding similarity
This keeps the prompt under ~8–10K tokens for most sessions while preserving conversational coherence.
Streaming reliability
The orchestrator is stateless; all durable state lives in Redis and the message store. Tokens are appended to a Redis key under message_id as they arrive. On client reconnect with Last-Event-ID, replay from that offset. If the client disconnects: cancel generation after a short grace period (freeing GPU capacity) and mark the message status=cancelled. The UI renders a partial reply with a clear indicator — never a blank or misleading state.
Tool use
When the model emits a structured tool call, the orchestrator validates it against an allowlist, executes it in a sandbox (calculator as a pure function with no eval, search scoped to user permissions), appends the result as a tool role message, and continues generation. Cap the tool loop (e.g., 5 iterations) to bound latency and cost. Stream tool_call and tool_result events so the UI shows what is happening rather than a frozen spinner.
Safety
- Input: run a toxicity/abuse classifier and jailbreak detector in parallel with prompt prefill so they add almost no TTFT. Abort on flag before spending GPU tokens.
- Output: a streaming moderation model checks each chunk and can halt mid-generation; signal a clean
errorevent to the client rather than truncating silently. - PII: regex plus NER model; redact before writing to logs, analytics pipelines, and eval datasets. Encrypt message content at rest. Honor deletion requests with a retention policy.
- Prompt injection: treat any model-returned content that will be re-injected (tool results, retrieved documents) as untrusted. Strip meta-instructions, validate against a schema, and never allow tool results to override system prompt directives.
Common Mistakes to Avoid
- Jumping to architecture without sizing — the numbers justify every major decision
- Treating inference as a black box; not discussing batching, KV-cache, or autoscaling
- Ignoring partial failure states: what renders when a reply is cancelled at token 50?
- Treating safety as a postscript; it belongs in the request path
- Over-engineering history storage before acknowledging the context-window budget problem