Category: NLP/LLM

  • MSD0020 Distributed Training System

    Design the distributed training system for a 100B+ parameter language model on a cluster of thousands of GPUs, the way Meta, OpenAI, and DeepSeek run their frontier models. A single run spans weeks to months, costs millions of dollars in compute, and must survive GPU failures, network bottlenecks, and stragglers without restarting from scratch.

    The system has to combine data, tensor, and pipeline parallelism, checkpoint efficiently, and keep GPU utilization high enough that the run finishes on budget.

    How would you design it? Cover the parallelism strategy and communication topology, fault tolerance and checkpointing, cluster scheduling, and how you diagnose and fix the bottlenecks that keep utilization below target.

    Line-art scene: a 100B-parameter model far too large for a single 80 GB GPU, a grid of thousands of cluster GPUs with one marked as failed, and annotations for weeks of wall-clock and millions of dollars of compute

    The Problem: the model does not fit on one GPU, the cluster is big enough that something breaks every few hours, and every idle GPU-second is billed. The design question is how to keep thousands of accelerators busy on one gradient for a month.

    Answer

    The design is 3D parallelism mapped onto the bandwidth hierarchy, wrapped in an elastic supervisor that treats hardware failure as a routine event. Tensor parallelism stays inside a node where NVLink is cheap, pipeline parallelism crosses nodes because only stage activations travel, and data parallelism with sharded optimizer state sits outermost where the gradient all-reduce can be overlapped with the backward pass. Fault tolerance is asynchronous distributed checkpointing at a mathematically chosen interval plus a hot-spare pool, so a dead GPU costs minutes rather than the run. The single number the whole system is managed against is MFU (model FLOPs utilization), because at this scale every lost percentage point is real money, and every design choice below is justified by its effect on that number.

    (1) Bandwidth-Matched Parallelism: tensor parallel degree capped at the intra-node GPU count, pipeline parallel across nodes, data parallel outermost; context parallelism added only when sequences get long.
    (2) Sharded State And Selective Recompute: optimizer states and gradients sharded across the data-parallel group, with selective activation recomputation trading roughly 8% extra FLOPs for the memory that makes the fit possible.
    (3) Async Checkpointing At The Optimal Interval: copy state to host memory in seconds, flush to storage in the background, and set the interval from measured cluster MTBF instead of habit.
    (4) Elastic Recovery With Hot Spares: a watchdog detects hangs and stragglers, a spare node replaces the failed one in place, and training resumes from the last checkpoint including data-loader position.
    (5) Topology-Aware Gang Scheduling: the job is placed inside one network island as an all-or-nothing gang, after a preflight burn-in that rejects slow links and weak GPUs before the run starts.
    (6) MFU As The Run’s SLO: per-rank step-time histograms, profiler traces, and a loss budget that attributes every missing point of peak FLOPs to a named cause.

    Training system pipeline: token shards feed a resumable loader into a 3D-parallel training step, then gradient reduction and sharded optimizer update, then async checkpointing to a checkpoint store, with a health watchdog and hot-spare pool closing the recovery loop

    Figure 1: One step is load → forward → backward → reduce → update → stage checkpoint. The lower loop is what makes a month-long run survivable: detect, replace, restore.

    Clarify Before Designing:
    (1) Hardware And Interconnect: how many GPUs per node, what intra-node link (NVLink or PCIe), and what inter-node fabric bandwidth per GPU?
    (2) Token Budget And Deadline: how many training tokens, and is the constraint calendar time, total GPU-hours, or dollars?
    (3) Sequence Length: is context 8k or 128k, because long context changes activation memory and adds a whole parallelism axis?
    (4) Precision Policy: is FP8 or BF16 allowed for GEMMs, and what loss-curve deviation from a reference run is acceptable?
    (5) Storage And Checkpoint SLA: what aggregate write bandwidth exists, and how much lost work per failure is tolerable?
    (6) Cluster Ownership: dedicated reservation or shared preemptible pool, and how large a hot-spare pool can be held idle?


    Login to view more content
  • MSD0019 On-Device Small LLM Polite

    Design a small LLM that runs entirely on a phone for a privacy-preserving assistant, in the style of Apple Intelligence’s on-device foundation model or Gemini Nano on Pixel. The model must fit in roughly 2-4 GB of RAM, respond in under 300 ms on a mobile NPU, and work with the radio off.

    It also has to stay polite. It should refuse harmful requests, avoid toxic or biased outputs, and hold a respectful tone even when the user is deliberately provoking it. Battery life and offline capability matter as much as raw benchmark quality, and no user text may leave the handset.

    How would you design this system? Cover model compression and quantization for the NPU, the alignment strategy that keeps the model polite at a small scale, the on-device serving path, and how you evaluate safety without sending user data to the cloud.

    Line-art scene: a person types a provoking message into a phone whose screen shows a question mark, with callouts for 2-4 GB RAM, under 300 ms, offline with no network, and battery budget

    The Problem: a few gigabytes of RAM, a fraction of a second, no network, and a user who is testing how rude the assistant will get.

    Answer

    The design is a distilled 3B-parameter model compressed with quantization-aware training to about 2 bits per weight, served on the NPU with per-feature LoRA adapters and a tiny always-resident guard model. Politeness is trained in rather than prompted in: a large aligned teacher supplies refusal and tone supervision, a preference pass sharpens “polite but not preachy”, and safety data stays inside the quantization loss so alignment survives compression. Two decisions are pivotal. First, safety is re-verified after quantization, because low-bit weights erode refusal behavior faster than they erode average benchmark quality. Second, a separate 100M-parameter guard screens the prompt and the streamed output, so a single jailbroken generation is caught by a component that can be patched over the air without retraining the base model.

    (1) Distill + QAT + Adapters: prune and distill a large teacher into ~3B parameters, then quantization-aware train to 2-4 bits and ship 16-bit LoRA adapters per feature (summarize, reply, rewrite).
    (2) Scratch-Trained Small Model + PTQ: train a 1-2B model on curated data and apply post-training 4-bit quantization; simplest pipeline, weakest quality per byte.
    (3) Elastic Nested Model: a MatFormer-style checkpoint whose submodels can be extracted at different sizes, letting the runtime trade quality for RAM under memory pressure.
    (4) On-Device Draft + Private Cloud Escalation: answer locally by default and escalate hard prompts to a privacy-hardened server tier with explicit consent.

    On-device serving path: user prompt enters a prompt guard, then the NPU decode loop running a 2-bit base model with a task LoRA adapter, backed by an adapter store and quantized KV cache, then an output guard, then the reply, all inside a dashed device boundary

    Figure 1: Everything inside the dashed boundary runs on the handset: guard, decode loop, adapters, and cache. Nothing crosses the boundary, so every check has to happen before pixels appear.

    Clarify Before Designing:
    (1) Latency Definition: is 300 ms the time to first token or the full reply? Streaming a 60-token answer at 30 tokens per second takes two seconds no matter how good the prefill is.
    (2) Task Set and Context: which features ship (reply suggestions, summarization, rewriting), and what is the maximum prompt length? Prefill cost and KV cache size follow directly from that number.
    (3) Device Floor: which chip generation is the minimum, and what does its NPU actually execute natively (INT8, INT4, palettized weights, per-channel scales)?
    (4) Escalation Policy: is any server path permitted with consent, or is strict offline operation a product promise we cannot break?
    (5) Safety Bar: which refusal taxonomy applies, and what false-refusal rate on benign-but-edgy prompts is acceptable? Over-refusal is the failure users complain about.
    (6) Telemetry Rules: may we collect differentially private aggregate counters and opt-in donated conversations, or literally nothing?


    Login to view more content
  • MSD0017 Meeting Summarization

    Design the system behind Zoom AI Companion’s meeting summary: after a 45-minute video meeting, every participant receives a recap, the decisions made, and their action items within a minute or two. The pipeline must handle cross-talk, accents, and bad microphones across ten speakers, and a hallucinated action item is worse than none at all.

    How would you design this system? Cover transcription, speaker attribution, the summarization stack, quality control, privacy, and cost at platform scale.

    Line-art scene: a two-by-two video call grid, a clock showing forty-five minutes elapsed, an empty notepad, and a question mark asking what was actually decided

    The Problem: forty-five minutes of overlapping speech from ten microphones must become a recap, a decision list, and attributed action items, within minutes, and one invented task destroys trust. Design the pipeline that was actually listening.

    Answer

    The design is a staged pipeline with a federated summarization stack, the approach Zoom publishes for AI Companion: streaming ASR turns audio into words, speaker diarization attributes them to people, a post-processing stage restores punctuation and domain terms, and the summarization stage drafts on a small in-house LLM, scores the draft with a learned quality model (Zoom’s Z-Scorer), and escalates to a stronger external LLM only when the score is low. The two pivotal decisions are separating “who spoke” from “what was said” (diarization plus ASR reconciled with the meeting roster, not one giant model asked to guess names) and never paying frontier-model prices for meetings a small model summarizes fine (Zoom reports comparable quality at roughly 6% of GPT-4 cost).

    (1) ASR Frontend: streaming encoder-decoder (Whisper-class) with custom vocabulary biasing for product and people names; about 95% word accuracy on real meetings.
    (2) Speaker Diarization: embedding-based turn detection (pyannote-style) reconciled with the participant roster and per-channel audio when available, so “Speaker 2” becomes “Ada”.
    (3) Structured Summarization: chained tasks with schema-checked JSON output: chapter segmentation, recap, decisions, action items with owners.
    (4) Federated Quality Control: small model drafts, a learned scorer predicts summary quality, low scores escalate to stronger LLMs, and a committee-of-LLMs cross-check suppresses hallucinated action items.
    (5) Privacy by Inheritance: summaries inherit the meeting’s access control and retention; a self-hosted-only model path serves regulated customers.

    Meeting summarization pipeline: meeting audio flows through ASR, then diarization, then an attributed transcript, then a summarization stage producing recap decisions and action items, through a quality scorer, to delivery; a dashed escalation path runs from the scorer back to a stronger LLM

    Figure 1: The pipeline: hear the words, attribute them, then summarize with schema-checked structure; the scorer, not blind trust, decides when a stronger model is worth paying for.

    Clarify Before Designing:
    (1) Live versus Post: in-meeting “catch me up” queries (seconds, incremental) or post-meeting delivery only (minutes, batch)?
    (2) Language Scope: English only, or 30-plus languages via translation assists or multilingual models?
    (3) Identity Source: is a participant roster, per-channel audio, or voice enrollment available, or must speakers stay anonymous labels?
    (4) Worst Error: which failure is most expensive here: hallucinated action items, missed decisions, or wrong attribution?
    (5) Scale and Budget: meetings per day, average length, and the cost ceiling per meeting-minute?


    Login to view more content
  • MSD0015 LLM Request Routing

    Design the routing layer for an AI assistant that chooses, per request, between a small cheap model and a large expensive one. ChatGPT’s GPT-5 does exactly this with a real-time router that picks between its fast and reasoning variants, and research frameworks like RouteLLM show a trained router can cut serving cost by over 80% while holding about 95% of the strong model’s quality.

    How would you design this system? Cover what the router sees and how it is trained, how answer quality is guarded, the cost accounting, and how the system adapts as models are added, upgraded, or deprecated.

    Line-art scene: a stream of mixed user queries arriving at a toll gate that must choose between a cheap road and an expensive road, with a running cost meter and a question mark

    The Problem: most requests are easy, a few are hard, and sending everything to the biggest model burns money on “hello”. Design the gate that sends each request down the cheapest road that still answers it well.

    Answer

    The design is a trained per-request router: a tiny scorer reads the request and predicts the probability that the strong model’s answer beats the weak one’s, then sends the request to the cheapest model expected to clear the quality bar. This is routing, not cascading, so each request normally pays for exactly one model. The two pivotal decisions are to train the router on human preference data (which model’s answer people actually preferred, as in Chatbot Arena battles) rather than hand-built rules, and to expose an explicit cost-quality operating threshold as a product knob, with an escalation fallback so a routing mistake costs extra compute, not a bad answer.

    (1) Difficulty Signals: query embedding and length, task type, tool needs, and conversation state; the router is BERT-class or smaller, ~1/1000 the cost of a strong call.
    (2) Preference-Trained Router: learn P(strong model wins | query) from human preference battles, augmented with LLM-judged comparisons; route strong when P passes the threshold.
    (3) Explicit Operating Point: the threshold is chosen on the measured cost-quality curve and recalibrated as the traffic mix drifts.
    (4) Guarded Fallback: if the small model or a verifier flags low confidence, escalate to the large model; routing errors become cost, not bad answers.
    (5) Model Registry & Shadowing: candidates live behind a versioned registry; new models are shadow-scored on live traffic before the router is retrained or recalibrated.

    LLM routing pipeline: a request enters the router, which scores win probability and dispatches to the small or large model; a dashed escalation path runs from the small model through a confidence check to the large model, and user feedback loops back into router training

    Figure 1: The routing path: one cheap score per request, one paid model call, and an escalation hatch when the cheap path doubts itself.

    Clarify Before Designing:
    (1) Candidate Set: two models or many; closed APIs, self-hosted weights, or both; is the real split fast-versus-reasoning rather than small-versus-large?
    (2) Decision Granularity: per request, per message in a conversation, or pinned per session for style consistency?
    (3) Quality Bar: which evaluation defines “good enough” (human preference, task success), and how much loss versus the always-strong policy is tolerable?
    (4) Router Budget: how much latency and cost may the router itself add per request?
    (5) Traffic Shape: what fraction of traffic is trivial chat versus hard reasoning today, and how fast does that mix drift?


    Login to view more content
  • MSD0013 Machine Translation at Scale

    Design a machine translation system for a product like Google Translate: text translation between 100+ language pairs, from high-resource pairs like English-Spanish down to low-resource languages with little parallel data, served interactively at web scale where users expect answers in a fraction of a second.

    How would you design this system? Cover the model architecture, how you get training data for low-resource languages, the serving design, and how you measure translation quality.

    Line-art scene: a grid of language nodes with dense cross edges illustrating the quadratic language-pair explosion, one document flowing in and translated copies flowing out, and a question mark over how to cover low-resource pairs

    The Problem: 100 languages mean roughly 10,000 directed pairs, most with almost no parallel data, and users still expect every pair to answer in milliseconds. Design one system that covers them all.

    Answer

    The design is a single massively multilingual encoder-decoder model trained on mined bitext plus back-translated monolingual text, with a target-language token steering generation (the NLLB recipe), behind a dual-track serving layer: a fast NMT track for short, latency-critical, terminology-sensitive text, and a fine-tuned translation LLM for long, nuanced, document-level input, which is exactly the split Google shipped in its Cloud Translation API (2024) and DeepL shipped as its next-gen model. The two pivotal decisions are the multilingual pooling (high-resource pairs teach low-resource ones through a shared representation, enabling zero-shot pairs) and the honest admission that one model family does not win everywhere: NMT still wins on latency, cost, and determinism, the LLM wins on context and fluency.

    (1) One Multilingual Model: shared encoder-decoder with a target-language token; transfer from high-resource pairs gives zero-shot coverage of unseen pairs instead of 10,000 separate models.
    (2) Data Flywheel: mine bitext from web crawls with multilingual sentence embeddings (LASER), then back-translate monolingual text to synthesize pairs for low-resource languages.
    (3) Dual-Track Serving: NMT for short/interactive/terminology-critical requests, translation LLM for long-form and idiomatic text; a router picks per request.
    (4) Quality Measurement: automatic metrics (COMET, BLEU) for regression, human MQM error marking for truth, A/B tests for product impact, all reported per language pair.
    (5) Low-Resource Strategy: zero-shot transfer first, then few-example adaptive conditioning (Google’s Adaptive Translation shows as few as 5, and up to 30k, example pairs can steer output at inference time).

    Translation architecture: source text enters a router that sends short interactive text to a fast NMT track and long nuanced text to a translation LLM track, both share multilingual training on mined bitext and back-translation, and outputs pass terminology constraints before serving

    Figure 1: Dual-track serving over one multilingual training base: the router sends short, latency-critical text to NMT and long, context-heavy text to the translation LLM; terminology constraints apply on both tracks.

    Clarify Before Designing:
    (1) Scope: text only, or also speech and image translation; and which language pairs at launch?
    (2) Latency Budget: interactive typing (sub-300 ms) versus document translation (seconds) imply different model families.
    (3) Quality Bar: gist-level understanding for users, or publication-grade output with human post-editing?
    (4) Terminology: must product names, legal terms, or brand glossaries be honored exactly?
    (5) Customization: do enterprise customers need domain adaptation (medical, legal) with their own example pairs?


    Login to view more content
  • 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
  • MSD0004 Long Document Attention Scalability

    

    The standard Transformer’s self-attention mechanism has a computational and memory complexity of  O(N^2) , where  N is the sequence length. For long document classification (e.g., thousands of tokens), this quadratic scaling becomes prohibitive.

    Describe one or more attention modifications you would design or choose to enable efficient and effective long document classification.

    Problem framing diagram: a full N by N attention matrix labeled O of N squared memory flows into a question mark, with the target sub-quadratic attention at equal classification accuracy

    The Problem: full self-attention costs O(N^2) in compute and memory. Redesign attention so a several-thousand-token document stays affordable without giving up classification accuracy.

    Answer

    To handle long documents, the quadratic complexity of full self-attention (O(N^2)) must be reduced. The two primary directions are Sparse Attention (Longformer, BigBird), which constrains each token to a relevant subset (a local window plus a few global tokens), and Hierarchical Attention (HATN), which applies attention within segments first and then across segment representations. Both preserve classification quality while cutting cost from O(N^2) toward linear; linearized and recurrent variants (Performer, Linformer, Transformer-XL) attack the same wall from other angles.

    (1) Sparse Attention (Mechanism): Replace the full attention matrix with a sparse design: local window attention for nearby context plus global tokens (e.g., [CLS]) that exchange information with all tokens (Longformer, BigBird).
    (2) Hierarchical Attention (Structure): Split the document into segments; apply token-level attention within each segment, then a document-level attention across segment representations (HATN, LNLF-BERT).
    (3) Linearized / Recurrent Variants: Kernel approximations (Performer, Linformer) reach true linear complexity; Transformer-XL / Compressive Transformer carry a recurrent memory across segments.

    Two attention matrices side by side in grayscale: full attention with every cell filled, and sliding window attention with only a diagonal band of width five filled

    Figure 1: Full attention (left) fills the whole N \times N matrix; sliding-window attention (right) keeps only a diagonal band: each token attends to its neighbors, and cost drops from O(N^2) to O(N \cdot w).

    Clarify Before Designing:
    (1) Document Length: typical and maximum token count: 2k, 8k, 32k?
    (2) Starting Point: adapt a pretrained BERT-style encoder, or train from scratch?
    (3) Binding Constraint: memory at training, or latency at inference?
    (4) Interaction Pattern: does classification need global token interactions (a [CLS] readout), and how long-range are the dependencies?
    (5) Budget For Change: may we modify the architecture, or only fine-tune an off-the-shelf long model?


    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