Interview Study Guide

Guide / AI engineering Most asked

AI design walkthroughs: recommendations, multimodal pipeline, conversational memory

Three more AI designs: a recommendation system (retrieval, ranking, cold start), a multimodal image/audio/video pipeline and long-term memory for conversational assistants.

Created · Updated · 8 min read

Fundamentals (the designs)#

1. Recommendation system (feed, e-commerce, content)#

Requirements. Personalised ranked lists in < 200 ms for 50M users and 10M items; handle new users and items (cold start); optimise engagement and business goals without filter bubbles. Metrics: CTR, conversion, watch time, retention, diversity, coverage; online A/B tests are the judge.

Architecture (the standard funnel).

Events (clicks, views, purchases) → Kafka → feature store (offline: warehouse; online: Redis/DynamoDB)
Candidate generation (thousands from millions)  → several sources: two-tower embeddings + ANN, collaborative filtering,
                                                   popular/trending, recent-interest, social, "similar to last viewed"
Pre-filter (availability, seen, policy) → Ranking (hundreds → tens): GBDT or deep model with rich features
→ Re-ranking (diversity, freshness, business rules, ads mixing, fairness) → response + logging of impressions

Deep dives.

  • Two-tower retrieval: a user tower and an item tower produce embeddings trained so that clicked pairs are close; item embeddings go to an ANN index (Vector databases); the user embedding is computed online from recent behaviour, so retrieval is milliseconds.
  • Ranking: predicts P(click), P(purchase), watch time with many features: user history, item stats, context (time, device), cross features; multi-task models; calibrate probabilities; score hundreds of candidates in a few tens of ms (batched, possibly on GPU).
  • Feature store: the same feature definitions offline (training) and online (serving) to avoid training-serving skew; point-in-time correct joins to avoid label leakage; freshness SLAs (streaming features for recent actions).
  • Cold start: new users: popularity by segment, onboarding choices, contextual bandits to explore; new items: content-based embeddings from text/image, boost exploration quota, creator signals. LLMs can generate item descriptions/embeddings and explain recommendations, and can rerank small lists with a prompt, but cost and latency limit them to the final tens of items.
  • Exploration vs exploitation: epsilon-greedy, Thompson sampling, or bandits so the system keeps learning about uncertain items; log propensities for unbiased offline evaluation.
  • Feedback loops and bias: popularity bias and position bias (items shown higher get more clicks regardless of quality): include position as a feature during training and remove it at serving, add diversity and freshness rules, monitor creator fairness.
  • Offline vs online evaluation: offline metrics (AUC, NDCG, recall@k) for iteration, A/B tests for decisions; guard with latency, diversity and long-term metrics; use holdouts to measure long-term effects.
  • Serving and scale: cache per-user candidate lists for seconds to minutes, precompute for inactive users, shard ANN by item partition, degrade to popular lists on timeout, pagination with stable cursors (REST API design).
  • Failure modes: stale features (silent quality drop: monitor feature freshness and distribution drift), embedding version mismatch between towers and index (rebuild atomically with versioned indexes), empty candidate sets (fallbacks), feedback poisoning/spam.

2. Multimodal pipeline (images, audio, video understanding)#

Requirements. Users upload images/audio/video; the system extracts text, describes content, answers questions, moderates, and makes it searchable. Example: 5M uploads/day, mixed sizes; moderation within seconds, enrichment within minutes.

Architecture.

Upload (presigned URL → object storage) → event → router by media type
  Image: resize/normalise → moderation classifier → captioning/VLM → OCR → embeddings (CLIP-style) → index
  Audio: VAD/segmentation → speech-to-text (ASR) with diarisation → text pipeline (summary, topics) → index
  Video: shot/scene detection + keyframe sampling → image pipeline per keyframe + ASR for audio track → timeline merge
→ metadata store + vector index + search index → APIs (search by text or image, Q&A over media)

Deep dives.

  • Staged, asynchronous, idempotent processing with queues per stage, priorities (moderation first), retries and DLQs, keyed by content hash so duplicates are processed once.
  • Cost control: run cheap classifiers first (NSFW, quality, duplicate via perceptual hash), sample video frames adaptively (scene changes, not every second), use small/specialised models for bulk work and a large VLM only on demand or for high-value items, batch GPU inference, cache by content hash.
  • Embeddings for search: shared text-image embedding space (CLIP-style) enables text→image and image→image search; store per-frame embeddings with timestamps for video; hybrid with text metadata and ASR transcripts.
  • Long video Q&A: index transcripts and keyframe captions with timestamps; retrieve relevant segments then answer with citations to time ranges rather than feeding the whole video to a model.
  • ASR specifics: language detection, streaming vs batch, diarisation, punctuation, domain vocabulary, word-level timestamps, confidence; evaluate with word error rate.
  • Moderation and safety: layered classifiers + human review queue, hash-matching against known-bad databases, region-specific policy, appeals; fail closed for high-risk categories.
  • Evaluation: per-modality metrics (caption quality via human or judge, OCR accuracy, WER, retrieval recall@k, moderation precision/recall), sampled human review, adversarial sets.
  • Failure modes: corrupt or huge files (limits, timeouts, sandboxed decoders: media parsers are an attack surface), GPU queue backlog (autoscale on queue age, degrade enrichment before moderation), model drift on new content types, privacy (faces, voices, minors).

