Design a Resilient AI Customer Support Chat Platform
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a customer-support chat platform where shoppers open a chat widget inside a merchant's web site or mobile app and converse with an automated AI support assistant powered by an external third-party large language model (LLM) API. For instance, a shopper might ask "Has shipment #804 gone out yet?" across an open laptop tab and a phone app simultaneously while the assistant invokes merchant backend tools (such as get_shipment(804) or process_refund) and streams back an answer.
The external model API sits outside your infrastructure boundary: it may respond slowly, return transient HTTP errors, hit rate limits, or sever a token stream mid-sentence. Traffic numbers, retention rules, and latency targets are intentionally omitted—state concrete product and scale assumptions up front (such as whether conversations can escalate to human support reps, whether responses stream live or arrive whole, multi-tab/multi-device behavior, read vs. write tool permissions, retention horizon, and whether an interrupted half-reply may remain in the permanent chat log).
Structure your design around three core areas, placing primary emphasis on failure recovery:
- End-to-end normal turn execution: Trace a single user message (e.g.,
"Has shipment #804 gone out yet?") from button tap on the client until the assistant's reply renders on screen, detailing the client-to-server transport protocol (WebSocket, SSE, or long polling), conversation and message schemas, identifiers and strict per-thread ordering, prompt context assembly, model orchestration, persistence, and delivery acknowledgements. - Publish/subscribe routing: Show how pub/sub decouples stateful client-connection gateways from stateless AI worker nodes so an answer generated on one worker reaches a client socket held on another gateway, distinguishing durable event streams from ephemeral live channels, per-thread ordering, deduplication, and fan-out to open devices and internal consumers (human agent consoles, QA, analytics).
- Resilience under partial upstream and client network failures: Walk through system actions, user-facing UI states, and clean recovery when (a) the upstream LLM vendor partially degrades (elevated error rates, slow first-token latency, or mid-stream disconnects—balancing retries, exponential backoff with jitter, retry budgets, circuit breakers, model failover, and partial-stream cleanup) and (b) the user's device loses and regains network connectivity mid-turn (reconnection handshakes, idempotent resends, pending/failed bubble states, and gap-free stream catch-up).
Scope & Expectations
- Clear assumptions & end-to-end trace: Explicit traffic/latency sizing and a concrete walkthrough of client protocol frames, message/run schemas, dense ordering identifiers, and durable write boundaries.
- Dual-tier pub/sub architecture: Principled separation between durable event logs and low-latency per-conversation live fan-out without coupling AI workers to socket gateways.
- Upstream LLM fault containment: Error classification, bounded single-layer retry budgets with jitter, circuit breaking, multi-level graceful degradation, and safe handling of half-streamed replies and state-mutating tool calls.
- Client disconnect & resume guarantees: Local client outbox + server idempotency keys, reconnect cursor reconciliation, and race-free subscription ordering so transcripts converge with zero duplicates or missing messages.
Step-by-step walkthrough
Clarify requirements and state assumptions
Because the prompt leaves scale and product rules open, start by answering the clarifying questions out loud so your interviewer can confirm or adjust them.
Product & failure assumptions:
- AI-first with seamless human handoff: An AI agent answers customer chats first and can hand the conversation off to a human support agent (on customer request, low confidence, or policy rules like high-value disputes), who replies inside the exact same chat thread.
- Token-by-token streaming: Replies stream live as words are generated so the customer starts reading in ~1–2 seconds rather than staring at a blank bubble for 6 seconds.
- Multi-device, multi-tab sync: Customers connect from a browser widget or mobile SDK (iOS/Android) and may have the same chat open across two browser tabs and a phone simultaneously; every screen must converge to the exact same transcript.
- Read and write tools: The AI agent calls merchant APIs—both read-only lookups (
get_shipment) and state-changing actions (process_refund,update_address). Repeating a lookup is harmless; repeating a refund is catastrophic. - 1-year history & downstream readers: Transcripts are retained for 1 year by default and read live by the human-agent console, quality review, analytics, and the AI agent's own context builder.
- Upstream degradation policy: Degraded upstream behavior includes elevated error rates, slow responses, malformed tool calls, and streams that cut off mid-sentence. Partial text may appear while streaming, but a broken reply is never left looking complete and is never saved to the permanent transcript—it is cleanly reset and regenerated (or replaced by a clear fallback).
Non-functional targets:
- Zero lost acknowledged messages: Once a customer bubble changes from "Sending…" to "Sent", that message survives any single server or disk failure.
- No duplicates, no missing messages, strict per-conversation order across all open tabs.
- Latency: "Sent" acknowledgement p99 < 300 ms; typing indicator < 200 ms after "Sent"; first streamed token p50 < 2 s (no tools) or < 3 s (one tool call), p95 < 5 s. Because the external LLM takes ~1 s per call to emit its first token, our internal hops must stay under ~200 ms total.
- Graceful availability: Even if the external LLM provider goes 100% down, customers can still send messages, search help articles, or join the human queue, and never wait > 10 s without an honest status update.
Back-of-the-envelope numbers
Scale ~2,000 business tenants; 2M conversations/day x 5 turns = 10M AI turns/day Turn rate 10,000,000 / 86,400 s ≈ 115 turns/s average; 3x peak ≈ 350 -> size for 400 turns/s LLM calls ~2 main calls/turn (1 tool-decision step + 1 final-answer step) = 800 main calls/s peak + ~0.5 lightweight parallel safety-classifier calls/turn = ~1,000 calls/s peak Token volume ~5,000 input tokens/main call (2k policy + 2k help docs + 1k chat history), ~200 output 800 main calls/s x 5,000 = 4M input tokens/s = ~240M input tokens/min at peak! Open sockets 10-min average chat: 2M x 10 / 1,440 min ≈ 14k average, ~42k peak, x 1.2 for extra open tabs/devices -> ~50,000 concurrent connections Live streaming 200 output tokens at ~50 tokens/s = ~4 s per reply 400 turns/s x 4 s = ~1,600 active streams; batched every 100 ms -> ~16k chunks/s DB writes ~5 durable rows/turn (customer msg, run start, tool journal, AI msg, run end) 400 turns/s x 5 = ~2,000 writes/s peak; ~25M rows/day x 1 KB ≈ 25 GB/day (~9 TB/yr) LLM traces ~20M main calls/day; store shared system prompts/docs once by content hash and keep only ~5 KB dynamic history + output per call -> ~100-125 GB/day (~3.5 TB for 30 days)Three crucial takeaways guide the whole architecture:
- Our own servers are modest: 50,000 open sockets fit comfortably on 6 small gateway VMs, and 2,000 writes/s fit on a single Postgres primary with a synchronous standby. Correctness under partial failures, not raw database scale, is the real challenge.
- External LLM token quota (~240M tokens/min) is the true bottleneck: Per-tenant rate limits, prompt-prefix caching, and a secondary LLM provider must be first-class components.
- The LLM dominates user-visible latency: Every internal hop we add must take milliseconds, not seconds.
Client protocol and identifier design
Compare the three browser/mobile transport options:
Transport How it works Verdict -------------- -------------------------------------------------------- -------------------------- Long polling Opens a brand-new HTTP request after every single event; Last-resort fallback only 16,000 token chunks/s would create massive HTTP overhead. SSE + POST Server-Sent Events (one-way HTTP stream from server to Automatic fallback if a client with built-in Last-Event-ID resume) + HTTP POSTs. corporate firewall blocks WS WebSocket One persistent two-way TCP connection carrying sends, Primary choice delivery acks, "stop generating", and live token chunks.We choose WebSockets (with SSE + HTTP POST fallback) because keeping customer sends, read acknowledgements,
"stop"clicks, and resume cursors ordered on a single connection simplifies client state.WebSocket frames (wss://chat.example.com/v1/ws) Client -> Server: {type: "hello", conversation_id, device_id, last_seq: 23, stream: {reply_id: "r_31", attempt: 1, last_chunk: 9}} // sent on connect & reconnect {type: "send", client_msg_id: "m_7b4", text: "Has shipment #804 gone out yet?"} {type: "ack", up_to_seq: 25} // confirms device rendered <= 25 {type: "stop", reply_id: "r_31"} Server -> Client: {type: "accepted", client_msg_id: "m_7b4", seq: 24} // committed to DB -> show "Sent" {type: "message", seq: 25, role: "customer"|"agent"|"human", client_msg_id?, reply_id?, text} {type: "reply_start", reply_id: "r_31", attempt: 1} {type: "reply_chunk", reply_id: "r_31", attempt: 1, chunk: 10, text: " arriving Thursday."} {type: "reply_reset", reply_id: "r_31", attempt: 2} // discard broken attempt 1 preview {type: "agent_status", state: "thinking"|"using_tool"|"degraded", note: "Checking shipment #804..."} HTTPS REST endpoints (initial load, gap backfill, and SSE fallback) POST /v1/conversations -> {conversation_id, auth_token} GET /v1/conversations/{id}/messages?after_seq=23 -> missed durable messages in seq orderThree identifiers carry the entire reliability design: -
client_msg_id: An idempotency key (a unique ID generated once on the customer's device when they hit Send and reused on every retry) so resending after a network drop saves the message once, never twice. -seq: A dense per-conversation integer (1, 2, 3, ...) assigned by the server. Because no number is ever skipped, a device holding23that receives25instantly knows24is missing! -(reply_id, attempt, chunk): Uniquely labels which reply is streaming, which retry generation (attempt = 1, 2) produced it, and the exact piece index (0, 1, 2, ...).Data model
At ~2,000 writes/s, a relational database (Postgres, sharded by
conversation_idonly if traffic grows 10x) lets simple ACID transactions andUNIQUEconstraints enforce our hardest invariants:conversations conversation_id PK, tenant_id, customer_ref, mode ('ai' | 'handoff_pending' | 'human' | 'closed'), next_seq INT, -- assigns gap-free 1, 2, 3... across all messages last_customer_seq INT -- tracks latest customer msg so mid-stream sends aren't missed messages PK (conversation_id, seq), role ('customer' | 'agent' | 'human' | 'system'), client_msg_id TEXT, reply_id TEXT, text TEXT, created_at TIMESTAMPTZ, UNIQUE (conversation_id, client_msg_id) -- deduplicates client retries! agent_runs run_id PK (doubles as reply_id), conversation_id, input_up_to_seq INT, status ('running' | 'completed' | 'failed' | 'superseded'), attempt INT, lease_owner TEXT, lease_expires_at TIMESTAMPTZ, fencing_token BIGINT, UNIQUE (conversation_id) WHERE status = 'running', -- at most 1 active AI run per chat UNIQUE (conversation_id, input_up_to_seq) -- redelivered Kafka event won't double-run tool_calls PK (run_id, step), tool_name, args_json, idempotency_key TEXT UNIQUE, status ('pending' | 'succeeded' | 'failed' | 'unknown'), result_json outbox outbox_id BIGSERIAL PK, conversation_id, payload_json, published BOOLEAN Redis (ephemeral, 10-min TTL) stream:{reply_id}:{attempt} -- recent chunks for reconnect catch-up Object storage (30-day TTL) llm_traces/{run_id}/{call_id} -- prompt/completion audit logsThree key patterns here, defined simply: - Transactional outbox: Writing an event row into
outboxinside the exact same database transaction that inserts a message, which a background relay (CDC, or change data capture, reading the DB write-ahead log) forwards to Kafka. That way the server can never commit a message to Postgres and crash before telling Kafka! - Lease: A time-bounded ownership claim (lease_expires_at = now + 10 s, renewed every 3 s) so if an AI worker crashes mid-reply, another worker detects the expired lease and takes over. - Fencing token: A monotonically increasing number (1, 2, 3...) incremented every time a lease changes hands; Postgres rejects any final write carrying an olderfencing_token, blocking a frozen "zombie" worker that wakes up late from overwriting the new worker's reply.High-level architecture and end-to-end happy path
Customer Browser / Mobile App [local outbox (IndexedDB/SQLite), last_seq, stream cursor] | WebSocket (or SSE + POST fallback) v Load Balancer ---> Stateless Connection Gateways (~6 VMs holding ~50k open sockets) | 1. RPC send ^ 5. SSUBSCRIBE live:{conversation_id} v | Conversation Service --(ACID tx)--> Postgres Primary (+ Sync Standby) | 2. CDC outbox relay v Kafka "conversation-events" (key = conversation_id, RF=3) +-------------------+--------------------+-------------------+ v v v v Agent Orchestrator Delivery Router Human Console Analytics / QA / (runs, leases) (pushes durable Service Tenant Webhooks | | | msgs to live:) ----+ | | +---> 4. Redis: XADD stream:{r}:{att} + SPUBLISH live:{conv} | +--------> Tool Service --(Idempotency-Key)--> Merchant APIs (shipments, refunds) v LLM Gateway (quotas, timeouts, retry budget, circuit breakers, hedging, failover) | | v v Provider A (Primary) Provider B (Secondary) / Fast Small ModelNow trace one single customer message—
"Has shipment #804 gone out yet?"—from click to screen:t = 0 ms Client generates client_msg_id = "m_7b4", saves it in local IndexedDB outbox, renders a grey "Sending..." bubble, and sends {type: "send", client_msg_id: "m_7b4", text} on WS. t = 30 ms Gateway G3 calls Conversation Service, which runs ONE Postgres transaction: SELECT next_seq FROM conversations WHERE conversation_id = $1 FOR UPDATE; -- returns 24 INSERT INTO messages (..., seq=24, role='customer', client_msg_id='m_7b4') ON CONFLICT (conversation_id, client_msg_id) DO NOTHING; IF inserted: UPDATE conversations SET next_seq = 25, last_customer_seq = 24; INSERT INTO outbox (conversation_id, event='customer_msg_24'); ELSE: -- duplicate retry! Do NOT bump next_seq (avoids gaps); fetch original seq. COMMIT; (waits for synchronous standby ack so committed = survives disk loss) t = 50 ms G3 sends {accepted, client_msg_id: "m_7b4", seq: 24} -> bubble flips to "Sent"; client deletes "m_7b4" from its local unsent outbox. t = 100 ms CDC relay publishes event to Kafka partition for conversation_id. t = 120 ms - Delivery Router publishes {message, seq: 24} to Redis `live:{conv}` so the user's second open browser tab immediately displays their question. - Agent Orchestrator inserts `agent_runs` (run_id="r_31", input_up_to_seq=24, attempt=1, fencing_token=1) and publishes {agent_status: "thinking"} -> typing dots appear! t = 180 ms Orchestrator loads cached tenant policy + last 20 messages + top help articles, and calls LLM Gateway -> Provider A with streaming enabled. t = 1.1 s Provider A emits tool call `get_shipment(804)`. Tool Service records `pending` in `tool_calls`, fetches shipment tracking (300 ms), records `succeeded` + JSON result, and updates status to "Checking shipment #804...". Orchestrator starts the second LLM call with the tool result. t = 2.4 s First answer token arrives! Every 100 ms, Orchestrator appends the batch to Redis Stream `stream:r_31:1` AND publishes `{reply_chunk, r_31, attempt: 1, chunk: n}` to `live:{conv}`. Gateway G3 pushes each chunk down the WebSocket; the customer watches the sentence grow. t = 6.0 s Stream completes. Orchestrator commits ONE Postgres transaction: UPDATE agent_runs SET status = 'completed' WHERE run_id = 'r_31' AND status = 'running' AND fencing_token = 1; -- If 0 rows updated, a newer worker superseded us -> ROLLBACK! INSERT INTO messages (..., seq=25, role='agent', reply_id='r_31', text=full_text); UPDATE conversations SET next_seq = 26 RETURNING last_customer_seq; INSERT INTO outbox (conversation_id, event='agent_msg_25'); -- If last_customer_seq > 24 (user sent another msg mid-stream), also enqueue next run! COMMIT; t = 6.1 s Delivery Router forwards `{message, seq: 25, reply_id: "r_31"}` to `live:{conv}`. Client replaces the temporary streaming preview with authoritative `seq = 25` and acks `25`.Deep dive 1: pub/sub decoupling and durable vs. ephemeral channels
Why we need two distinct pub/sub tiers (socket gateways vs. stateless workers): Customer
conv_88's WebSocket sits open on GatewayG3, while stateless Orchestrator WorkerW4generates the reply without knowingG3exists. Why not use Kafka for everything, or Redis for everything?- Kafka cannot route to individual sockets: A Kafka consumer subscribes to coarse partitions (e.g., 1 of 64 partitions), not a single
conversation_id. If 6 gateways used Kafka directly, every gateway would have to ingest 100% of all conversations just to filter out the ones connected to it! - Redis pub/sub is not durable: Classic pub/sub drops messages if a subscriber blips, which is unacceptable for billing, audit logs, or triggering an AI turn.
So we split traffic strictly by whether losing a packet is acceptable:
Channel Engine & Retention Durable? Purpose & Subscribers ---------------------------- -------------------------- -------- ------------------------------------------- conversation-events Kafka (key=conversation_id, YES Committed messages, handoffs, run triggers. RF=3, 7-day retention) Read independently by Orchestrator, Delivery Router, Human Console, Analytics, Webhooks. live:{conversation_id} Redis 7 Sharded Pub/Sub NO Live token chunks, typing status, + live push (SPUBLISH / SSUBSCRIBE) of committed messages to whichever gateways currently hold a socket for `conversation_id`. stream:{reply_id}:{attempt} Redis Stream (10-min TTL) 10 min Short replay buffer of chunks 0..N so a tab reconnecting mid-reply catches up smoothly.(Note: Redis 7 sharded pub/sub hashes
live:{conversation_id}to a single Redis Cluster shard instead of broadcasting every message to every Redis node, allowing horizontal scaling.)Delivery guarantees & the "Subscribe-Then-Read" rule: - Postgres -> Outbox -> Kafka -> Consumers is at-least-once, turned into effective exactly-once by
UNIQUEDB keys (client_msg_id,(conversation_id, input_up_to_seq)) and client deduplication onseq. - Redis -> Gateway -> Client is best-effort (at-most-once), repaired automatically by denseseqgap checks, reconnect catch-up, and an 8-second client idle timer ("AI says it is working, but 8 s passed with zero chunks -> pollGET /messages?after_seq=last_seq"). - Subscribe-then-read on connect: Whenever a gateway attaches a socket toconv_88, it must subscribe tolive:conv_88BEFORE querying Postgres and Redis Stream:WRONG (Read, then Subscribe): t1: Read DB (gets up to seq 24) t2: seq 25 commits & publishes to live:conv_88 <-- MISSED! Not in DB read, not subscribed yet! t3: Subscribe to live:conv_88 RIGHT (Subscribe, then Read): t1: SSUBSCRIBE live:conv_88 <-- buffered in gateway memory t2: seq 25 commits & publishes to live:conv_88 <-- caught by subscription! t3: Read DB (also returns seq 25) <-- client deduplicates seq 25 by ID. Zero gaps!- Kafka cannot route to individual sockets: A Kafka consumer subscribes to coarse partitions (e.g., 1 of 64 partitions), not a single
Deep dive 2: handling degraded or failing upstream LLM calls
Core error classification rule: separate every fault by (1) can a retry succeed? and (2) could attempt 1 already have mutated external state?
Failure mode Retry helps? Side effect? Action ---------------------------------------- ------------ ------------------ ----------------------------------------- TCP/TLS error or HTTP 5xx before token 1 Yes No Gateway retries with jitter, then Provider B HTTP 429 (rate limit) After wait No Respect Retry-After or shift immediately to B Slow time-to-first-token (> 3 s) Often No (only tokens) Hedged request: start Provider B in parallel, keep whichever emits token 1 first, cancel loser Stream stalls (> 5 s gap) or drops at #9 Yes Partial UI preview Orchestrator starts attempt 2, sends reply_reset HTTP 400 context length exceeded Not unchanged No Trim/summarize history, retry once HTTP 400 bad schema / 401 bad API key No No Fail fast, alert on-call, drop to fallback Malformed tool JSON Once No Re-prompt once with parser error message Safety filter block No No Send safe canned response + offer human agent Tool call (`process_refund`) timed out DANGEROUS! Money may have moved NEVER blind-retry; reconcile via idempotency keyPreventing retry storms (3 anti-overload guardrails): 1. Never stack retries across layers: If the mobile app retried 3x, the Orchestrator retried 3x, and the LLM Gateway retried 3x, one user message during a brownout would trigger
3 x 3 x 3 = 27LLM calls! Instead: - Client retries onlysenduntilaccepted(never LLM generation). - LLM Gateway retries at most 2 times before token 1, using exponential backoff with full jitter (sleep = random(0, min(2 s, 0.25 s * 2^attempt))—randomizing wait times so thousands of stalled requests don't wake up in lockstep). - Orchestrator retries at most 1 regeneration attempt (attempt = 2) if a stream dies mid-sentence. 2. 10% retry budget & circuit breakers: A token bucket caps total retries at <= 10% of normal traffic; once empty, errors fail over immediately without retrying. Per(provider, model)circuit breakers (automatic switches that trip "open" when >= 50% of the last 20+ calls in 30 s fail) route calls straight to Provider B, letting 5% probe requests test recovery after 30 s. 3. Streaming-specific timeouts: A single 60-second HTTP timeout is useless for streaming. Enforce separate budgets: 1 s TCP connect, 3 s soft first-token timeout (triggers a hedged request—a parallel backup call to Provider B capped at <= 5% of traffic), 8 s hard first-token timeout, 5 s max silence between chunks, and 30 s total turn deadline.Recovering a half-streamed reply cleanly: Suppose the customer sees
"Shipment #804 left our hub Tuesday and is..."and Provider A drops the connection: - Resuming mid-sentence on Provider B is fragile (different phrasing, or no support for prefilled assistant prefixes). Buffering the entire reply before showing anything would ruin normal latency (~6 s wait). - Instead, Orchestrator incrementsattempt = 2, replays any already-completedtool_callsfrom the Postgres journal without calling the merchant API again, and publishes{reply_reset, reply_id: "r_31", attempt: 2}. The UI dims the unfinished sentence ("Reconnecting to assistant…"), replaces it cleanly asattempt: 2streams in, and ignores any late-arrivingattempt: 1chunks.4-level graceful degradation ladder: - Level 0: Primary model on Provider A. - Level 1: Equivalent model on Provider B (tested continuously on 5% canary traffic). - Level 2: Smaller, faster model with shorter context window; complex tool requests hand off to humans. - Level 3 (total LLM outage): Instant friendly message + keyword-matched help-center articles + "Join human support queue" or "Leave your question for email follow-up."
Deep dive 3: network drops and client/server resume
When a customer rides into a subway tunnel, both sides track an explicit cursor and reconcile on reconnect:
What the Client remembers locally What the Server remembers durably ------------------------------------------------- ------------------------------------------------- - last_seq rendered on screen (e.g., 23) - Every committed message & dense seq (Postgres) - Unacknowledged sends in local outbox ("m_7b4") - Every seen client_msg_id -> original seq - Active preview cursor: (r_31, attempt=1, #9) - Active agent_run + chunks 0..N in Redis StreamDetecting dead connections & reconnecting safely: Mobile NATs often drop idle sockets silently without a TCP
FIN. The client sends apingevery 20 s and treats missingpongafter 10 s (or OSonline/ app-foreground events) as a disconnect, reconnecting to any stateless gateway with full-jitter backoff (0.5 sup to30 s) so 8,000 users from a crashed gateway don't stampede at once.The 6-step resume handshake (zero duplicates, zero gaps):
1. Client -> Gateway G6: {hello, conv_id, last_seq: 23, stream: {r_31, attempt: 1, last_chunk: 9}} 2. G6 runs SSUBSCRIBE live:{conv_id} FIRST (so no new event slips through the crack). 3. G6 fetches Postgres messages with seq > 23 and sends them in order. 4. G6 checks active stream state for conv_id: - Same attempt 1 still running -> reads chunks > 9 from Redis Stream `stream:r_31:1`, then live! - Moved to attempt 2 -> sends `reply_reset(attempt: 2)` + chunks 0..k of attempt 2! - Run already finished -> `seq = 25` arrived in Step 3; client swaps preview for seq 25! 5. Client resends any message still sitting in its local unsent outbox (same `client_msg_id: "m_7b4"`). 6. Conversation Service hits `ON CONFLICT (conversation_id, client_msg_id) DO NOTHING`, looks up the already-assigned `seq = 24`, and returns `{accepted, "m_7b4", seq: 24}` without creating a second row!Meanwhile, server-side LLM work never aborts when a client disconnects:
r_31finishes normally and commitsseq = 25to Postgres so the answer is waiting instantly when the customer emerges from the tunnel (or can be emailed if they stay offline for 15 minutes).Scaling, infrastructure crashes, and summary of trade-offs
Handling server crashes inside our own stack:
Component crash Impact & automatic recovery ---------------------------- ------------------------------------------------------------------------- Gateway VM dies ~8k WebSockets drop; clients jitter-reconnect to surviving gateways and run the `hello` handshake. Zero lost state (gateways are 100% stateless). Orchestrator worker dies Its active runs stop renewing their 10 s lease. Within <= 10 s, another worker claims the run with `attempt + 1` and `fencing_token + 1`, sends `reply_reset`, and replays `tool_calls` from Postgres without re-running tools. Zombie worker (GC freeze) Wakes up after lease loss: its chunks carry old `attempt` (ignored by UI) and its Postgres commit fails `WHERE fencing_token = current_token`. Redis shard fails over ~15 s pause in live chunks for affected chats; client's 8 s idle timer polls Postgres for completed messages until replica promotion finishes. Kafka cluster blip Customer sends still commit to Postgres + `outbox` and show "Sent"; CDC relay drains the `outbox` backlog in order once Kafka recovers. Postgres primary crash Synchronous standby promotes in ~15-30 s with zero lost `accepted` rows; during failover, client messages stay in local outbox ("Sending...") & retry.Summary of key trade-offs:
- WebSocket primary + SSE/POST fallback: Single ordered pipe for bidirectional acks/stops, while gracefully traversing strict corporate proxies via SSE.
- Postgres + transactional outbox vs. Kafka-first writes: At 2,000 writes/s, Postgres gives trivial
client_msg_iddeduplication, gap-freeseqnumbering, and single-active-run locks for ~50–100 ms of CDC lag (invisible beside a 1,000 ms LLM call). - Kafka (durable events) + Redis sharded pub/sub (ephemeral chunks): Every critical event is replicated and replayable for analytics/consoles, while 16,000 chunks/s route only to the specific gateways holding open sockets.
- Stream immediately +
reply_reseton mid-stream error: Delivers ~2 s perceived responsiveness on 99%+ of turns at the cost of a visible reset on the < 1% of streams that sever mid-sentence. - Single-layer retries + 10% budget + journaled tool idempotency: Protects struggling LLM providers from 27x retry amplification and guarantees side-effecting tools like refunds never execute twice.
Intuition & how it works
Think of this system like a well-run café counter connected to an unpredictable external kitchen. The moment you hand over your order, the cashier writes it into a permanent ledger with a gap-free receipt number (seq = 24) before telling you "Received." Waiters (stateless WebSocket gateways) only carry plates to tables and can swap shifts anytime; live dish-prep updates are announced over a table-specific speaker (live:{conversation_id} in Redis); every bank card refund is written into a logbook before touching the payment terminal; and if the external chef (the LLM provider) drops a plate halfway through, a backup chef remakes the dish cleanly using the already-logged shipment lookup instead of charging or querying your account twice.
A naive architecture—holding chat state in memory on one WebSocket server that directly streams from an LLM HTTP call—breaks at every seam in production. If the user's phone switches from Wi-Fi to cellular mid-reply, the server drops the stream and throws away the LLM work; if the user taps Retry after a lost acknowledgement, the server saves a duplicate question and triggers two overlapping AI replies (or issues two refunds!); and if the LLM provider slows down, uncoordinated retries across client, worker, and gateway multiply traffic (3 x 3 x 3 = 27x) until quotas collapse. Decoupling connection gateways from durable agent_runs via a transactional outbox (saving each message and its "to-publish" Kafka event in one atomic Postgres transaction) plus three strict identifiers—client_msg_id, dense seq, and (reply_id, attempt, chunk)—keeps every failure recoverable.
Trace a concrete 4-step example where a shopper sends "Has shipment #804 gone out yet?" (client_msg_id = "m_7b4"), loses Wi-Fi at chunk 9 of the reply, and reconnects 4 seconds later:
1. Durable send: Gateway G3 commits "m_7b4" to Postgres as seq = 24 alongside an outbox row and returns {accepted, "m_7b4", seq: 24}, but suppose that ack packet drops just as the user enters an elevator—and meanwhile Worker W4 starts run r_31 (attempt = 1), journals get_shipment(804) in tool_calls, and streams chunks 0..9 to Redis.
2. Work continues offline: Even though G3's socket died, W4 is completely decoupled from the socket—it finishes streaming and commits the full AI answer to Postgres as seq = 25.
3. Subscribe-then-read reconnect: Four seconds later, the phone connects to a different gateway G6 and sends {hello, last_seq: 23, stream: {r_31, attempt: 1, last_chunk: 9}} plus a cautious resend of "m_7b4".
4. Clean convergence: G6 subscribes to live:{conv} first, reads Postgres rows seq > 23 (returning both seq = 24 and completed seq = 25), swaps the unfinished chunk-9 preview bubble for authoritative seq = 25, and hits ON CONFLICT DO NOTHING on "m_7b4" so it re-acknowledges seq = 24 with zero duplicates and zero gaps.
Key trade-offs
- WebSockets vs. Server-Sent Events (SSE) + HTTP POST. SSE (a standard one-way HTTP text stream from server to browser) traverses strict corporate proxies easily, whereas a WebSocket (a persistent two-way TCP channel) keeps customer sends, delivery acks,
"stop"signals, and stream cursors ordered on a single connection. Using WebSockets first with automatic fallback to SSE + POST gives the cleanest ordering without stranding firewall-restricted users. - Postgres + transactional outbox vs. writing directly to Kafka. At ~2,000 durable writes/s, committing to Postgres first lets simple
UNIQUEconstraints enforceclient_msg_iddeduplication, gap-freeseqcounters, and one active AI run per chat, paying only ~50–100 ms of CDC (change data capture—tailing the database log into Kafka) latency before an AI worker starts—negligible next to a ~1,000 ms LLM first-token delay. - Dual pub/sub (Kafka + Redis sharded pub/sub) vs. a single bus or session registry. Kafka stores durable events (
seqmessages, handoffs) with 7-day replay for independent consumers (analytics, QA, human agent consoles), while Redis sharded pub/sub (routinglive:{conversation_id}to a single Redis Cluster hash slot) lets each gateway subscribe only to the ~8,000 chats connected to it without maintaining a fragile "user -> gateway IP" lookup table. Because Redis pub/sub is fire-and-forget, denseseqnumbers, reconnect handshakes, and an 8-second idle poll repair any dropped packet. - Streaming immediately +
reply_resetvs. buffering full replies. Streaming gives a ~2 s time-to-first-token instead of waiting ~6 s for the entire completion, at the cost of sendingreply_resetto replace partial text on the rare (< 1%) turns where a stream breaks mid-sentence. Regeneratingattempt = 2from scratch works identically across different LLM providers, unlike prefilling half an assistant sentence. - Single-layer bounded retries + hedging vs. aggressive retries everywhere. Restricting call retries to the LLM Gateway (<= 2 retries with full jitter, meaning randomized exponential wait times, capped by a 10% retry budget) and <= 1 mid-stream regeneration in the Orchestrator prevents retry storms, while firing a hedged request (a parallel backup request to Provider B when Provider A emits no token after 3 s, capped at <= 5% of calls) trims p99 tail latency for minimal extra token spend.
- Multi-provider setup vs. single external LLM. Maintaining a secondary provider turns a full provider outage into seamless failover, at the ongoing engineering cost of prompt regression testing, tool-schema parity, and holding token quota on two vendors.
Common mistakes
- Running the LLM call inside the WebSocket gateway handler, so any mobile Wi-Fi blip aborts the in-flight LLM generation and wastes tokens.
- Showing "Sent" before Postgres commits (or deleting the message from the device's local outbox before
{accepted}returns), silently losing customer messages during crashes. - Omitting a client-generated
client_msg_id, causing every client retry after a lost acknowledgement to insert a duplicate customer message, bumpnext_seqtwice, and launch two AI responses. - Trying to push per-socket live tokens straight from Kafka, overlooking that Kafka partitions cannot filter down to the ~8,000 specific conversations held by one gateway VM.
- Reading Postgres history before subscribing to
live:{conversation_id}on reconnect, leaving a millisecond race window where a newly committed reply is missed by both the query and the live subscription. - Using a single 60-second HTTP timeout on streaming LLM calls instead of separate connect (1 s), first-token (3 s hedge / 8 s abort), and inter-chunk stall (5 s) timeouts, leaving users staring at frozen half-sentences for a full minute.
- Blindly retrying timed-out side-effecting tool calls (like
process_refund) instead of journaling an idempotency key before calling the downstream API. - Saving half-streamed broken text into the
messagestable, polluting both the customer transcript and the AI's context window on future turns.
Follow-up questions
- How should the platform behave—and what should end users see—during a prolonged, total outage of the external model vendor? Within seconds at ~1,000 calls/s, our per-model circuit breakers (automatic failure switches that trip open once >= 50% of recent calls fail or time out) open on Provider A and route 100% of traffic to Provider B, which stays warm via a continuous 5% live canary so customers see normal AI answers. If Provider B is also down or hits its token quota ceiling, the degradation ladder drops cleanly to Level 3 within a couple of seconds: customers can still send durable messages, immediately see keyword-matched help-center articles, click "Talk to a human support agent" (with live queue wait estimates), or leave their question for email follow-up. Meanwhile, unanswered AI threads are tagged in Postgres, and once periodic 5% breaker probes confirm the vendor has recovered, a rate-limited drainer answers still-connected chats first and emails offline customers who were not already resolved by a human.
- What happens when a user submits three rapid back-to-back messages while the assistant is still generating its reply to the first one? First, adding a short ~800 ms–1 s debounce before launching a run naturally coalesces rapid-fire bursts from fast typists into a single prompt. If Run 1 (
input_up_to_seq = 24) is already running when messages25and26commit (updatingconversations.last_customer_seq = 26), behavior depends on whether the customer has seen text yet: if Run 1 has not streamed any visible reply tokens yet, the Orchestrator cancels Run 1's LLM stream, marks Run 1superseded(keeping any completedtool_callsin the journal for reuse!), and starts Run 2 coveringinput_up_to_seq = 26so one coherent answer addresses all three messages. If Run 1 is already streaming text on screen, we let Run 1 finish cleanly, and when its commit transaction seeslast_customer_seq (26) > input_up_to_seq (24), it immediately triggers a single follow-up run covering both25and26together rather than firing two separate runs. - Suppose the assistant has a tool that triggers monetary refunds—how do you guarantee a timed-out call and subsequent retry never refund the customer twice? Before calling the payment service, the Tool Service computes a deterministic idempotency key naming the business intent rather than the network attempt—such as
sha256(tenant_id, conversation_id, "refund", shipment_or_order_id, amount_cents)—and commits a row intool_callswithstatus = 'pending'. It passes that exact key in theIdempotency-Keyheader to the merchant's payment API so any duplicate HTTP call returns the original receipt instead of moving money twice. If the HTTP call times out, we mark the rowunknown(never blindly generating a fresh refund call!) and run a status-lookup reconciliation byorder_idoridempotency_key, while also enforcing hard guardrails in the Tool Service (at most one refund per order, and human approval required above a dollar threshold). - How would you validate all of these server, upstream, and network recovery paths before exposing the system to live customer traffic? Build a deterministic fault-injecting mock LLM provider behind the LLM Gateway in CI and staging that simulates HTTP 429/503 bursts, 6-second first-token hangs, mid-stream disconnects at chunk
K, and malformed tool JSON, while automated assertions verify core invariants: zero duplicate or missingseqnumbers across simulated multi-tab clients, zero runs stuckrunningpast the 30 s deadline, and zero duplicate executions on the mock refund API. Pair this with client chaos tests using a network proxy (like Toxiproxy) injecting 30% packet loss and Wi-Fi-to-cellular drops, plus staging game days that kill gateway VMs, Orchestrator workers mid-lease, and Redis shards under load to verifyfencing_tokenprotection and the 10% retry budget before launch.
Follow-up questions
- How should the platform behave—and what should end users see—during a prolonged, total outage of the external model vendor?
- What happens when a user submits three rapid back-to-back messages while the assistant is still generating its reply to the first one?
- Suppose the assistant has a tool that triggers monetary refunds—how do you guarantee a timed-out call and subsequent retry never refund the customer twice?
- How would you validate all of these server, upstream, and network recovery paths before exposing the system to live customer traffic?
Similar questions
- Paginated Chat Transcript Loading and Token-Budget Eviction
- Paginated Record Collection and Token-Budget Compaction
- Paginated Conversation Loader with Suffix Token Trimming
- Drain Paginated Logs and Compact to a Byte Limit
- Header-Preserving Markdown Chunker
- Global Live Video Streaming Platform