Design a Resilient AI Chat Service with Streaming and Failover
System DesignModel answerLast updated
Build a customer-facing chat platform powered by a third-party LLM, handling streaming responses, network interruptions, and provider outages gracefully.
You're designing a real-time chat platform for customer support. Customers visit a company's website or mobile app and interact with an AI assistant. The assistant's responses come from a third-party large language model API that your platform calls.
Your interviewer wants you to focus on three areas:
-
The complete request flow: trace a customer's message from their device through your infrastructure to the LLM provider and back, identifying every component and decision point.
-
Pub/sub architecture: explain where message brokering fits, which components publish and subscribe, and how messages route when the customer's WebSocket connection lives on a different server than the one generating the reply.
-
Failure scenarios: this is the core evaluation. Detail your approach when the LLM provider degrades (slow responses, partial failures, or a streamed reply that cuts off mid-sentence) and when the customer's network drops. Cover server-side logic, client-side behavior, and recovery.
Scope and Assumptions
- The LLM provider is external and unreliable: it may be slow, return errors, time out, or stop streaming partway through.
- You control the infrastructure between the customer and the provider.
- Make reasonable assumptions about scale, latency targets, and feature scope. State them clearly.
Questions to Consider
- Should responses stream token-by-token to the customer, or arrive complete?
- Can a customer open the same conversation on multiple devices simultaneously?
- Does the assistant only answer questions, or does it also execute actions like order lookups or refunds?
- How long is chat history retained, and who else accesses it (analytics, compliance, human agent escalation)?
- Is there a human handoff path, and if so, how does the transition work?
Hints
Hint 1
Think about how you'll identify and order messages within a conversation, especially when requests are retried or connections fail.
Hint 2
Consider what partial success means for a streamed LLM response—how do you decide whether to show it to the customer or discard it?
Hint 3
Pub/sub should decouple connection handling from AI processing; sketch the topics and the guarantees you need for each.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A strong answer walks methodically through the happy path, introduces pub/sub as the backbone for routing and fan-out, then systematically tackles failure modes with concrete retry logic, client state machines, and observability hooks.
1. Happy Path Architecture
Components
- Client (web/mobile): Holds a persistent connection (WebSocket preferred for bidirectional streaming and lower latency than SSE or long polling).
- API Gateway / Load Balancer: TLS termination, routing, rate limiting.
- Connection Service: Manages WebSocket connections, tracks which customers are online, publishes inbound messages, subscribes to replies for connected customers.
- Orchestration Service (Agent Workers): Subscribes to new customer messages, retrieves conversation history, builds the LLM prompt, calls the provider, streams the reply back via pub/sub.
- Message Broker (pub/sub): Kafka, Redis Streams, or cloud equivalents. Two channel types: inbound messages (durable) and outbound replies (ephemeral or short TTL).
- Database: Stores conversations, messages, metadata. Append-only message log per conversation with sequence numbers.
- LLM Provider: External API returning streamed or complete responses.
Request Flow
- Customer sends a message over WebSocket to Connection Service.
- Connection Service assigns a unique message ID, writes the message to the database with status
received, publishes to thecustomer-messagestopic withconversationIdand sequence number. - Agent Worker subscribes to
customer-messages, picks up the new message. - Worker fetches recent conversation history (last N messages or sliding window up to token limit).
- Worker constructs the prompt and calls the LLM provider's streaming API.
- As tokens arrive, Worker publishes chunks to the
agent-repliestopic keyed byconversationId, with a sequence number and adoneflag on the final chunk. - Connection Service subscribes to
agent-repliesfiltered by active conversations, forwards chunks over WebSocket to the customer. - Customer's UI appends tokens in real time, rendering the reply as it streams.
- When
doneis received, Connection Service writes the complete reply to the database with statusdelivered.
Data Model
- Conversation:
id,customerId,businessId,createdAt,status(active, resolved, escalated). - Message:
id,conversationId,role(customer|agent|system),content,sequenceNumber,status(received, processing, delivered, failed),createdAt.
Sequence numbers provide total order within a conversation and enable idempotent replay.
2. Pub/Sub Design
Topics and Guarantees
customer-messages(durable, partitioned byconversationId): Inbound messages from customers. At-least-once delivery, ordered per conversation. Enables horizontal scaling of Agent Workers.agent-replies(ephemeral or 5-minute TTL, partitioned byconversationId): Streamed reply chunks and complete replies. Subscribers: Connection Service instances holding active WebSocket connections, and optionally analytics or logging services.system-events(durable): Conversation lifecycle events (created, escalated, closed) for analytics and monitoring.
Routing
Connection Service A holds the customer's WebSocket. Agent Worker B, on a different host, processes the message and publishes reply chunks to agent-replies. Connection Service A subscribes to all agent-replies for its active conversations and forwards the chunk to the correct WebSocket.
Multi-Device Support
If a customer opens the same conversation on phone and laptop, both Connection Service instances subscribe to agent-replies for that conversationId. Each device receives the same streamed reply. The database ensures exactly-once storage of the final message.
Deduplication
Connection Service tracks the last sequenceNumber delivered per conversation. If a duplicate chunk arrives (provider retry, pub/sub redeliver), it's discarded. Agent Workers include a requestId in the database when they start processing a message; if another worker picks up the same message (rare, after a crash), it checks for an existing in-progress reply and either joins or skips.
3. Error Handling
3a. LLM Provider Failures
Failure Modes:
- Complete failure (5xx, timeout): No tokens received.
- Partial failure (stream cuts off): 80% of the reply arrived, then the connection drops.
- Degraded performance: Slow token rate, high latency.
- Rate limit (429): Provider is overloaded or quota exceeded.
Strategy:
- Timeout and retry with exponential backoff: Set a request timeout (e.g., 30s for first token, 60s total). On timeout or retriable 5xx, retry with backoff (1s, 2s, 4s) and jitter. Cap at 3 retries.
- Circuit breaker: After N consecutive failures (e.g., 10 in 1 minute), open the circuit for 30s. During open state, return a fallback reply immediately ("I'm having trouble right now. A human agent will help shortly.") or queue the request for later processing.
- Partial reply handling: If the stream cuts off after delivering ≥50% of an expected reply (heuristic: >100 tokens or a sentence-ending punctuation), store the partial reply with status
partial, show it to the customer with a UI indicator ("Response incomplete—reconnecting..."), and retry the full request in the background. If the retry succeeds, replace the partial reply. If it fails after retries, markfailedand offer escalation to a human. - Rate limit (429): Respect
Retry-Afterheader. Do not retry immediately. Queue the request or return a polite delay message ("High volume right now—your reply is coming in a moment.").
Customer Experience:
- While processing: "Typing..." indicator.
- On transient failure: Keep "Typing..." for a few seconds during the first retry. If retries exhaust, show "Something went wrong. [Retry] or [Talk to a person]".
- Partial reply: Display what arrived with a visual cue (grayed out, spinner at the end). Replace atomically when the full reply arrives, or convert to an error state if recovery fails.
3b. Network Interruptions (Customer Side)
Scenario: Customer's connection drops mid-stream.
Client Behavior:
- Detect disconnection: WebSocket
oncloseoronerrorevent. - Retry connection: Exponential backoff (1s, 2s, 5s, 10s, then every 10s). Maximum 5 minutes of retries before giving up.
- Replay on reconnect: Send a
resumemessage withconversationIdand the lastsequenceNumberthe client successfully rendered. Server responds with any messages the client missed (from database or pub/sub replay if still in buffer). - Idempotent send: If the customer sent a message just before disconnect, the client includes a client-generated
messageId(UUID). On reconnect, if the server already has thatmessageId, it returns the existing reply rather than reprocessing.
Server Behavior:
- Connection Service detects the disconnect, unsubscribes from
agent-repliesfor that connection, but keeps the conversation state. - Agent Worker continues generating the reply and publishes to pub/sub. If no subscriber is active when chunks arrive, they expire (ephemeral topic) or are buffered briefly. The complete reply is always written to the database.
- On reconnect, Connection Service queries the database for messages with
sequenceNumber > lastClientSequence, sends them in a batch, then resumes live streaming if a reply is still in progress.
Edge Case: Message In-Flight During Disconnect
Customer sends message M at t=0, disconnect at t=0.5s, message reaches server at t=1s. Client reconnects at t=3s and resends M (same messageId). Server sees M is already processing or delivered, returns the cached reply or current status.
4. Observability and Metrics
- Provider SLA metrics: Success rate, p50/p95/p99 latency, error rate by status code, stream interruption rate.
- Alerts: Error rate >5% for 2 minutes, p95 latency >10s, circuit breaker open.
- Tracing: Per-conversation trace ID spanning client → Connection Service → Agent Worker → provider → pub/sub → client. Surfaces where time is spent and where failures occur.
- Client-side telemetry: Reconnection rate, time to first token, message delivery confirmation rate.
5. Trade-Offs
- Streaming vs. Complete Replies: Streaming reduces perceived latency and feels interactive, but complicates error handling (partial replies, deduplication). Complete replies simplify state but add latency.
- Retry Aggressiveness: Aggressive retries improve availability but risk overwhelming a degraded provider (thundering herd). Circuit breakers and backoff are essential.
- Message Durability: Durable pub/sub topics (Kafka) guarantee no loss but add cost and complexity. Ephemeral topics (Redis Pub/Sub) are cheaper but require database fallback for missed messages.
- Multi-Device Consistency: Real-time fan-out to all devices is smooth UX but requires more pub/sub bandwidth and subscriber management. Alternative: Poll for updates on secondary devices.
Complexity
- Latency: First token in 200–500ms (network + provider), full reply in 2–5s for typical queries.
- Throughput: Horizontally scalable. Connection Service and Agent Workers scale independently; pub/sub is the bottleneck (mitigated by partitioning on
conversationId). - Failure Recovery: Client reconnects in 1–10s; retries exhaust in ~10s; circuit breaker recovers in 30–60s.
Common Mistakes
- No idempotency: Retrying a customer message without deduplication creates duplicate replies.
- Ignoring partial replies: Discarding 90% of a streamed reply on a minor network blip frustrates customers. Show what you have.
- Retry storms: Every Agent Worker retrying a failing provider simultaneously amplifies the outage. Use jitter and circuit breakers.
- Client gives up too soon: 2-second disconnect shouldn't force the customer to retype their question. Retry for at least a minute.
- No tracing: Without end-to-end traces, diagnosing "replies are slow" is a guessing game across six services.