Build a Scalable Streaming LLM API
System DesignModel answerLast updated
Design an API that streams LLM responses, starting simple and adding reliability, overload protection, and conversation state.
Build a Scalable Streaming LLM API
Design an API service that accepts text prompts and streams back LLM-generated responses token by token. Start with a basic implementation that handles individual requests independently, then progressively add features for production scale: reliability under load, graceful degradation when dependencies fail, and conversation memory.
Initial Scope
Your first implementation does not need to remember past interactions—treat every incoming prompt as standalone. However, even this basic version must handle authentication, content filtering, request limits, and client disconnections correctly.
Key Considerations
- The LLM backend is an external service with unpredictable response times and capacity limits
- Clients receive tokens as they're generated and may abandon requests mid-stream
- System resources are bounded; define what happens when capacity is exceeded
- Security and content safety apply to every request
Questions You Should Explore
- What format and size restrictions apply to prompts and responses?
- What performance targets (p50, p99 latency) and uptime guarantees are needed?
- What compliance requirements govern content filtering and data retention?
- If you later add conversation memory, must users access history across multiple devices?
Part 1: Core Request Flow
Design the basic architecture for a single stateless request. Explain how a prompt moves through the system from API entry to streamed response, including validation, safety filtering, model invocation, and termination handling.
Your design should address:
- User authentication, rate limiting, prompt validation, and tracing
- An orchestration layer that calls the model service and pipes streamed tokens back
- Handling client disconnects and duplicate requests after partial responses
Part 2: Production Readiness
Extend your design for high throughput and resilience. Cover traffic management when approaching capacity limits, strategies for handling model service outages, multi-region deployment, and architectural changes needed to support persistent conversation history.
Your design should address:
- Request prioritization, queue management, shedding load before saturation
- Timeout policies, fallback behaviors, and avoiding dangerous retries
- Consistency and ordering requirements once conversation state is introduced
- Isolating blast radius of failures
Part 3: Observability and Testing
Define the metrics and tests that reveal whether problems originate in API handling, orchestration logic, or the underlying model service.
Your design should address:
- Latency breakdowns (first token, full response), throughput, error types, abandonment rate
- Resource utilization, safety filter outcomes, dependency status, unit economics
- Scenarios to validate: traffic spikes, model slowdowns, abrupt disconnections, retry storms, regional outages
Hints
Hint 1
Start with a synchronous path for one request before adding queues or state
Hint 2
Distinguish between problems you can retry safely versus those requiring user intervention
Hint 3
Separate metrics for each system boundary: API gateway, orchestrator, model backend
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part 1: Core Request Flow
Architecture Overview
The minimal design has three layers:
-
API Gateway: Terminates TLS, authenticates requests (JWT/API key), enforces per-user rate limits (token bucket), validates prompt length (e.g., 4K tokens max), and assigns unique request IDs for tracing.
-
Orchestration Service: Stateless workers that receive validated prompts, invoke the model backend via HTTP streaming or gRPC, apply content filters to generated tokens, and relay filtered output back to clients via Server-Sent Events or chunked HTTP.
-
Model Backend: External LLM service providing token-by-token generation. We treat this as a black box with variable latency (500ms–10s p99) and finite capacity.
Request Flow
- Client POSTs prompt → Gateway checks auth, rate limit, size
- Gateway forwards to available orchestrator with request ID
- Orchestrator validates against safety policies (no jailbreaks, PII patterns)
- Orchestrator calls model backend, streams response
- Each token passes through output filter (toxicity, banned content)
- Filtered tokens sent to client; request completes when model signals done or timeout reached (30s default)
Cancellation & Disconnects
When clients disconnect, the gateway propagates cancellation to the orchestrator, which terminates the model call immediately to free capacity. If a client retries with the same request ID within a short window (5s), we reject it with 409 Conflict since we cannot guarantee which tokens were already received. After the window, treat as a new request—clients are responsible for deduplication.
Error Handling
- Validation failures (oversized prompt, auth failure): immediate 4xx
- Safety violations: 400 with generic message, log details internally
- Model timeout: 504 Gateway Timeout after 30s
- Model error (5xx from backend): 502 Bad Gateway, do not retry automatically
Part 2: Production Readiness
Admission Control & Backpressure
Orchestrators maintain an in-memory semaphore limiting concurrent model calls (e.g., 100 per instance). When saturated, the gateway queues requests in-memory (bounded at 200) with a 5s wait limit. Beyond queue capacity, return 503 Service Unavailable with Retry-After header. This prevents cascading failures where blocked threads accumulate.
Load Balancing
Gateway uses least-outstanding-requests routing to orchestrators, directing traffic to instances with available capacity. Orchestrators expose a /health endpoint returning current semaphore usage; health checks fail when >90% saturated, removing the instance from rotation.
Dependency Failure Strategies
- Circuit breaker: After 10 consecutive model failures, open circuit for 60s to prevent wasted attempts
- Timeout tuning: Set model timeout at p99 + margin (e.g., 15s) to balance patience vs resource waste
- No blind retries: Never retry after receiving partial tokens—client state is unknown
- Fallback: On model unavailability, optionally return cached canned responses for simple prompts ("I'm temporarily unavailable")
Multi-Region Design
Deploy API gateway + orchestrators + model replicas in 3+ regions. Route users to nearest region via latency-based DNS. Model state is independent per region (no cross-region calls). If one region's model backend fails, gateway can redirect new requests to other regions, accepting higher latency over total failure.
Adding Conversation History
Introducing persistent conversations requires:
- Storage: DynamoDB or Cassandra for message history, keyed by conversation_id + timestamp
- Read path: Orchestrator fetches last N messages (e.g., 10) before calling model, formats as context
- Write path: Append user prompt + assistant response after generation completes
- Consistency: Use conditional writes (optimistic locking) to prevent concurrent updates to same conversation
- Idempotency: Store request_id with each message; duplicate requests return existing response if found within 5min
- Cross-device: Conversation ID is user-scoped, accessible from any device after authentication
This adds latency (10-50ms read + write) and introduces new failure modes (DB unavailable). Separate the DB dependency with its own circuit breaker.
Part 3: Observability and Testing
Key Metrics
Latency (histograms with p50/p95/p99):
- Time to first token (TTFT): measures model responsiveness
- Time to last token: full request duration
- Token generation rate: tokens/second during streaming
- Queue wait time: delay before orchestrator pickup
Throughput & Errors:
- Requests per second by endpoint, status code, cancellation reason
- Active concurrent model calls vs semaphore limit
- Queue depth and rejection rate (503s)
Safety & Cost:
- Safety filter matches by category (toxicity, PII, etc.)
- Tokens processed (prompt + completion) for cost allocation
- Model call success rate, timeout rate, error breakdown
Dependency Health:
- Model backend latency and error rate (separate from API errors)
- DB read/write latency and failure rate (if conversations enabled)
- Circuit breaker state transitions
Testing Strategy
- Load testing: Ramp to 2x expected peak traffic, measure latency degradation and 503 rate
- Chaos testing: Introduce 50% model error rate, verify circuit breaker opens and traffic shifts
- Disconnect simulation: Abort 30% of requests mid-stream, confirm resources are released
- Retry storm: Send duplicate request IDs rapidly, validate 409 responses and no duplicate work
- Regional failover: Take down one region's model, confirm traffic redistributes with acceptable latency
- DB failure (if applicable): Simulate history DB outage, verify graceful degradation (accept requests, skip history)
Common Mistakes
- Assuming infinite model capacity: causes cascading failures without admission control
- Retrying after partial success: can lead to duplicate/corrupted outputs shown to users
- Not canceling model calls: wastes capacity on abandoned requests
- Single timeout for all requests: simple prompts and complex ones have different p99s
- Logging full prompts/responses: exposes PII and sensitive content; log IDs and summaries only