Home / AI Architecture & System Design / AI System Design
Design a customer-support chatbot that answers from a company knowledge base.
30-second answer
Clarify scale, latency, languages and escalation requirements. Metrics: resolution/deflection rate, groundedness, CSAT, p95 latency, cost per conversation. Architecture: ingestion pipeline (parse, chunk by section, embed, index with metadata), orchestrator with input guardrails, hybrid retrieval + rerank, an LLM prompted to answer only from cited context and hand off when unsure, output checks, streaming. Deep dives: evals (golden set with unanswerable cases), human handoff, freshness of docs, caching common questions, and monitoring with feedback loops.
Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.
New to these terms? 28 terms on this page are explained in the glossary
0–5 min Functional requirements
Support bots range from an FAQ widget to an agent that issues refunds, and those are very different systems. Pin down the product before drawing anything.
You Who uses it, and where? Logged-in customers, anonymous visitors, or both?
Interviewer Both. Most are logged in on the website and mobile app; some anonymous visitors use it from the help center.
You Should it only answer questions, or also take actions like refunds and address changes?
Interviewer Answers only at launch. Actions are likely in phase two, so don't paint yourself into a corner.
You What does it answer from? Help-center articles only, or account data like order status too?
Interviewer About 20,000 help-center articles, updated daily. Order status would be nice if it's cheap to add.
You When it can't help, what happens today?
Interviewer Customers open a ticket or start a live chat with an agent.
You Which languages?
Interviewer English, Spanish, French and German.
| # | Functional requirement | Why it matters |
|---|---|---|
| F1 | Answer questions grounded in help-center articles, with links to the sources | Customers can verify answers; the bot can't invent policy |
| F2 | Handle multi-turn conversations ("what about annual plans?") | Real conversations are rarely one question |
| F3 | Answer account questions such as order status for logged-in users, through read-only tools | High-volume questions that articles can't answer |
| F4 | Hand off to a human with a summary when it can't help, when asked, or for sensitive topics | Wrong answers cost more than escalations |
| F5 | Support four languages and reply in the customer's language | Stated requirement |
| F6 | Collect feedback and log conversations for review and evaluation | Needed to measure and improve |
| F7 | Admin controls: in-scope topics, canned responses for sensitive intents, a kill switch | Support leaders need control without engineering |
Out of scope for now: taking actions (refunds, cancellations), voice, and tools for human agents. Mention them as extensions.
5–10 min Non-functional requirements and estimates
You What does success look like for the business?
Interviewer Deflection: conversations resolved without an agent, without hurting customer satisfaction.
You How bad is a wrong answer?
Interviewer Bad. A wrong refund-policy answer turns into a complaint or a chargeback.
You Then I'll prefer handing off over guessing, and measure deflection and the wrong-answer rate together. Optimizing deflection alone would reward a bot that answers confidently and wrongly.
| Requirement | Target | What it forces in the design |
|---|---|---|
| Latency | First text ≤ 1.5 s at p95, streamed; full answer ≤ 6 s | Streaming, small models for routing, parallel steps |
| Answer quality | ≥ 95% grounded on the evaluation set; ≤ 2% wrong answers in weekly audits | Retrieval quality, citations, a groundedness check for policy questions |
| Handoff | Escalates when it should ≥ 90% on labelled cases | Explicit handoff signals, not just model judgement |
| Availability | 99.9%; degrade to article search when the LLM is down | A non-LLM fallback path |
| Freshness | Article edits live within 15 minutes | Webhook-driven indexing |
| Privacy | Account data only for the signed-in user; PII redacted in logs | Tools scoped by identity; redaction before logging |
| Cost | ≤ ~$0.03 per conversation (illustrative) | Routing, prompt caching, history summarization |
Back-of-envelope estimates. Prices here are illustrative; the point is the shape of the cost.
- Traffic: 200,000 conversations/day × 5 turns = 1M turns/day. That's ~12 turns/s on average and ~40/s at peak (3×).
- Prompt size per turn: system prompt and tool definitions ~1,500 tokens, conversation history ~1,000, four retrieved chunks ~1,600, the question ~50: about 4,200 input tokens, plus ~200 output tokens.
- Naive cost: 4.2B input + 0.2B output tokens/day. At $3 per million input and $15 per million output tokens for a large model, that's ~$12.6k + $3k ≈ $15.6k/day, about $0.08 per conversation: well over budget.
- With prompt caching of the 1,500-token static prefix (cached reads at ~10% of the price), input drops to ~$8.6k/day. Routing 60% of turns to a model ~10× cheaper brings the total to roughly $5.3k/day, ~$0.027 per conversation. Caching and routing are requirements, not optimizations.
- Index size: 20,000 articles × ~1,500 tokens ≈ 30M tokens per language, ~75,000 chunks, so ~300,000 chunks across four languages. At 1,024 dimensions × 4 bytes that's ~1.2 GB of vectors: small. Any vector store, including Postgres with pgvector, is fine.
10–18 min High-level design
You I'll split it into an online path that answers each turn and an offline path that keeps the knowledge base fresh. The online path puts a cheap router first, so simple and sensitive conversations never reach the expensive model.
Interviewer Go ahead.
Scroll sideways to see the whole diagram.
Components:
- Chat widget: web and mobile clients; renders streamed text, source links and the handoff button.
- API gateway: authentication, rate limits, conversation IDs.
- Orchestrator: runs the per-turn pipeline and owns conversation state.
- Input guardrails: PII detection, prompt-injection and abuse classifiers.
- Intent router: a small model that classifies the turn (FAQ, account question, complaint, sensitive, out of scope) and estimates difficulty.
- Retrieval: query rewrite, hybrid search filtered by locale and product, and a reranker.
- Answer LLM: generates a grounded, cited answer, streaming tokens.
- Output guardrails: policy and tone checks, plus a groundedness check for policy questions.
- Conversation store: messages, summaries, feedback.
- Human handoff: creates a ticket with a summary in the existing support tool.
- Offline ingestion: CMS webhooks → parse → chunk → embed → index.
One turn, step by step:
Scroll sideways to see the whole diagram.
- The widget sends the message; the gateway authenticates and attaches the conversation ID.
- The orchestrator loads recent history and the running summary.
- Input guardrails run; the router classifies intent. Sensitive intents (legal threats, account takeover, self-harm) get a scripted response and an immediate handoff offer.
- In parallel, a small model rewrites the question into a standalone query using the history.
- Retrieval returns the top four chunks. If the best reranker score is below a threshold, the bot says it doesn't have that information and offers a human.
- The answer model streams a response with citations; output guardrails check it.
- The turn, sources, model versions and latency are logged; the customer can rate it.
API sketch:
POST /v1/conversations → { conversation_id }
POST /v1/conversations/{id}/messages { text, locale }
→ SSE stream: delta | sources | handoff_offer | done
POST /v1/conversations/{id}/feedback { message_id, rating, resolved }
POST /v1/conversations/{id}/handoff → { ticket_id, queue_position }
Data model: conversations(id, user_id?, locale, status, summary), messages(id, conversation_id, role, text, sources[], model, prompt_version, latency_ms, tokens), feedback(message_id, rating, resolved).
How it works: a worked example
A study aid rather than something to recite: it traces one real turn through the running system, with the actual payloads, so you can picture what each box does.
The scenario. Maria, a logged-in customer on the Pro plan, has been chatting for two turns about her subscription. She types: "what about annual plans? can I still get my money back?"
1. The widget sends the turn.
POST /v1/conversations/c_8f21/messages
Authorization: Bearer <session token>
{ "text": "what about annual plans? can I still get my money back?", "locale": "en" }
The gateway validates the session, attaches user_id=u_5521, plan=pro, checks her rate limit, and opens a Server-Sent Events stream back to the browser.
2. The orchestrator loads state from Postgres: the last 6 messages and a running summary ("Customer on Pro monthly asked how to cancel; told cancellation is in Settings → Billing.").
3. Three small calls run in parallel (~60–250 ms in total):
// input guardrails
{ "pii": [], "injection_score": 0.02, "abuse": false }
// intent router (small model)
{ "intent": "billing_policy", "sensitive": false, "needs_account_data": false }
// query rewrite (small model, uses the history)
{ "query": "refund policy for annual subscription plans after purchase" }
4. Retrieval. Hybrid search on the English index, filtered by product=subscriptions, status=published, returns 50 candidates; the reranker keeps 4. The best one:
{ "chunk_id": "kb-1182#3", "title_path": "Billing > Refunds > Annual plans",
"text": "Annual plans can be refunded in full within 30 days of purchase. After 30 days, ...",
"url": "https://help.example.com/a/1182", "rerank_score": 0.91 }
0.91 is above the 0.5 "don't know" threshold, so the bot answers.
5. The prompt the answer model actually sees (~4,200 tokens; the first block is identical on every request, so it's served from the provider's prompt cache):
[system] You are Acme's support assistant. Answer ONLY from the documents below.
Cite every policy statement as [doc:ID]. If the documents don't answer,
say so and offer a human. Reply in the customer's language. Be brief.
[summary] Customer on Pro monthly asked how to cancel...
[history] user: how do I cancel? / assistant: In Settings → Billing ... [doc:kb-1043#1]
[docs] <doc id="kb-1182#3"> Annual plans can be refunded in full within 30 days... </doc>
<doc id="kb-1182#1"> ... </doc> (4 docs)
[user] what about annual plans? can I still get my money back?
6. Streaming back. First text appears after ~1 s. The browser receives:
event: delta data: {"text": "Yes, if you're within 30 days of buying the annual plan, "}
event: delta data: {"text": "you can get a full refund [doc:kb-1182#3]. After 30 days..."}
event: sources data: [{"id": "kb-1182#3", "title": "Refunds on annual plans", "url": "..."}]
event: done data: {"message_id": "m_771", "handoff_offer": false}
7. Output check. Because the intent is billing_policy, a groundedness check confirms "full refund within 30 days" is supported by kb-1182#3 (~300 ms, run as the text streams). Had it failed, the widget would have replaced the text with links to the articles.
8. Logging (async). One trace record goes to the log pipeline: route large, 4,180 input tokens (1,500 cached), 96 output tokens, TTFT 940 ms, cost ≈ $0.01, prompt version support-v14, chunk IDs. PII is redacted before it's stored.
Where each piece runs:
| Component | Runs as | Example technology | Sizing for 40 turns/s at peak | If it fails |
|---|---|---|---|---|
| Gateway | Managed API gateway + auth service | Envoy, cloud API gateway | ~200 concurrent streams at peak (40/s × ~5 s each) | Return 503; widget shows "search help articles" |
| Orchestrator | Stateless async service, autoscaled | Python/FastAPI or C#/ASP.NET | 3–6 pods; it mostly waits on I/O | Pods are interchangeable; a retry goes to another pod |
| Guardrails + router + rewrite | Small hosted model or self-hosted classifier | Small LLM API, fine-tuned BERT-class classifier | ~120 small calls/s | Skip rewrite; route to large model; fail closed on abuse check |
| Search | Managed search with vectors | OpenSearch/Elasticsearch or Postgres + pgvector | 300k chunks: one small cluster | Fall back to keyword-only search |
| Reranker | Hosted or one GPU replica | Cross-encoder | 40 × 50 pairs/s | Skip reranking; use top 4 by fused score |
| Answer model | Provider API via model gateway | Large + small models | ~10M input tokens/min at peak (40 turns/s × 4,200 tokens), ~4M of them on the large model | Fail over to second provider, then to "here are the relevant articles" |
| Conversation store | Postgres | — | 1M messages/day; partition by month | Read replica; degrade to no history |
| Ingestion | Queue + workers | CMS webhook → SQS/Kafka → workers | ~2,000 article edits/day | Dead-letter queue; alert; index stays on last good version |
| Handoff | Integration with ticketing tool | Zendesk/Salesforce API | Hundreds of tickets/hour | Queue the ticket and show the support email |
18–32 min Deep dive
You I'd go deeper on three things: retrieval quality, how it decides to answer or hand off, and cost and latency. Which first?
Interviewer Retrieval. How do you make sure it finds the right article?
Deep dive 1 · Retrieval quality
- Chunking: split articles by heading, ~300–500 tokens, and prefix every chunk with
Article title > Section. Keep tables whole. Index each language separately so Spanish questions retrieve Spanish articles. - Query rewriting: follow-ups are often unsearchable on their own. "What about annual plans?" becomes "Can I get a refund on an annual plan?" A small model does this in ~200 ms, in parallel with the router.
- Hybrid search: BM25 catches product names, plan names and error codes; vectors catch paraphrases ("money back" vs. "refund"). Merge with Reciprocal Rank Fusion.
- Filters: locale, product, plan and published status. A customer on the Basic plan shouldn't get the Enterprise answer.
- Reranking: a cross-encoder reranks the top 50 down to 4. Its top score doubles as a confidence signal.
- Freshness: CMS publish and unpublish webhooks re-index an article within minutes. Unpublishing deletes its chunks immediately, so retired policies stop appearing.
- Measurement: recall@4 on the golden set, broken down by intent. If billing questions have poor recall, fix that slice instead of tuning globally.
Interviewer Fine. How do you stop it confidently inventing a refund policy?
Deep dive 2 · Answer policy and handoff
Grounding. The prompt requires answers only from the provided articles, with a citation for every policy statement, and allows "I don't have that information." For policy intents (refunds, billing, cancellations), a groundedness check compares each claim with the cited text. If a claim isn't supported, the bot shows the relevant article links instead of its own wording.
Deciding to hand off. Don't leave this to the model alone; combine explicit signals:
Scroll sideways to see the whole diagram.
- The customer asks for a human.
- The intent is sensitive: legal threats, chargebacks, account security, or self-harm (show crisis resources too).
- Retrieval confidence is low.
- The conversation is going badly: two thumbs-down, repeated rephrasing, or increasingly negative sentiment.
The handoff creates a ticket with an AI-written summary, the transcript, the articles shown and the detected intent, routed to the right queue for language and topic. The customer shouldn't have to repeat themselves.
Tone. A short style guide in the system prompt plus a few example answers keeps the brand voice consistent. Avoid long apologies and filler; customers want the answer.
Interviewer Your estimate said cost is a problem. Walk me through latency and cost together.
Deep dive 3 · Cost and latency
Latency budget for the first visible text:
Scroll sideways to see the whole diagram.
The router and the query rewrite are independent, so they run in parallel. Retrieval and reranking take ~200 ms together, and the answer model's time to first token dominates. That puts first text around 1 s, inside the 1.5 s target with room for variance.
Cost levers, in order of impact:
- Routing: the router sends simple FAQ-style turns (~60%) to a small model and multi-step or ambiguous ones to the large model. Measure quality per route on the golden set.
- Prompt caching: keep the system prompt and tool definitions byte-identical at the start of every request so the provider can cache them.
- History summarization: after six turns, replace older turns with a running summary that keeps order numbers, plan names and decisions.
- Exact-match answer cache: for the most common questions, keyed by normalized question, locale, product and article versions. It's invalidated whenever a source article changes. A semantic cache is riskier here, because "cancel my order" and "don't cancel my order" are close in embedding space.
Deep dive 4 · Evaluation and launch (if time allows)
- Golden set: 300 real past conversations, each labelled with the correct article, a reference answer and whether it should hand off. Include unanswerable and multi-language cases.
- Offline gates in CI: recall@4, groundedness, handoff precision and recall, per locale.
- Launch in stages: first, the bot drafts answers for human agents to review (shadow mode). Then 5% of English traffic, then ramp by locale.
- Online metrics: resolution rate, CSAT, escalation rate, and a weekly human audit of ~200 sampled conversations to measure the wrong-answer rate honestly. Count a conversation as resolved only if the customer doesn't contact support again within 48 hours.
32–37 min Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Knowledge source | RAG over articles | Fine-tune on articles | Fresh within minutes, citable, no retraining; fine-tuning is weak at facts |
| Models | Router with small and large models | One large model for everything | ~3× cheaper; quality checked per route |
| Handoff | Conservative, signal-based | Let the model decide | Wrong answers cost more than escalations; signals are testable |
| Answer caching | Exact match, invalidated on article change | Semantic cache | Higher hit rate isn't worth wrong answers to similar-looking questions |
| Groundedness check | Policy intents only | Every answer | Adds ~300 ms; spend it where errors are expensive |
| Languages | Separate index per locale | Translate everything to English | Better retrieval and tone; costs 4× indexing, which is small here |
| Actions | Read-only at launch | Tools from day one | Ship value safely; add actions with confirmation later |
Build first: English-only RAG answers with citations, handoff to a ticket, and the golden set. Then routing and caching for cost, then the other locales, then order-status tools.
37–40 min Wrap-up and likely follow-ups
Close with: "A streaming chatbot where a small router handles intent and sensitivity, hybrid retrieval with reranking finds articles per locale, and a grounded answer model cites them. It hands off to humans on clear signals with a summary. Caching and routing keep cost near three cents a conversation, and a golden set plus weekly audits keep it honest."
Likely follow-ups:
- How would you add refunds? Tool calls scoped to the signed-in customer, refund rules enforced in code rather than the prompt, explicit confirmation showing the amount, idempotency keys and per-customer limits, plus an audit log.
- What if the knowledge base doesn't cover a question? Log unanswered and handed-off questions, cluster them weekly and send the top clusters to the content team as article requests.
- Can customers or articles inject instructions? Treat retrieved text as data in delimited blocks; the bot has no tools with side effects at launch, which limits the damage.
- How do you measure deflection honestly? Count a conversation as resolved only if there's no ticket or chat from that customer within 48 hours, and audit a sample by hand.
What interviewers listen for
- Clarifying actions vs. answers, languages and handoff before designing.
- Cost estimated from tokens, and design choices (routing, caching) that follow from it.
- Retrieval details: rewriting, hybrid search, filters, freshness.
- Handoff as a designed feature, not an afterthought.
- Measuring wrong answers alongside deflection.
Red flags
- "Put the knowledge base in the prompt" or "fine-tune on the articles".
- No handoff path, or handoff left entirely to the model.
- No cost estimate for a million turns a day.
- Measuring only deflection.
Discussion
Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.