Tag: System

  • MSD0011 LLM Evaluation Pipeline

    Your team ships an LLM-powered product: a customer-support copilot built on a foundation model API, similar in spirit to how GitHub evaluates models for Copilot before each release. The model version, prompts, retrieval index, and tools all change every few weeks, and every change can silently alter answer quality.

    Design an evaluation pipeline that runs before each release. What do you test, how do you score open-ended outputs, and how do you decide whether the new version is safe to ship?

    Line-art scene: a release train carrying a new model version and new prompts toward a production gate, a clipboard with quality metrics, and a question mark over whether the new version regressed

    The Problem: the system under test is stochastic, so a green build means nothing without a repeatable quality signal. Design the gate between “we changed the prompt” and “customers see it.”

    Answer

    The design is a CI pipeline for a stochastic system: a curated golden suite mined from real production failures, a grader ladder (deterministic checks where possible, an LLM judge calibrated against human labels where necessary, human audits on top), and a release gate that compares the candidate against the current version on quality metrics plus guardrails (safety, latency, cost). GitHub runs more than 4,000 such offline tests in CI before any Copilot model change; Anthropic’s guidance is to start with 20 to 50 tasks drawn from real failures and grow from there. The pipeline ends in a canary and A/B test, and production monitoring feeds new failures back into the suite, so the eval set is a living artifact.

    (1) Cases From Reality: the golden suite is mined from production logs, bug reports, and support tickets, not invented at a desk; 20-50 real tasks beat 500 synthetic ones.
    (2) Grader Ladder: deterministic checks first, an LLM judge (calibrated to human labels, pairwise where possible) second, human audits as the calibration anchor.
    (3) Capability vs Regression Suites: capability evals start at a low pass rate and measure progress; regression evals sit near 100% and block backsliding; saturated capability cases graduate into the regression suite.
    (4) Release Gate With Guardrails: the candidate must beat or tie the incumbent on quality with statistical significance, and must not breach guardrails on safety, latency, and cost.
    (5) Flywheel: production failures are mined, de-identified, and converted into new eval cases every release cycle.

    Release evaluation pipeline: a candidate version flows through the golden suite, deterministic checks and an LLM judge with human calibration, a release gate comparing deltas and guardrails, then canary and A/B rollout, with a loop from production logs back into the golden suite

    Figure 1: The pre-release path: golden suite, grader ladder, gate, then canary. The loop back from production logs is what keeps the suite honest as user behavior shifts.

    Clarify Before Designing:
    (1) Product Surface: single-turn answers, multi-turn chat, or an agent with tool calls; the grader design differs sharply.
    (2) What Changes per Release: model version, prompts, retrieval data, tools; each change type needs its own regression coverage.
    (3) Failure Cost: what is the worst plausible wrong answer (refund mistakes, medical tone, leaked PII) and who is accountable for it?
    (4) Human Label Budget: how many expert labels per cycle can we afford, since they anchor the judge’s calibration?
    (5) Release Cadence: weekly prompt tweaks and quarterly model upgrades imply different gate depths.


    Login to view more content
  • MSD0010 Grammar Checking Writing Assistant

    

    You are building a writing-assistance product like Grammarly. As a user types in a browser extension, email client, or mobile keyboard, the system underlines mistakes and offers corrections in near real time: spelling, punctuation, subject-verb agreement, tense, and for premium tiers, style and clarity rewrites.

    How would you design this system? Cover the model architecture, the latency budget, the training data, and how you evaluate suggestion quality.

    Line-art scene: a document page with several sentences, wavy underlines beneath a misspelled word and a grammar error, a blinking caret mid-sentence, a stopwatch annotated with a 100 ms budget, and a question mark over which model answers fast enough

    The Problem: suggestions must arrive faster than the next keystroke, and a wrong correction costs more trust than a missed error. Design the system behind the wavy underline.

    Answer

    The design is a model ladder behind a per-sentence router: cheap deterministic rules and dictionaries catch spelling and punctuation on-device, an edit-tagging Transformer (one parallel pass over the tokens emitting KEEP, DELETE, INSERT, REPLACE tags) handles most grammatical error correction in the cloud, a seq2seq model takes the sentences that need reordering, and an LLM serves style and clarity rewrites only on demand. The two pivotal decisions are routing each sentence to the cheapest model that can fix it (latency is a product feature), and tuning every error type to a precision-first operating point because false corrections erode trust faster than misses.

    (1) Error Taxonomy Drives Architecture: mechanical errors (spelling, punctuation, agreement) and open-ended style rewrites are different problems and deserve different models.
    (2) Model Ladder With Routing: rules → edit-tagger → seq2seq GEC → LLM, cheapest first; the router reads error type, confidence, and latency budget.
    (3) Precision-First Operating Points: per-error-type thresholds tuned on F0.5, since a wrong correction damages trust more than a miss.
    (4) Latency Engineering: score only the current sentence, cache unchanged text, and keep the inline path under 100 ms end to end.
    (5) Personalization & Dialect: locale (US/UK), register (casual vs formal), and per-user dismiss history modulate which suggestions fire.

    Real-time suggestion pipeline: keystrokes enter a sentence buffer with cache, a router sends the sentence to spell and rules, an edit-tagging model, a seq2seq corrector, or an async LLM, and a suggestion merger renders underlines in the editor

    Figure 1: The inline path: each finished sentence is routed to the cheapest sufficient model, and a merger dedupes overlapping suggestions before rendering underlines. Unchanged text is served from cache.

    Clarify Before Designing:
    (1) Scope: which languages and locales, and is style or clarity rewriting in scope or only mechanical correctness?
    (2) Latency Budget: how many milliseconds for inline suggestions, and is there an async path for long-form checks?
    (3) Deployment: what runs on-device versus in the cloud, given browser-extension and mobile constraints?
    (4) Privacy: may user text leave the device, and are there regulated contexts (legal, medical) to special-case?
    (5) Personalization: can we learn from per-user accept and dismiss behavior, and where may that profile live?


    Login to view more content
  • MSD0009 Restaurant Recommendation System for Food Delivery

    

    You are building the restaurant recommendation system for a food-delivery platform like Uber Eats or DoorDash. When a user opens the app, the home feed must rank nearby restaurants in a way that converts to orders, while respecting hard logistics: the restaurant must be open, inside the delivery radius, and able to deliver on time given the current courier supply.

    How would you design this system? Cover the retrieval and ranking architecture, the features and objectives, and how you handle cold start for new restaurants.

    Line-art scene: a phone showing a restaurant feed stands next to a city map dotted with restaurant pins inside a 5 km delivery circle, a clock marks the lunch rush, and a question mark hangs over which restaurant should rank first

    The Problem: a million restaurants platform-wide, but only a few hundred can actually deliver to this user right now. Rank the right ones first, inside a lunch-rush latency budget.

    Answer

    The design is a multi-stage funnel with a hard logistics gate in front: a geo/open/ETA filter cuts the catalog to the few hundred restaurants that can actually serve the request, multi-source retrieval (two-tower embeddings, co-order graphs, trending-nearby) proposes candidates, a multi-task ranker scores them for order probability, basket value, and delivery time, and a re-ranker enforces cuisine diversity and new-restaurant exploration. The two decisions that make or break the system are treating deliverability as a constraint rather than a feature, and reserving exploration slots so new restaurants ever get seen.

    (1) Funnel, Not One Model: filter → retrieve → rank → re-rank, so each stage stays cheap enough for the 50 ms feed budget.
    (2) Logistics As Hard Filters: open hours, delivery radius, courier supply, and predicted ETA gate eligibility before any learned model runs.
    (3) Context-Heavy Features: time of day, day of week, weather, and session activity matter as much as long-term taste, because lunch intent differs completely from late-night intent.
    (4) Multi-Objective Ranking: combine P(order), expected basket value, and delivery-time risk into one score with explicit business weights.
    (5) Cold Start By Construction: content-based embeddings give new restaurants a Day-1 representation, and reserved exploration slots guarantee them impressions.

    Recommendation funnel pipeline: catalog enters a geo open ETA filter, then multi-source candidate retrieval, then a multi-task ranker, then a re-ranker for diversity and exploration, producing the home feed, with a logging and retraining loop feeding back

    Figure 1: The serving funnel: about one million restaurants shrink to roughly 300 deliverable candidates, then to a ranked top-20 feed. The dashed loop is the offline retraining path fed by logged impressions and orders.

    Clarify Before Designing:
    (1) Scale: how many cities, restaurants, and daily active users, and what is the peak feed QPS at lunch?
    (2) Latency Budget: how many milliseconds for the home feed, and are personalized search results in scope too?
    (3) Objective Priority: is the north star order conversion, gross merchandise value, or delivery-time reliability?
    (4) Cold-Start Volume: how many new restaurants onboard per week, and in how many cities?
    (5) Constraints: must we support sponsored slots, dietary filters, and per-market regulations?


    Login to view more content
  • MSD0007 Demand Forecasting System for Retailer

    

    Design a demand forecasting system for a large retail company like Costco, Walmart, or Target. The system should predict future product demand across stores and time to support inventory planning, replenishment, and promotions.

    Line-art scene: store shelves with products and a sales history curve flow into a question mark, producing a replenishment plan with P10, P50, and P90 quantities

    The Problem: thousands of SKUs across hundreds of stores. Predict each one’s future demand well enough to keep shelves full and waste low, then feed those numbers to replenishment and pricing.

    Answer

    The demand forecasting system ingests diverse data (sales, inventory, weather, promotions) and predicts product demand with ML models spanning time series, tree-based, and deep learning methods. It features a scalable layered architecture (data pipelines, real-time processing, integration for inventory management) and drives decisions with probabilistic forecasts, reducing stockouts, optimizing supply chains, and improving accuracy through iterative model training.

    (1) Problem Definition & Metrics: Fix granularity (SKU-store-day), horizon (2-week operational, 3-month tactical), and objective (minimize out-of-stocks and waste); measure with WMAPE and forecast bias.
    (2) Data Strategy: A unified feature store over internal signals (sales, hierarchy, pricing, promos, inventory, clicks) and external ones (calendar, weather, events, competitor, macro).
    (3) Layered Architecture: Ingestion → processing & feature store → modeling layer → serving APIs → monitoring & feedback.
    (4) Hierarchical Ensemble Modeling: Interpretable base (Prophet/ETS) at aggregate level, global LightGBM/XGBoost as the granular workhorse, TFT/DeepAR for high-volatility items, reconciled top-down and bottom-up.
    (5) Probabilistic Forecasts: Output quantile forecasts (P10, P50, P90) so logistics can set safety stock from uncertainty, not a single number.

    Five-layer architecture diagram: batch and real-time data ingestion flows to feature store, modeling layer, forecast serving API with replenishment and pricing consumers, and monitoring with a feedback arrow returning to modeling

    Figure 1: The five-layer system: ingestion and the feature store feed a model repository; forecasts are served through APIs to replenishment and pricing, while monitoring closes the loop back into retraining.

    Clarify Before Designing:
    (1) Scale: how many SKUs, stores, and series (SKU × store) must be forecast?
    (2) Granularity & Horizon: store-day or region-week? 2-week replenishment or 3-month tactical planning?
    (3) Decision Consumers: automated replenishment, or human planners reviewing suggestions?
    (4) Data Reality: is a promotions calendar available in advance? New product launch cadence (cold-start rate)?
    (5) Cost Asymmetry: the cost of a stockout (lost sale, empty shelf) versus overstock (waste, markdowns)?


    Login to view more content
  • MSD0006 Video Recommendation System

    

    How would you design a scalable and personalized video recommendation system for a platform like YouTube, Netflix, or TikTok that can recommend relevant videos in real time to billions of users?

    Line-art scene: a user with a phone facing a huge wall of video thumbnails labeled billions of videos, with a question mark leading to a clean top twenty feed on the phone

    The Problem: billions of videos, billions of users, one feed request at a time. Pick the top-20 most relevant videos for this user in milliseconds.

    Answer

    A modern recommendation system uses a multi-stage pipeline to narrow billions of videos down to a top-20 list for a user in milliseconds. It typically consists of Candidate Generation (filtering down to hundreds), Ranking (scoring those hundreds with deep learning), and Re-ranking (applying business logic for diversity, freshness, and safety). The full path is: Data Logging → Candidate Generation → Ranking → Re-ranking → Serving.

    (1) Multi-Stage Pipeline: No single model can score a billion items per request. The funnel makes it affordable: retrieve ~500 candidates cheaply, then rank precisely, then polish.
    (2) Data & Features: User signals (watch history, watch time, likes, skips, follows), video features (visual/audio/text embeddings, popularity, freshness), and context (time of day, device, network).
    (3) Candidate Generation: Multi-source retrieval (collaborative filtering / two-tower, content-based, seed-based co-watch, trending), merged and deduplicated to ~100-500.
    (4) Ranking: A deep model scores the candidates: DNNs on hundreds of features, Multi-Task Learning heads (click, watch time, like, share), and sequence models for session context.
    (5) Re-Ranking: Business and quality constraints: remove seen/unsafe items, inject diversity and freshness, fight filter bubbles.

    Funnel diagram: billions of videos narrow through candidate generation to about five hundred, through ranking to a top twenty list, then re-ranking and serving to the user feed

    Figure 1: The recommendation funnel: each stage trades breadth for precision: cheap retrieval cuts billions to hundreds, the ranking model orders them precisely, and re-ranking applies the final business logic before serving.

    Clarify Before Designing:
    (1) Scale: how many videos, daily active users, and feed requests per second?
    (2) Latency Budget: how many milliseconds for a feed request, end to end?
    (3) Objectives: what are we optimizing (clicks, watch time, long-term satisfaction), and are there multiple conflicting goals?
    (4) Cold Start Volume: how many new users and new videos arrive daily?
    (5) Constraints: ads insertion, content safety, regional/legal rules that override relevance?


    Login to view more content
  • MSD0005 Surveillance Video Anomaly Detection

    

    How would you design an end-to-end surveillance system that automatically detects and alerts security personnel to ‘anomalous events’ (e.g., break-ins, fainting, or prohibited movements) in a large shopping mall?

    Line-art scene: a shopping mall corridor watched by a wall-mounted camera, with a walking person and a question mark callout asking normal or anomaly

    The Problem: dozens of cameras stream continuously. Spot the rare anomalous event (break-in, fainting, prohibited movement) in real time, knowing you have no labeled anomalies to train on.

    Answer

    A surveillance anomaly detection system captures video streams, preprocesses them into clips, and uses a deep learning model (typically a pretrained video backbone plus a lightweight anomaly scoring head) to identify unusual behavior. It operates in a semi-supervised setup trained on normal data, runs in real time with sliding windows and temporal smoothing, and wraps the model in alerting, monitoring, and a human-in-the-loop feedback loop for calibration and retraining.

    (1) Ingestion & Preprocessing: Capture real-time streams from many cameras; resize frames and normalize pixels before clipping them into short windows.
    (2) Feature Extraction: A pretrained backbone (2D CNN (EfficientNet), optical flow, 3D CNN (I3D), or a Video Transformer (Swin, TimeSformer)) turns each clip into features.
    (3) Semi-Supervised Normal Model: An autoencoder or GAN trained on months of “normal” mall activity; high reconstruction error on new footage flags an anomaly against a calibrated threshold.
    (4) Alerting & Human-In-The-Loop: Real-time alerts send anomalous frames to operators, whose “Not an Anomaly” clicks feed recalibration and retraining.
    (5) System Design: Edge devices do preliminary processing to save bandwidth, the cloud does heavy computation; evaluation tracks precision, recall, F1 and false-alarm rates.

    Three-panel mechanism diagram: clips flow into a pretrained video backbone for feature extraction, an autoencoder trained on normal activity reconstructs them, and a reconstruction error curve crossing a threshold line flags anomalies

    Figure 1: The detection mechanism: backbone features feed a model trained to reconstruct normal activity; when reconstruction error crosses the calibrated threshold, the clip is flagged anomalous.

    Clarify Before Designing:
    (1) Scale: how many cameras, what fps and resolution, and how many concurrent clips must be scored?
    (2) Alert Latency: how many seconds from event to operator notification?
    (3) Anomaly Definition: a closed list of event types, or anything unusual; and are any labels available (frame-level, video-level, none)?
    (4) False-Alarm Budget: how many false alerts per camera per day can guards tolerate before they start ignoring the system?
    (5) Deployment: on-prem edge hardware available, or cloud-only?


    Login to view more content
  • MSD0003 Spam Email Detection

    

    Design an end-to-end Machine Learning system to effectively detect and filter spam emails in a high-volume email service.

    Describe how you would design, train, and deploy this system.

    Line-art scene: a stream of email envelopes flows into a filter marked with a question mark, splitting into a clean inbox and a spam bin

    The Problem: a high-volume mail stream must be split into inbox and spam in real time, where one false positive can lose a user’s important email forever.

    Answer

    The system is a real-time classification pipeline at the mail gateway. It begins with data collection and preprocessing (features from text and metadata) and trains a supervised model on user-labeled history. Deployment is a low-latency prediction service that scores every incoming email and applies a tuned threshold. Because spammers constantly adapt, the system lives or dies by its monitoring and continuous-training loop that fights concept drift.

    (1) Objectives & Metrics: Precision first: a false positive (legitimate mail in spam) is far costlier than a false negative; keep recall high as the secondary goal and track F1 / PR-AUC.
    (2) Data & Features: User-labeled history plus external corpora; features span email text (subject, body), metadata (sender, domain reputation, recipients), and behavior (links, attachments, frequency).
    (3) Two-Stage Cascade: A fast traditional model filters the obvious ~80%, then a Transformer deep-analyzes the ambiguous ~20%: accuracy where it matters, speed everywhere else.
    (4) Deployment: A low-latency prediction API at the gateway: receive → extract features → score → threshold → route to spam folder or inbox.
    (5) Maintenance: Monitor precision/recall daily, harvest user feedback (‘Mark as Spam’ / ‘Not Spam’) as fresh labels, and retrain continuously against concept drift.

    Inference pipeline: incoming email passes through mail server, spam API, feature extraction, model scoring, then a threshold decision branching to spam folder or inbox

    Figure 1: The real-time inference path: every incoming email is scored by the model (e.g., 0.95), and a tuned threshold (e.g., 0.8) routes it (spam folder or inbox) inside the latency budget of the mail gateway.

    Clarify Before Designing:
    (1) Scale: email volume per day and peak QPS at the gateway?
    (2) Latency Budget: how many milliseconds may scoring add before the email is delivered?
    (3) Cost Asymmetry: confirmed: is a false positive (lost legitimate mail) really the catastrophic error here?
    (4) Labels: how much user-labeled spam/not-spam data exists, and how fresh is it?
    (5) Adversaries: how quickly do spam tactics mutate in this ecosystem: days, weeks?


    Login to view more content
  • MSD0001 Real-Time Factory Product Inspection

    

    You are tasked with designing and deploying a deep learning-based computer vision system for real-time quality control on a high-speed manufacturing assembly line. The system must classify each product as ‘Pass’ or ‘Fail’ due to surface defects (scratches, cracks, misalignments).

    Describe the complete end-to-end system design, from data acquisition and model selection to deployment and post-deployment maintenance.

    Crucially, how would you address the challenges of real-time inference speed and the severe class imbalance due to the fact that defects are rare?

    Problem framing diagram: a high-speed line producing 600 units per minute with surface defects flows into a question mark, with required outputs Pass or Fail within a 100 millisecond per unit budget at a 0.1 percent defect rate

    The Problem: 600 units per minute stream past a camera. Design the system that fills the question mark: real-time Pass/Fail within 100ms per unit, with defects occurring at only ~0.1%.

    Answer

    The solution is an Edge-AI Computer Vision Pipeline. It starts with a controlled imaging setup to capture consistent, high-quality images. The core is a lightweight CNN (e.g., MobileNetV2) fine-tuned via transfer learning, trained with a specialized loss (Focal Loss) to handle the rare-defect imbalance. Deployment runs on a local Edge GPU to guarantee low-latency inference, and a continuous MLOps loop monitors performance and retrains the model against new or subtle defects (concept drift).

    (1) Data & Setup: Controlled environment (lighting/staging) plus high-resolution cameras; transfer learning reduces the need for large-scale defect collection.
    (2) Imbalance Handling: Focal Loss (or weighted loss) combined with heavy data augmentation and oversampling of the rare ‘Fail’ class.
    (3) Model Architecture: A lightweight CNN (MobileNetV2, EfficientNet-B0) chosen for speed over a large, deep network.
    (4) Real-Time Deployment: Edge deployment on an industrial GPU (e.g., NVIDIA Jetson) with ONNX/TensorRT optimization and INT8 quantization to stay inside a sub-100ms budget.
    (5) Post-Deployment MLOps: Log every classification (especially false negatives) and trigger periodic retraining to combat model drift.

    End-to-end edge-AI quality control pipeline: camera and lighting feed preprocessing, an edge CNN classifier, a pass/fail actuator, and a logging path that loops back to periodic retraining

    Figure 1: The end-to-end pipeline. Solid arrows are the real-time inference path (capture → preprocess → edge CNN → actuator); the dashed loop is the offline MLOps path: logged hard examples and low-confidence frames flow back into retraining.

    Clarify Before Designing:
    (1) Throughput: line speed in units per minute, and the per-unit latency budget?
    (2) Defect Ontology: a closed set of defect types, or can new types appear in production?
    (3) Deployment Constraints: is cloud inference acceptable, or must everything run on-prem at the line?
    (4) Data Availability: how many labeled ‘Fail’ examples exist today, and what is the true defect rate?
    (5) Cost Asymmetry: the business cost of a false accept (defect escapes) versus a false reject (good unit scrapped)?


    Login to view more content