Designing ChatGPT (AI Conversational Assistant)
Difficulty: Advanced · Prerequisites: Message Queues and Caching
TL;DR
An AI chat system accepts user prompts, assembles conversation context, routes to GPU inference servers, and streams the response token-by-token back to the user via SSE. The hard parts: managing context windows (128K tokens max), scaling expensive GPU inference, streaming partial responses in real-time, and handling millions of concurrent conversations.
💡 Three words carry this whole design. A token is the model’s unit of text - roughly three-quarters of a word - and everything here is counted, billed and limited in tokens. The context window is the maximum number of tokens the model can be shown at once, so a long conversation eventually will not fit. A GPU (graphics processing unit) is a processor built for the large matrix multiplications a model runs, and it is the expensive, scarce resource the design exists to ration.
flowchart LR
USER["User"]
API["Chat Service"]
QUEUE["Inference Queue"]
GPU["GPU Pool<br/>LLM Inference"]
DB[("Conversation DB")]
USER -->|"1. Send prompt"| API
API -->|"2. Assemble context"| DB
API -->|"3. Enqueue for inference"| QUEUE
QUEUE -->|"4. Pick job"| GPU
GPU -->|"5. Stream tokens via SSE"| USER
In 3 sentences: User sends a prompt → Chat Service fetches conversation history, assembles a context window, and enqueues an inference request. A GPU server picks the job, runs the LLM (large language model), and streams tokens one-by-one back to the user via SSE. The full response is persisted to the conversation DB for future context.
💡 SSE is Server-Sent Events: a one-way stream from server to browser over an ordinary HTTP response that is simply left open. It is how a word appears on screen the moment the model produces it, instead of after the whole answer is written.
1. Understanding the Problem
An AI chat system like ChatGPT lets users have multi-turn conversations with a large language model. Unlike a traditional request-response API, the LLM generates output token-by-token (taking 5-30 seconds for a full response), so the system must stream partial results back to the user in real-time. The model has a fixed context window (e.g., 128K tokens) so the system must intelligently manage which parts of the conversation history to include. GPU inference is extremely expensive ($2-4/hour per GPU) so efficient scheduling and scaling is critical.
Real examples: ChatGPT (OpenAI), Claude (Anthropic), Gemini (Google), Copilot (Microsoft).
2. Naive First Cut
flowchart LR
USER["User"]
API["API Server"]
LLM["LLM Model<br/>single GPU"]
DB[("One DB")]
USER --> API
API --> LLM
API --> DB
User sends prompt → API calls LLM synchronously → waits 10-30 seconds → returns full response at once.
How it breaks:
- User stares at blank screen for 30 seconds waiting for full response (terrible UX, or user experience — ChatGPT shows words appearing in real-time)
- One GPU serves one request at a time. With 1M concurrent users → need 1M GPUs (impossible, each costs $2-4/hour)
- No context management — sending entire conversation history to LLM exceeds context window after 10 messages
- API server thread is blocked for 30 seconds per request → thread pool exhaustion at 100 concurrent users
- No rate limiting → one user can monopolize GPU resources
- No conversation persistence — refresh the page, history is gone
3. Prior Art We’re Drawing From
- OpenAI Streaming API — Uses Server-Sent Events to stream tokens as they’re generated. Each token is a separate SSE event with a delta field. Client renders incrementally. The connection stays open for the full generation duration (5-60 seconds). (OpenAI API Docs)
- vLLM (UC Berkeley) — High-throughput LLM serving engine using PagedAttention. Batches multiple requests on a single GPU by managing KV-cache memory like virtual memory pages. Achieves 2-4x throughput vs naive serving. (vLLM Paper)
💡 While generating, the model keeps intermediate state for every token it has seen so far - the KV-cache (key-value cache, the model’s stored attention state). PagedAttention stores that state in fixed-size pages so several requests can share one GPU’s memory instead of each reserving a worst-case block. - Anthropic’s Constitutional AI — Multi-layer safety filtering: input classifier → model generation → output classifier. Harmful prompts are rejected before reaching the model; harmful outputs are filtered before reaching the user.
💡 A classifier is a small, cheap model whose only job is to score text on one question - here, “is this harmful?”. It is thousands of times cheaper to run than the model it is protecting, which is the entire reason this layering works. - NVIDIA Triton Inference Server — Production inference orchestrator that handles request batching, model versioning, GPU scheduling, and health monitoring. The standard for deploying LLMs at scale.
💡 Triton is a server that hosts models and handles the batching, versioning and health checks around them, so the inference code does not have to.
4. Functional Requirements
Core (Top 3)
- Send prompt and receive streaming response — user types a message, LLM generates a response streamed token-by-token in real-time (<200ms to first token)
- Multi-turn conversation with context — the model remembers previous messages in the conversation and responds coherently across turns
- Conversation persistence — users can view chat history, continue old conversations, and access them from any device
Discussion
Newest first