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
- 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 messages per day, average load is QPS (queries per second), or about QPS at peak. If of traffic lands in a grey-zone review band, that creates alerts per day; at 300 reviews per analyst shift, you need reviewers daily, whereas a 50-person team ( reviews/day) caps the review rate at unless near-duplicate campaigns are clustered first.
- 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 ; track PR-AUC (precision–recall area under the curve) and recall at fixed low FPR (false-positive rate), such as recall at . Online, monitor user spam-report rate, false-positive appeal/unmark rate (messages rescued from the spam folder) and delivery latency.
- 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.
- 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 -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.
- 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 -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.
- Design serving architecture and latency: run a cascading pipeline inside the mail transfer path: edge rate-limiting and reputation/hash blocklists (under ), parallel feature hydration from an online Redis/key-value store and lightweight text parsing (), and batched model scoring (). Route high-confidence spam () 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.
- 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 of traffic while watching the rescue (not-spam) rate and delivery p99 (99th-percentile) latency before full A/B ramp-up.
- 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
- Optimising overall accuracy or ROC-AUC (area under the ROC curve) on imbalanced mail traffic; a classifier with accuracy can still overwhelm users with false positives on important receipts and one-time passwords.
- Training on user-reported spam without snapshotting features at delivery time; sender reputation and URL blocklists change after the email arrives, leaking post-delivery signals into training.
- Assuming labels are i.i.d. (independent and identically distributed) and stationary; attackers actively mutate text, images and domains to evade yesterday's model.
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 and power (with and ), 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?