3. Conversational memory for assistants#

Requirements. An assistant that remembers user preferences and past interactions across sessions, without exceeding context limits, leaking data, or remembering wrong things. Metrics: personalisation accuracy, retrieval precision of memories, user trust (corrections), latency overhead < 100 ms.

Memory types.

TypeWhatStorage and use
Short-term (working)Current conversation messagesContext window; trim/summarise as it grows
EpisodicSummaries of past conversations/eventsVector index + timestamps; retrieve by relevance and recency
Semantic (facts/preferences)“Prefers vegetarian, lives in Pune, uses Python”Structured store (key-value/graph) with provenance and confidence
ProceduralLearned how-tos, user-specific instructions/toolsPrompt additions or tool configs

Architecture.

Conversation turn → [memory read] retrieve relevant memories (vector search + recency + importance, filtered by user/tenant)
                  → prompt = system + retrieved memories + recent messages + question → LLM → answer
                  → [memory write, async] extract candidate memories from the turn (LLM) → dedupe/merge/resolve conflicts
                    → store with metadata {user, source turn, time, confidence, TTL, sensitivity}
Background jobs: summarise old threads, decay/forget, consolidate duplicates, re-embed on model change

Deep dives.

  • What to remember: extract only durable, useful facts and stated preferences; skip sensitive categories unless the user opts in; store the source and timestamp so facts can be explained and corrected.
  • Retrieval scoring: score = relevance (embedding similarity) + recency decay + importance, then a token budget; use hybrid search for names and identifiers; rerank for precision.
  • Conflicts and updates: “moved to Mumbai” supersedes “lives in Pune”: use entity/attribute keys with versioning rather than appending forever; ask the user when uncertain; keep a history for audit.
  • Summarisation of long threads: rolling summaries with periodic re-summarisation; keep key decisions and open tasks verbatim; hierarchical summaries for very long histories.
  • User control and privacy: view, edit, delete memories; memory off/incognito mode; per-tenant isolation; encryption; retention limits; deletion that removes embeddings and summaries too (AI safety and compliance).
  • Safety: memory poisoning (a malicious document or message writes false “facts” or instructions into long-term memory): never store instructions from untrusted content, require user-originated sources, confidence thresholds and review, and treat retrieved memories as data.
  • Evaluation: test scenarios (preference recall after N sessions, updates, contradictions, irrelevant memory not injected), measure retrieval precision, wrong-memory rate, user corrections, and latency; regression tests for forgetting requests.
  • Cost/latency: extraction asynchronously after the response; cache retrieved memories per session; small model for extraction; limit memory tokens per prompt.
  • Failure modes: over-personalisation (irrelevant memories injected), stale facts, memory bloat, cross-user leakage (strict user-scoped filters at the storage layer), embedding model change (versioned re-embedding).

Most asked questions#

1. What are the stages of a recommender? Candidate generation, ranking, re-ranking; plus a feature store and logging for training.

2. How do you handle cold start? Popularity and segments, content-based embeddings, onboarding, exploration via bandits.

3. How do you process video cost-effectively? Scene detection and keyframe sampling, cheap classifiers first, transcribe audio separately, batch GPU inference, cache by content hash.

4. How do you give an assistant long-term memory? Extract durable facts and summaries into user-scoped stores, retrieve by relevance/recency/importance within a token budget, and let users inspect and delete.

5. How do you evaluate recommendations? Offline ranking metrics for iteration, A/B tests for decisions, plus diversity and long-term retention guardrails.

Senior-level questions#

1. “Offline AUC improved but the A/B test lost revenue.” Offline-online mismatch: training-serving skew, position bias, selection bias in logged data, optimising clicks over purchases, or latency regressions. Debug features at serving time, use counterfactual evaluation with logged propensities, and align the objective with the business metric.

2. “Two-tower embeddings and the ANN index went out of sync after a retrain.” Versioned embeddings: build the new index with the new item tower, validate recall, switch atomically with an alias, keep the old version for rollback, and never mix versions between user and item towers.

3. “Users complain the assistant remembers things it should not.” Add sensitivity classification, opt-in for categories, visible memory dashboard, short TTLs for inferred facts, user-scoped deletion, and tests for leakage across users or sessions.

4. “A video moderation backlog delays all uploads.” Separate priority queues (moderation fast path with cheaper models first), autoscale GPUs on queue age, publish videos in a “pending review” state, and degrade enrichment before moderation.

5. “How do you keep recommendations diverse and fair to creators?” Re-ranking constraints (MMR, exposure quotas, freshness boosts), exploration for new items, monitoring of exposure distribution (Gini), and A/B testing on long-term metrics.

Quiz#

1. Why separate candidate generation from ranking?

Ranking models are too expensive to run on millions of items; retrieval narrows to hundreds cheaply, and the ranker then uses rich features on those.

2. What is training-serving skew?

Features computed differently offline and online, so the model sees different data in production; fix with a shared feature store and consistent definitions.

3. Why use perceptual hashes in a media pipeline?

To detect duplicates and known-bad content cheaply before running expensive models.

4. How should a changed user fact be stored in memory?

As a versioned attribute that supersedes the old value, with source and timestamp, not as an appended contradiction.

5. What is memory poisoning?

Untrusted content causes false or malicious “facts” or instructions to be saved in long-term memory; prevent by only storing user-sourced, validated facts and treating retrieved memory as data.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes