Design a Recommendation Engine with a Conversational Layer
Machine LearningModel answerLast updated
Design a personalized recommender from scratch, then add a chatbot that surfaces and explains those recommendations without hallucinating unavailable items.
Scenario
You are joining a team that has no existing recommendation infrastructure. Users browse a catalog of items (think products, articles, or media — pick one and state your assumption). Your goal is to design the full recommendation stack from scratch, then extend it with a conversational interface that lets users ask questions like "What would you recommend for me today?" or "Why did you show me that item?"
Part 1 — Recommendation System
Design the end-to-end system:
- How do you collect and represent user and item data when you are starting from zero?
- What is your retrieval strategy, and how does it scale to millions of items?
- How do you rank candidates once you have retrieved them?
- How do you handle new users and new items (cold start)?
- How do you evaluate the system offline and online?
- What does the serving architecture look like, and what are your latency targets?
Part 2 — Conversational Interface
Extend the system with a chatbot that:
- Answers natural-language questions about recommendations
- Explains why a particular item was recommended
- Respects exactly the same eligibility and ranking rules as the non-conversational system (e.g., out-of-stock items must not appear)
- Does not invent or hallucinate items
Address how the chatbot retrieves live recommendations, maintains session context, handles ambiguous queries, and degrades gracefully when the recommender is unavailable.
What Is Expected
A structured verbal or written walkthrough. Cover data, modeling, serving architecture, latency and throughput, evaluation, monitoring, failure modes, and how you would iterate over time. Justify your choices and call out trade-offs explicitly. You do not need to write code, but precise component names, data formats, and numbers are expected where useful.
Clarifying Questions You Should Ask First
Before answering, state what assumptions you are making about:
- The item domain, catalog size, and feedback signals available
- Whether user interactions in the chat session should influence long-term preference models
- Acceptable end-to-end latency for recommendations and for chatbot responses
Hints
Hint 1
Start by nailing down your feedback signal (explicit ratings vs. implicit clicks/dwell time) because it drives almost every downstream modeling choice — sparse explicit signals usually push you toward implicit collaborative filtering or two-tower models rather than matrix factorization.
Hint 2
Treat retrieval and ranking as two distinct problems with different latency budgets: ANN search over embeddings for retrieval (~10 ms), a feature-rich pointwise or listwise ranker for the top-K candidates (~50 ms). Don't conflate them.
Hint 3
The chatbot's hardest constraint is grounding: the LLM must only reference items that come back from a live recommender API call made at query time. Think of the LLM as a presentation layer, not a knowledge store, and enforce that with tool use / function calling rather than hoping the model behaves.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Assumptions
State these upfront in an interview to demonstrate structured thinking:
- Domain: e-commerce product catalog, ~5 M SKUs, 10 M monthly active users.
- Feedback signals: implicit only — clicks, add-to-cart, purchases, dwell time. No star ratings.
- Latency targets: recommendation API ≤ 100 ms p99; chatbot response ≤ 3 s end-to-end.
- Chat and long-term preferences: session context is ephemeral for now; updating the long-term model from chat interactions is a Phase 2 problem.
Part 1 — Recommendation System
Data Foundation
Collect three kinds of data from day one: user behavior events (click, purchase, skip), item attributes (category, price, embeddings of title/image), and contextual signals (device, time of day, location). Stream events through Kafka into a feature store (e.g., Feast or Tecton) with both an online store (Redis, <5 ms reads) and an offline store (Parquet on S3) for training.
Cold start is the first real problem. For new items, use content-based representations — embed title and image, then find similar items with known engagement. For new users, fall back to popularity-weighted recommendations within the user's declared preference category (set during onboarding), then bootstrap a personalized model once ~20 interactions are observed.
Retrieval
With 5 M items, scoring every candidate is infeasible at query time. Use a two-tower neural network: one tower encodes the user (recent interactions, demographics, context), the other encodes the item (attributes, historical CTR). Train with in-batch negatives plus hard negatives mined from items the user saw but skipped. The output is a 128-d embedding for each side.
At serving time, pre-compute and index all item embeddings in a vector database (Faiss on GPU or Pinecone). An ANN search returns the top 500 candidates in ~10 ms. This is your retrieval stage.
Ranking
Pass the 500 candidates through a pointwise ranker — a gradient-boosted tree (LightGBM) or a shallow MLP — that scores each (user, item) pair using richer cross features: user–item embedding dot product, historical CTR for the item, price relative to the user's median purchase, recency of similar purchases. Apply eligibility filters (in-stock, region-available, age-restricted) as hard constraints before or after scoring, never rely on the model to learn them implicitly. Return the top 20 ranked items.
Common mistake: skipping position bias correction. If your training data comes from logged impressions, items shown in position 1 get inflated positive labels. Apply inverse propensity weighting or train a separate propensity model to debias.
Evaluation
- Offline: Precision@K, Recall@K, NDCG@K on a time-split holdout. Avoid random splits — they leak future data into the past.
- Online: A/B test on click-through rate, add-to-cart rate, and revenue per session. Run for at least one full business cycle (usually 2 weeks) to capture weekly patterns.
- Monitoring: Track embedding drift (cosine similarity of today's average user embedding vs. last week's), ranking score distribution, and null-result rate (queries that return zero eligible items).
Serving Architecture
User request
→ Feature fetch (Redis, ~5 ms)
→ Two-tower ANN retrieval (Faiss, ~10 ms)
→ Eligibility filter (catalog service, ~5 ms)
→ LightGBM ranker (model server, ~20 ms)
→ Response cache (Redis, TTL 60 s for non-personalized fallback)
Total p99 target: ~100 ms
Batch-refresh item embeddings nightly; update user embeddings incrementally as new events arrive.
Part 2 — Conversational Interface
Core Design Principle: The LLM Is a Presentation Layer
The single biggest failure mode is letting the language model generate item names or attributes from its weights. It will hallucinate unavailable, discontinued, or incorrect items. The correct architecture is tool use / function calling:
- The LLM receives the user's message and decides whether to call
get_recommendations(user_id, context, filters). - That function hits the live recommendation API described in Part 1 — same retrieval, same ranking, same eligibility filters.
- The LLM receives the structured result (item IDs, names, prices, scores) and generates a natural-language response grounded strictly in that payload.
This makes hallucination a policy violation, not just a model tendency — you can assert in the prompt and in post-processing that the response must reference only items present in the tool's return value.
Session Context
Maintain a short-term session store (Redis, TTL 30 min) with the last N turns and the last retrieved item list. This lets the user say "tell me more about the second one" without re-calling the recommender. Do not persist session signals to the long-term preference model in Phase 1 — this avoids polluting training data with conversational exploration patterns, which differ from organic browsing intent.
Explaining Recommendations
For explainability, attach a reason code to each ranked item at serving time (e.g., "because_you_purchased": ["item_X"], "trending_in_category": "Running Shoes"). The LLM uses these codes to generate the explanation, not its own inference about why the model ranked something highly.
Handling Ambiguous Queries
If the user's query is underspecified ("show me something nice"), run the standard personalized retrieval. If it is contradictory or outside the catalog ("find me a flying car"), the LLM should acknowledge the constraint clearly rather than attempting a forced mapping.
Graceful Degradation
If the recommendation service is unavailable, the chatbot should say so explicitly rather than falling back to LLM-generated suggestions. A hard fallback to a static "most popular items" list is acceptable and honest; a soft fallback that silently invents items is not.
Latency Budget for the Chatbot
User message → intent detection + tool call decision: ~200 ms (LLM, streaming)
→ Recommendation API call: ~100 ms
→ LLM response generation (streaming): ~1–2 s
Total: ~2–3 s, within the 3 s target
Use streaming output so the user sees partial text while the full response generates.
Iteration Roadmap
- Phase 1: Two-tower retrieval + LightGBM ranker + rule-based chatbot grounding. Ship fast, measure.
- Phase 2: Session signals feed a short-term interest model; explore sequential models (SASRec, BERT4Rec).
- Phase 3: Fine-tune the LLM on internal explanation data; add multi-turn preference elicitation ("do you prefer X or Y?") that updates the session context in real time.
The strongest answers articulate why each component exists, not just what it is — and are honest about what gets deferred and why.