Build a production spam filter for email
Machine LearningModel answerLast updated
Design a complete ML system to classify incoming email as spam or legitimate, covering labeling, features, models, serving, metrics, and adversarial defenses.
You are building a spam detection system for an email platform serving hundreds of millions of users.
Design the complete machine learning pipeline to classify incoming messages as spam or legitimate mail. Your design should address:
- Problem framing and labels: How do you define spam? Where do training labels come from, and what biases do they carry?
- Data and features: What signals and feature families will you use? How do you extract them reliably?
- Model architecture: What modeling approach fits the latency, scale, and accuracy requirements? Should you use rules, classical ML, deep learning, or a combination?
- Inference and serving: How do you deploy models to handle peak traffic with strict latency budgets? How do you avoid training-serving skew?
- Thresholds and decisions: How do you choose operating points? What actions (reject, quarantine, spam folder, inbox) map to which score ranges?
- Metrics: What offline and online metrics matter? How do you validate that the system works before and after launch?
- Adversarial robustness: Spammers adapt. How do you defend against evasion, poisoning, and probing?
- Monitoring and iteration: How do you detect drift, retrain models, and roll out updates safely?
State your assumptions about scale, latency targets, and the relative cost of false positives versus false negatives. A strong answer balances technical depth with pragmatic trade-offs.
Hints
Hint 1
Consider that a false positive (legitimate mail marked spam) is far more damaging than a false negative. How does this asymmetry shape threshold choices and evaluation?
Hint 2
Spammers constantly evolve tactics. What normalization and robustness techniques prevent simple obfuscation attacks, and how do you monitor for new evasion patterns?
Hint 3
The system sits in the critical delivery path. How do you layer models of different complexity to meet latency requirements while maintaining high accuracy?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Scope and Assumptions
Begin by clarifying the operating environment and constraints.
Scale
Assume 500 million active mailboxes receiving approximately 10 billion messages daily. That translates to roughly 115,000 messages per second on average, with peak traffic reaching 300,000 per second. More than half of all connection attempts are abusive and should be rejected cheaply before invoking expensive classification.
Latency requirements
Classification happens inline during message delivery. Target end-to-end scoring latency of under 100 ms at p99. Heavy models can run only on a small subset of traffic.
Cost asymmetry
A false positive—legitimate mail incorrectly filtered—can mean a missed job interview confirmation or a lost password reset. False positives cost 10 to 100 times more than false negatives. This drives every downstream decision about thresholds, metrics, and system design.
Problem Definition and Label Sources
Frame this as binary classification: estimate P(spam | message, context). You may also need separate detectors for phishing and malware, which demand stricter handling.
Where labels come from
- User feedback: "Report spam" and "Not spam" buttons provide high-volume signal, but labels are noisy and delayed. Users sometimes report newsletters they originally subscribed to. Weight feedback by reporter reliability and account history.
- Spam traps: Email addresses never used by real people. Any mail arriving at a trap is spam with extremely high confidence. Traps provide fresh adversarial examples but contain no legitimate mail.
- Professional raters: Human experts label a small, balanced sample drawn from donated mailboxes. Use this as your gold evaluation set.
- Implicit signals: Replies, adding sender to contacts, and moving mail out of the spam folder are strong indicators of legitimate mail.
Avoiding label leakage
Join feedback to the features as they existed at decision time, not current state. Sender reputation computed after the fact will leak future information into training.
Deduplicate campaign content by hashing so that one mass mailing doesn't dominate your training set.
Feature Engineering
| Feature family | Examples |
|---|---|
| Network and connection | IP address reputation, autonomous system number, DNS blocklist presence, reverse DNS validity, connection rate, geographic origin, TLS usage |
| Email authentication | SPF, DKIM, and DMARC results; anomalies in the Received header chain; mismatches between From and Reply-To; Message-ID format; SMTP client fingerprint |
| Sender reputation | Aggregate statistics per IP, domain, and DKIM signing domain: message volume, user report rate, bounce rate, spam trap hits, domain registration age. Compute over multiple time windows. |
| Message content | Text embeddings from normalized body; URL characteristics (domain age, redirect chains, typosquatting distance from popular domains); attachment file types; HTML-to-text ratio; OCR-extracted text from images |
| Recipient context | Is sender in recipient's address book? Has recipient replied to this sender before? Historical engagement patterns. |
| Campaign clustering | Fuzzy content hashing (SimHash, MinHash) with cross-recipient counts. Identical bulk mail from a new sender is suspicious. |
Normalization for adversarial robustness
Before extracting features, apply aggressive normalization:
- Remove zero-width Unicode characters.
- Map homoglyphs and lookalikes to canonical ASCII.
- Decode all character encodings and quoted-printable obfuscation.
- Expand URL shorteners and decode redirects.
Model Architecture
Use a tiered approach matching cost to uncertainty.
Tier 0: Rule-based filters
Blocklists, rate limits, authentication policy enforcement (reject if DMARC policy is p=reject and auth fails), and known-bad content hashes. These are fast, interpretable, and serve as both cold-start and fallback.
Tier 1: Gradient-boosted trees
Train on reputation, header, and lightweight content features. Inference takes around 1 ms per message on CPU. This handles the majority of traffic with high confidence.
Tier 2: Transformer-based deep model
A distilled BERT-style encoder processes message text, URLs, and optionally rendered HTML or images. Invoke only when Tier 1 produces uncertain scores (roughly 10–20% of messages). Run on GPU with request batching to stay within latency budget.
Continuous updates
Reputation features update in near real-time via streaming aggregation (e.g., Flink or Spark Streaming). Optionally, maintain a lightweight online logistic layer over hashed features that updates hourly based on recent feedback.
Handling class imbalance
Use weighted loss functions or stratified sampling during training. Train on the post-filter distribution—what actually reaches the model in production—not raw SMTP traffic.
Serving Architecture
SMTP edge
↓
Connection filters (IP rep, rate limits, blocklists) → reject ~50%+
↓
Auth checks (SPF/DKIM/DMARC) + feature assembly ← online feature store (Redis, <5 ms)
↓
Tier 1: GBDT scorer (CPU, ~1 ms)
↓ (uncertain range only)
Tier 2: Transformer scorer (GPU, batched, <50 ms)
↓
Policy engine: calibrated score + segment-specific thresholds
↓
Decision: inbox / spam folder / quarantine / reject
↓
Log: features, model version, score → Kafka → label join, retraining, monitoring
- Stateless scoring services scale horizontally behind a load balancer.
- Shared feature definitions between offline training and online serving prevent skew. Use a feature store or code generation to guarantee consistency.
- Asynchronous rescoring: Delivered mail can be rescanned if a URL later becomes malicious. Implement "zero-hour auto purge" to remove threats post-delivery.
Thresholding and Calibration
- Calibrate model outputs using isotonic regression or Platt scaling on a recent held-out set. Recalibrate after every model retrain so thresholds remain interpretable across versions.
- Choose thresholds by minimizing expected cost:
C_FP · FP + C_FN · FN, whereC_FP ≈ 10–100 × C_FN. In practice, maximize recall subject to a false positive rate on legitimate mail of ≤ 0.1%. - Three-tier decisions:
- High confidence spam: reject at SMTP or quarantine.
- Medium confidence: deliver to spam folder (user-recoverable).
- Low confidence: deliver to inbox.
- Use separate, stricter thresholds for phishing. Relax thresholds for senders the recipient has previously engaged with.
Evaluation Metrics
Offline (on held-out gold set)
- Precision-recall AUC and recall at fixed false positive rates (e.g., 0.1%, 0.5%, 1%).
- ROC-AUC is less informative because the operating point is in the extreme low-FPR regime.
- Cost-weighted loss at the chosen production threshold.
- Slice performance by language, sender type (transactional vs. marketing), and sender age (new vs. established).
Online (in production)
- Spam-in-inbox rate, measured via sampled rater audits and user report-spam rate.
- False positive proxy: "Not spam" button clicks and moves from spam to inbox.
- Legitimate bulk sender complaint rate.
- Inference latency (p50, p99, p99.9).
Adversarial Defenses
| Attack vector | Mitigation |
|---|---|
| Obfuscation (homoglyphs, image-only spam, HTML tricks) | Aggressive normalization; OCR; render-based features |
| Snowshoe spam (low volume per IP/domain) | Graph clustering over shared infrastructure, URL domains, and message templates |
| Probing (testing what gets through) | Don't expose scores or reasons to senders; add slight randomness near thresholds; rate-limit new senders |
| Feedback poisoning (fake "not spam" votes) | Weight reporters by reliability; cap influence per sender; detect anomalous vote bursts |
| Compromised accounts | Detect sudden volume or content shifts from known-good accounts; require re-authentication |
Monitoring and Retraining
Drift detection
Monitor feature distributions, prediction score histograms, and label rates over time. Alert when distribution shift exceeds thresholds.
Retraining cadence
Retrain Tier 1 models weekly or biweekly. Retrain Tier 2 less frequently (monthly) due to cost. Reputation features update continuously.
Safe rollout
- Shadow mode: run new model alongside production, log decisions, compare offline.
- Gradual ramp: route 1%, then 5%, then 25%, then 100% of traffic.
- Guardrail metrics: halt rollout if false positive proxy or latency degrade.
- Instant rollback capability via feature flags.
A/B testing
Randomly assign users to control or treatment. Measure spam-in-inbox rate and user satisfaction. Use two-sided tests to detect regressions.
Privacy and Compliance
- Minimize PII in logs. Hash or tokenize email addresses and message IDs.
- Provide users transparency: show why a message was marked spam (e.g., "sender has low reputation") without exposing internal scores.
- Support user appeals and manual review queues.
- Comply with regional regulations (GDPR, CCPA) regarding data retention and user data access requests.
Common Mistakes
- Ignoring cost asymmetry: Optimizing for accuracy or F1 score instead of explicitly penalizing false positives far more than false negatives.
- Training-serving skew: Using different feature computation logic offline versus online, or training on stale reputation that doesn't match decision-time state.
- Exposing feedback to adversaries: Telling senders their mail was marked spam teaches them how to evade.
- Single-model architecture: Trying to meet latency and accuracy requirements with one model instead of layering fast and slow classifiers.
- Static thresholds: Not recalibrating after model updates, causing threshold semantics to drift.
This design balances accuracy, latency, adversarial robustness, and operational safety. It handles billions of messages daily while keeping false positives extremely low and adapting continuously to evolving threats.