Building a Low-Latency Email Abuse Filter with ML
Machine LearningModel answerLast updated
Design a production ML pipeline that scores inbound mail within a tight latency budget, keeps hard-block false positives very low, and stays robust as attackers adapt.
You are asked to design a machine-learning system that classifies inbound email as unwanted or legitimate, and to take an enforcement action on each message before delivery.
Requirements
- Synchronous scoring with p99 latency under 50 ms.
- Hard blocks must reach precision of at least 98%. Wrongly blocking a password reset or an invoice is much worse than letting a promotional message through. Recall should still be as high as possible.
- Senders are adversarial and change tactics within hours or days.
- Possible actions: block, quarantine, tag/move to spam folder, deliver.
Cover the following in your answer
- Framing and labels: ham vs. spam, how to treat graymail (bulk mail the user signed up for), noisy or weak labels, and abuse reports that arrive late.
- Features: text n-grams, sender/domain/IP reputation, URL signals, MIME structure, lightweight embeddings, and how you prevent leakage (future information, reply and forward chains).
- Model and serving: compare logistic regression, gradient-boosted trees and a compact transformer; explain calibration and how you choose thresholds for each action.
- Training pipeline: sampling to cope with class prevalence, retraining cadence, and drift detection (stability metrics, canaries).
- Evaluation: offline metrics (PR-AUC, calibrated precision and recall at business thresholds) and online evaluation (A/B design, guardrails, holdouts).
- Feedback and safety: appeals, human review, bias, privacy and PII handling.
- Cost, reliability and rollback.
Finish by naming the three failure modes you worry about most and a concrete mitigation for each.
Hints
Hint 1
Start by stating assumptions (traffic volume, spam prevalence after network-level filtering, a per-stage latency budget). Then separate the problem into a cheap early gate, a main model, and an expensive model used only on uncertain messages.
Hint 2
Most leakage and evaluation mistakes come from time: compute features as of receive time, wait for labels to mature before training, split by time, and keep campaigns or sender clusters together in one split.
Hint 3
Thresholds should come from a calibrated model on unsampled recent data, using a confidence bound on precision for hard blocks. Treat thresholds as configuration so you can change or roll them back without redeploying the model.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions and budget
Assume about 1B messages/day, roughly 12k QPS on average and about 40k QPS at peak. Much of the raw traffic is rejected at the connection level, so the content classifier might see around 15% spam. The 50 ms p99 budget could be split as: parsing 5 ms, feature fetch 10 ms, model 15 ms, headroom 20 ms. The API is synchronous from the mail transfer agent, returning a spam probability, a graymail probability, an action, reason codes and a model version. Slow enrichment (OCR, URL detonation) runs asynchronously and can re-score after delivery.
1. Framing and labels
Use multi-task outputs: spam, phishing/malware, and graymail. Graymail is not spam, so it is routed to a promotions view and never blocked. Folding it into the spam label inflates false positives.
Label sources, strongest to weakest: analyst labels, spam traps and honeypots, authenticated-sender allowlists, user "report spam" / "not spam" actions, and heuristics (blocklists, campaign clustering). Combine them with a weak-supervision label model or per-source reliability weights. Weight user reports by reporter reputation so a few heavy reporters or attackers cannot steer the model. Use confident-learning style checks to surface likely mislabels.
Reports arrive late, so use a maturation window (say 7 days) and train only on older examples. Meanwhile use fast, high-precision sources (traps, analysts) for quick updates. Remember that recent "ham" is partly unreported spam.
2. Features and leakage
- Content: hashed character n-grams (3-5) resist obfuscation such as "v1agra"; add word uni/bigrams after Unicode and homoglyph normalization.
- Reputation: sender, domain and IP volume, complaint and bounce rates over 1h/1d/30d; domain age; SPF/DKIM/DMARC alignment; ASN and residential-IP flags.
- URLs: count, redirect depth, domain age, lexical features (entropy, IP literals, brand lookalikes), anchor-text vs. href mismatch.
- MIME: part types, image-to-text ratio, attachment types, hidden text and zero-width tricks.
- Embeddings and behavior: a 64-128 dim distilled sentence embedding, a MinHash/SimHash campaign ID with cluster-level spam rate, and recipient context (first contact, sender in contacts).
Leakage controls:
- A point-in-time feature store, so a sender's later blocklisting does not appear in training features.
- No post-delivery signals (opens, replies, reports) as inputs.
- Time-based splits (for example train weeks 1-8, validate week 9, test week 10).
- Group splits by campaign or sender cluster so near-duplicates do not straddle splits.
- Strip or separately featurize quoted reply/forward content, so "forwarded to the abuse mailbox" does not become a spam signal.
3. Model, serving, calibration, thresholds
Use a cascade:
- Connection-level gate: IP blocklists, rate limits, authentication failures; under 1 ms.
- Main model: gradient-boosted trees on reputation, URL and MIME features plus the output of a hashed n-gram logistic regression. About 2-5 ms on CPU. The LR retrains often and adapts quickly; the trees capture nonlinear reputation interactions.
- Uncertain band only (~10%): a distilled int8 transformer (about 4 layers, 256 tokens, ~8 ms) for paraphrased or semantic spam.
Running a transformer on everything wastes compute; LR alone underfits reputation interactions.
Calibration: fit isotonic or Platt scaling on a recent, unsampled time slice, and check segments (for example locale) for diverging reliability curves.
Thresholds come from the calibrated PR curve on the latest test week:
- Block: lowest threshold where the lower 95% confidence bound on precision is at least 98%, plus corroborating evidence (poor reputation or a known campaign). Never block an authenticated, well-reputed sender on content alone.
- Quarantine: about 90% precision, recoverable via a digest.
- Tag/spam folder: a higher-recall threshold.
Keep thresholds in config so they can be changed without a deploy.
4. Training, sampling, drift
Pipeline: event logs, point-in-time join, label join after maturation, dedup, train, evaluate, registry. Retrain LR hourly or daily, trees daily, transformer weekly; reputation features update continuously.
Downsample easy ham, oversample hard negatives (graymail, transactional mail), and mine recent errors. If negatives are sampled at rate w, correct with p = p'/(p' + (1-p')/w), then recalibrate on unsampled data.
Drift: PSI on top features and on the score distribution (alert around 0.2); daily action rates per segment; label-free proxies such as "not spam" rescue rate and report rate on delivered mail. Canaries are golden sets run continuously through production: known transactional ham (banks, airlines), known spam, and synthetic probes. Any change pages on-call.
5. Evaluation
Offline: PR-AUC, precision with confidence intervals at each action threshold, recall at fixed precision, expected cost with FP cost far above FN cost, reliability diagrams and ECE, slices (language, new vs. established sender, transactional vs. bulk), and a backtest on a future week.
Online: shadow mode first, then an A/B test randomized by recipient. Primary metrics are user spam reports on inbox mail (FN proxy), rescues from spam (FP proxy) and reviewed precision of blocks. Guardrails cover complaint rates, delivery rate of known-good transactional mail and latency. Keep a small long-lived holdout (with safe, non-blocking treatment) to measure true recall and drift, and use sampled human review to estimate precision of blocked mail.
6. Feedback loops and safety
Beware selection bias: blocked mail never gets user feedback. Mitigate by reviewing a random sample of blocked and quarantined mail and by exploration on low-risk segments. Provide an appeals path and quarantine digests; route borderline high-value cases (for example mail from sender domains with large legitimate volume) to human review. Feed confirmed outcomes back as high-quality labels. For privacy, minimize retention, hash or tokenize PII, restrict raw content access, and audit access. For bias, monitor error rates by language and region, since non-English or small-sender mail is often over-blocked.
7. Cost, reliability, rollback
Cost is dominated by feature fetches and the transformer, so cache reputation features, restrict the transformer to the uncertain band, and use int8 CPU inference. For reliability, fail open to a simple rules/LR fallback when the feature store or model times out (with a conservative "deliver or tag" action rather than block). Deploy via shadow, canary percentage, then full rollout, with versioned models and thresholds so rollback is a config flip. Auto-rollback on canary or guardrail breach.
Top three failure modes
- False-positive spike on legitimate bulk or transactional mail (a new bank template, a feature outage). Mitigate with golden-set canaries, the corroboration requirement for blocks, allowlisting for authenticated senders, a quick threshold rollback, and fail-open fallbacks.
- Adversarial adaptation and drift (obfuscation, new campaigns, probing). Mitigate with char n-grams and normalization, fast-updating LR and reputation features, campaign clustering, hard-negative mining, rate-limiting feedback to attackers (delayed or uniform responses), and PSI/action-rate alerts.
- Corrupted or biased feedback loops (label poisoning by mass reports, missing labels on blocked mail, delayed labels). Mitigate with reporter-reputation weighting, a maturation window, random review of blocked mail, and holdouts for unbiased evaluation.
Common mistakes: random train/test splits, calibrating on sampled data, treating graymail as spam, using post-delivery signals as features, and picking thresholds from point estimates rather than confidence bounds.