Design a Streaming LLM Output Architecture
System DesignModel answerLast updated
Design a scalable backend architecture for real-time AI token streaming featuring resume capability, low latency, prompt cancellation, and fault isolation.
Scenario
You are tasked with building the backend architecture for a high-concurrency generative AI application (such as an interactive document canvas or code generation platform). When a user submits a prompt, the platform must stream the model's text response back to the browser in real time.
Users must be able to interrupt generation at any moment, edit earlier steps to create branching chat threads, and automatically reconnect to active streams if their device loses network connectivity.
Requirements
Functional Requirements
- Low-Latency Streaming: Deliver generated output chunks to the web client with minimal delay as they are emitted by model inference nodes.
- Immediate Cancellation: Abort inference runs upstream as soon as a user clicks "Stop", preventing wasteful GPU utilization.
- Connection Recovery & Resume: If a client disconnects mid-generation, it must be able to reconnect and seamlessly pick up output from the exact index it last saw.
- Thread & State Persistence: Store incomplete and completed user/assistant interactions securely, ensuring state consistency across cancellations, crashes, and branches.
Scale & Non-Functional Constraints
- Scale: 10 million Daily Active Users (DAU), up to 150,000 active concurrent streams at peak output.
- Latency Targets: Time-to-First-Token (TTFT) $p_{95} < 800\text{ms}$; Inter-token gap $p_{95} < 50\text{ms}$.
- Availability: 99.99% operational SLA for retrieving past conversation threads.
- Cost & Efficiency: Hard upper bound of 200ms to propagate cancellation commands from the client to the active GPU inference process.
Discussion Points
- Protocols & Contracts: Compare Server-Sent Events (SSE), WebSockets, and chunked HTTP transfer encoding. Draft the API schemas for both client-gateway communication and gateway-orchestrator-worker pipelines.
- System Architecture: Map out the end-to-end topology from reverse proxies and edge gateways down to session buffers, orchestration layers, and storage engines.
- Data Schema & Ephemeral State: Plan the storage models for persistent conversations, message nodes, and active streaming tokens.
- Reliability & Edge-Case Handling: Detail recovery protocols for dropped connections, worker node crashes, and request deduplication.
- Observability: Highlight core operational metrics needed to monitor latency degradation, token rates, and stream lifecycle health.
Hints
Hint 1
Decouple the lifetime of the inference stream from the client connection lifetime.
Hint 2
Use sequence numbers to turn stream delivery into an append-only log, enabling effortless resume using headers like Last-Event-ID.
Hint 3
Propagate cancellation signal via gRPC context cancellation or Pub/Sub rather than waiting for HTTP connection timeouts.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Design a Streaming LLM Output Architecture
1. Capacity Planning & Scale Requirements
Before selecting system components, we establish operational boundaries to inform our design choices:
- Throughput Target: 150,000 peak concurrent streams emitting tokens at an average rate of 40–50 tokens/sec yields roughly 6 million to 7.5 million tokens/sec across the system.
- Buffer Memory Overhead: Assuming an average generation size of 1,000 tokens (~6 KB of raw UTF-8 payload), holding active state for all 150,000 concurrent generations in memory consumes $150,000 \times 6\text{ KB} \approx 900\text{ MB}$. Factoring in metadata overhead, holding all active streams in an in-memory storage cluster requires under 5 GB of RAM.
- Database Writes: 10M DAU with 20 turns/day = 200M total turns/day. This yields an average write volume of ~2,300 writes/sec, peaking at ~10,000 DB operations/sec. Writing every individual token directly to the primary database is unsustainable and unnecessary.
- Latency Budgets:
- TTFT Budget ($p_{95} < 800\text{ms}$): Gateway processing (~15ms) + Authentication/Rate Limiting (~10ms) + Task Scheduling/Admission (~125ms) + GPU Prefill Stage (~350–600ms).
- Inter-Token Latency ($p_{95} < 50\text{ms}$): Requires non-blocking relay mechanisms. Token delivery must never wait on synchronous disk I/O.
2. API Design & Streaming Protocols
Protocol Comparison
| Criteria | Server-Sent Events (SSE) over HTTP/2 | WebSockets | HTTP/2 Chunked Transfer |
|---|---|---|---|
| Directionality | Unidirectional (Server-to-Client) | Full Duplex | Unidirectional |
| Proxy Compatibility | High (Standard HTTP semantics) | Moderate (Requires UPGRADE header handling) | High |
| Native Reconnection | Native via Last-Event-ID | Custom application-level logic required | Custom application-level logic required |
| Connection State | Stateless at infrastructure layer | Persistent state per proxy | Persistent connection |
Decision: SSE over HTTP/2 for output delivery, paired with standard RESTful POST endpoints for client actions (sending messages, issuing interrupts).
Because generative stream interactions are asymmetric (a single prompt yields thousands of output tokens), full-duplex WebSockets add unnecessary state complexity at the proxy layer. Standard HTTP POST endpoints provide straightforward idempotency handling, authorization, and load balancing for inbound requests.
API Contract (Client ↔ Gateway)
1. Initiate Generation
POST /v1/threads/{thread_id}/messages
Idempotency-Key: 7c9e6679-7425-40de-944b-e07fc1f90ae7
Content-Type: application/json
{
"parent_message_id": "msg_01H1234567890",
"content": "Refactor this function to be async...",
"model": "code-gen-v2"
}
Response (202 Accepted):
{
"message_id": "msg_01H9876543210",
"generation_id": "gen_01H9876543210",
"stream_url": "/v1/generations/gen_01H9876543210/stream"
}
2. Read Output Stream
GET /v1/generations/gen_01H9876543210/stream
Accept: text/event-stream
Last-Event-ID: 42
Response Stream (200 OK):
event: token
id: 43
data: {"text": " async", "seq": 43}
event: token
id: 44
data: {"text": " function", "seq": 44}
event: complete
id: 45
data: {"finish_reason": "stop", "total_tokens": 45}
3. Abort Generation
POST /v1/generations/gen_01H9876543210/cancel
Content-Type: application/json
{}
Response (200 OK):
{
"status": "cancellation_requested",
"generation_id": "gen_01H9876543210"
}
Internal Service Contract (Orchestrator ↔ GPU Worker)
Internal communication uses gRPC with server-side streaming.
syntax = "proto3";
service InferenceRunner {
rpc StreamGenerate (GenerateRequest) returns (stream TokenChunk);
}
message GenerateRequest {
string generation_id = 1;
repeated int32 input_token_ids = 2;
int32 max_tokens = 3;
float temperature = 4;
}
message TokenChunk {
string generation_id = 1;
int64 sequence_number = 2;
string text_delta = 3;
int32 token_id = 4;
bool is_final = 5;
}
3. High-Level Architecture
The core architectural pattern decouples Inference Lifetime from Client Connection Lifetime. If a user's browser disconnects, the background generation process continues operating independently.
+-------------------------------------------------+
| Client Layer |
+-------------------------------------------------+
| ^
POST /messages | | SSE Stream
POST /cancel v | (Last-Event-ID)
+-------------------------------------------------+
| API & Stream Gateways |
+-------------------------------------------------+
| |
Schedule Request | | Consume Stream
v v
+----------------------------------+ +-------------------------+
| Generation Orchestrator | | Token Buffer Cluster |
+----------------------------------+ | (Redis Streams) |
| | +-------------------------+
gRPC | | Write Frame ^
Stream | +------------------------+
v
+----------------------------------+
| Inference Engine (GPU Worker) |
+----------------------------------+
|
| Async Batch Checkpoints (~1s)
v
+---------------------------------------------------------------+
| Persistent Database (Spanner) |
+---------------------------------------------------------------+
Core Components
- API & Stream Gateway Layer: Stateless HTTP nodes responsible for TLS termination, client auth, rate limiting, and reading streaming events from the buffer layer to feed connected clients via SSE.
- Generation Orchestrator: Manages execution lifecycles. Receives new generation requests, acquires compute capacity from the inference scheduler, opens bidirectional gRPC streams to workers, sequences generated tokens, writes sequence frames to Redis Streams, and executes periodic checkpoints to disk.
- Token Buffer (Redis Stream Cluster): Sharded in-memory message queue. Serves as an ephemeral log for generated tokens, guaranteeing fast sequence reads ($<2\text{ms}$) for streaming clients and enabling instant recovery upon client reconnection.
- Inference Workers: GPU clusters running continuous batching inference servers (e.g., vLLM or TensorRT-LLM). They process prefill and decode phases, streaming generated tokens back to the orchestrator over gRPC.
- Database Storage (Distributed SQL): Persists metadata, message context trees, and full message texts.
4. Data Modeling & State Management
Persistent Storage (Cloud Spanner / CockroachDB)
To support conversation branching (where editing an earlier prompt forks the thread), messages are structured as nodes in a Directed Acyclic Graph (DAG) using parent pointers.
CREATE TABLE threads (
thread_id STRING(36) NOT NULL,
user_id STRING(36) NOT NULL,
title STRING(256),
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
) PRIMARY KEY (user_id, thread_id);
CREATE TABLE messages (
message_id STRING(36) NOT NULL,
thread_id STRING(36) NOT NULL,
parent_message_id STRING(36), -- NULL for thread root node
role STRING(16) NOT NULL, -- 'user', 'assistant', 'system'
content TEXT,
status STRING(16) NOT NULL, -- 'pending', 'streaming', 'completed', 'cancelled', 'failed'
generation_id STRING(36),
token_count INT64,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
) PRIMARY KEY (thread_id, message_id);
Ephemeral State (Redis Cluster)
-
Token Stream Log:
- Key:
stream:gen:{generation_id}(Data structure: Redis Stream) - Entries:
{seq: 42, text: " async", ts: 1710000000} - Policy: Configured with
MAXLEN ~ 2000and TTL of 10 minutes.
- Key:
-
Generation Registry Metadata:
- Key:
meta:gen:{generation_id}(Data structure: Hash) - Fields:
orchestrator_id: "orch-node-88"worker_id: "gpu-worker-104"status: "RUNNING"last_seq: 42
- Key:
5. Resilience, Failure Modes & Edge Cases
Fast Cancellation Pipeline (< 200ms Target)
When a user triggers an interrupt ("Stop generating"):
- The client sends
POST /v1/generations/{gid}/cancel. - The Gateway processes the request, sets the state in
meta:gen:{gid}toCANCELLED, and publishes a message to a Redis Pub/Sub channel keyed bycancel:{orchestrator_id}. - The targeted Generation Orchestrator receives the broadcast within ~5ms and cancels the active gRPC context attached to the GPU worker.
- The GPU worker receives the gRPC cancellation signal, immediately drops the batch request from its continuous batching queue, and frees the associated Key-Value Cache (KV Cache) memory blocks.
- Total latency: HTTP Gateway (10ms) + Redis Pub/Sub (5ms) + gRPC cancel (5ms) + Engine step iteration (~30ms) = ~50ms, well under the 200ms target.
Client Gateway Redis Pub/Sub Orchestrator GPU Worker
| | | | |
|--- POST /cancel ->| | | |
| |-- SET status --->| | |
| |-- PUBLISH ------>| | |
|<- 200 OK ---------| |-- Cancel Msg --->| |
| | | |-- gRPC Cancel ->|
| | | | | [Free KV Cache]
Connection Dropping & Native Resumption
- Client Reconnection: When a disconnected client restores network access, it issues an SSE request including the header
Last-Event-ID: 42. - Gateway Execution: The Gateway reads directly from Redis using
XREAD STREAMS stream:gen:{gid} 42. It replays missed frames to the client instantly without querying the primary database or interrupting the orchestrator. - Orphaned Generations: If a client remains disconnected, the orchestrator continues generating until completion or until a 45-second inactivity timeout triggers self-cancellation.
Persistence Strategy Under Workers/Orchestrator Crashes
To prevent data loss without overloading the database:
- Periodic Checkpointing: The Orchestrator flushes buffered tokens to Spanner every 1 second or 200 tokens (whichever comes first), writing incremental chunk updates.
- Orchestration Crash Recovery: A background worker monitors active generations via heartbeats in Redis. If an orchestrator dies mid-generation, a fallback cleaner detects the missed heartbeats, reads the highest sequence frame available from the Redis Stream, saves the partial content to Spanner with status
failed_interrupted, and marks the stream complete.
6. Observability & Key Metrics
Monitoring a high-throughput streaming AI system requires tracking both standard system health metrics and generative-AI specific latency indicators:
- Time to First Token (TTFT): Measures elapsed time from initial HTTP
POSTsubmission to the first SSE token delivery. Alerts trigger if $p_{95} > 800\text{ms}$. - Inter-Token Latency (ITL): Time delay between consecutive generated tokens within an active stream. Alerts trigger if $p_{95} > 50\text{ms}$.
- Cancellation Propagation Time: Duration between a client invoking
/canceland the GPU worker clearing the batch request from memory. - Orphaned Generation Rate: Percentage of streaming operations completed without an active SSE subscriber listening at the Gateway. High rates indicate broken client reconnect logic.
- Redis Stream Memory Utilization & EVICTION Rate: Tracks RAM usage across the streaming buffer layer to ensure zero data loss before persistent DB writebacks finalize.