How would you design a spam detection system for a large messaging or email platform?

ML system design, Case studies
Level L4 Advanced. Length Long. Nature Th+Mat Both.

What's being asked

Whether you can design an end-to-end adversarial classification pipeline under severe class imbalance, asymmetric false-positive costs, noisy delayed labels and bounded human-review capacity.

Key idea

Spam detection is an adversarial, high-precision filtering problem where blocking a genuine message (false positive) hurts trust far more than letting one spam message through (false negative). A production system pairs a millisecond rule and blocklist tier with a calibrated ML classifier, routes uncertain cases to a capacity-capped human review queue, and retrains continuously on fresh labels to counter adaptive spammers.

Steps

  1. Clarify requirements and scale: confirm scope (inbound text, links and attachments; automated blocking vs quarantine/spam-folder routing), latency SLA (service-level agreement, typically under 100 ms at message delivery) and error costs (high precision at low false-positive rate). Back-of-envelope estimate: at 108 messages per day, average load is 108/86,400≈1,157 QPS (queries per second), or about 3,472 QPS at 3× peak. If 0.05% of traffic lands in a grey-zone review band, that creates 108×0.0005=50,000 alerts per day; at 300 reviews per analyst shift, you need ⌈50,000/300⌉=167 reviewers daily, whereas a 50-person team (15,000 reviews/day) caps the review rate at 15,000/108=0.015% unless near-duplicate campaigns are clustered first.
  2. Define the ML objective and metrics: frame detection as calibrated binary or multi-class classification (ham, spam, phishing, malware) trained with weighted cross-entropy or focal loss to reflect asymmetric costs. Offline, avoid raw accuracy because spam prevalence after perimeter blocks may be under 1–2%; track PR-AUC (precision–recall area under the curve) and recall at fixed low FPR (false-positive rate), such as recall at FPR≤0.1%. Online, monitor user spam-report rate, false-positive appeal/unmark rate (messages rescued from the spam folder) and delivery latency.
  3. Design data and labels: combine user feedback (report-spam and mark-as-not-spam clicks), spam-trap honeypot accounts, curated analyst labels and automated bounce/authentication signals. User reports are noisy (users sometimes mark newsletters as spam) and delayed (hours or days after delivery), and blocks create selection bias because blocked messages never receive user feedback. Address this by snapshotting raw features at delivery time, upweighting trusted analysts and trap accounts, running stratified sampling across score buckets for unbiased evaluation, and using time-based train/validation splits.
  4. Engineer features across four modalities: (1) sender reputation and authentication: domain age, historical complaint rate, IP (Internet Protocol) reputation, and SPF (Sender Policy Framework), DKIM (DomainKeys Identified Mail) and DMARC (Domain-based Message Authentication, Reporting and Conformance) pass/fail status; (2) content and obfuscation: normalised Unicode tokens, character n-grams, TF-IDF (term frequency–inverse document frequency) and neural text embeddings, HTML-to-text ratio, hidden CSS/zero-width characters and OCR (optical character recognition) text from image-only spam; (3) behaviour and velocity: burst sending rate, recipient count and reply-to mismatch in sliding windows; (4) graph features: sender–recipient interaction graph, shared redirect domains and URL (Uniform Resource Locator) shortener chains. An interviewer will probe how you prevent leakage from future reputation: all historical counters must be computed strictly point-in-time.
  5. Build models from simple to advanced: start with deterministic rules and hashes (known malicious IPs, URLs and attachment signatures) to drop high-volume junk cheaply, followed by a fast linear or logistic regression baseline on sparse n-grams and sender features. Move to a two-tier ML stack: a GBDT (gradient-boosted decision trees) or compact multi-modal DNN (deep neural network) combining dense text/image embeddings with tabular reputation and velocity features, plus an asynchronous heavy classifier or graph clustering job for coordinated campaigns and attachments. Interviewers often probe interpretability vs accuracy and why GBDT or linear models pair well with fast rule overrides for zero-day attacks.
  6. Design serving architecture and latency: run a cascading pipeline inside the mail transfer path: edge rate-limiting and reputation/hash blocklists (under 5 ms), parallel feature hydration from an online Redis/key-value store and lightweight text parsing (20–30 ms), and batched model scoring (20–40 ms). Route high-confidence spam (p≥0.99) to the spam folder, quarantine borderline high-impact messages (such as suspected phishing) into a clustered human-review queue sized to analyst throughput, and log every prediction with snapshotted features. Trade-off probed: synchronous blocking before delivery vs asynchronous post-delivery retraction (clawback) when heavy attachment or graph signals arrive late.
  7. Evaluate and launch safely: validate offline on chronologically held-out days sliced by sender domain age, language and region to catch slice regressions. Roll out in shadow mode first to measure latency and score shifts against the live filter without moving user mail, then canary on 1–5% of traffic while watching the rescue (not-spam) rate and delivery p99 (99th-percentile) latency before full A/B ramp-up.
  8. Monitor and iterate against adversarial drift: track feature-distribution shifts via PSI (population stability index), sudden drops in model confidence, spikes in user spam reports or appeals, and shifts in sender domain age. Because spammers probe boundaries and pivot within hours (e.g. switching to image-only payloads or newly registered domains), pair rapid expert rule deployment with daily/hourly incremental retraining on snapshot-logged data, adversarial augmentation (homoglyphs, obfuscated URLs) and active learning from the human-review queue.

Common mistakes

How long your answer should be

8–10 minutes; cover the cascading architecture, capacity calculation and adversarial feedback loop.

Read this

Previous in ML system design: A production model's request error rate is 2%. A canary deployment receives 5% of 1,000 queries per second (QPS). Using a one-sided test at significance level α=0.05 and power 0.8 (with zα=1.645 and zβ=0.8416), how many canary requests are needed to detect a rise in error rate to 2.5% against the baseline fleet, and how long does that take? Why does peeking repeatedly at canary metrics inflate false alarms?
Next in ML system design: How would you design a video recommendation system for a large video platform?