Design a Bot and Spam Detection System
Understanding the Problem
🤖 What is a bot and spam detection system? It's the part of a social platform that decides whether an account is run by an automated program or a spammer, and whether a post, comment or message is spam: scam links, crypto giveaways, fake engagement, the same promo pasted a thousand times. It scores accounts and content as they're created, acts within milliseconds on the obvious cases, and keeps re-scoring as more evidence arrives. Every platform with user-generated content runs one, and the people it targets are paid to get around it.
You'll hear this as "detect bot-generated posts," "design real-time spam detection with ML," or "find fake accounts." These are the same system looked at from two sides. Spam is a property of content. Bots are a property of accounts. In practice you need both: content models catch the spam an account posts, account models catch the bot before its content is even seen, and each feeds the other (a post from a likely bot is more likely spam, an account that keeps posting spam is likely a bot). We'll design one system with an account model and a content model sharing features, labels and serving.
Functional Requirements
We're the integrity team of a social platform with public posts, comments, replies and direct messages.
Core Requirements
- Every new post, comment and DM should get a spam score before it's visible to others, with an action: allow, reduce distribution, hold for review, or block.
- Every account should have a bot score, computed at signup and updated as it behaves, which can trigger a challenge (CAPTCHA, phone verification), rate limits or suspension.
- The system should detect coordinated campaigns: many accounts posting the same or near-identical content.
- User reports and moderator decisions should flow back as labels, and users should be able to appeal.
Below the line (out of scope)
- Harmful content that isn't spam (hate speech, nudity, violence). That's the content moderation problem, with similar plumbing.
- Payment fraud and account takeover (see fraud detection), although a hijacked account posting spam will show up here.
- Ad fraud and fake clicks on ads.
Non-Functional Requirements
Ask for scale. Ours: 300 million daily active users, 200 million posts and comments a day (about 2,300 per second on average, 10,000 per second at peak), 1 billion DMs a day (about 11,600 per second), and 3 million new accounts a day, a large share of them created by bots.
Core Requirements
- The synchronous check on a post or DM should add at most 50 ms at p99 to the write path. Deeper checks can run asynchronously within a minute and remove content retroactively.
- Precision must be high on hard actions. Blocking a real user's post or suspending a real account is costly, so we target precision above 99% for automatic blocks and suspensions; lower-confidence cases get softer actions.
- The system should catch most spam before it gets many views. A spam post that is removed after 10,000 impressions has done its damage.
- The system should adapt to new spam within hours, not weeks, since spammers change tactics quickly.
- It should fail open for posting (we accept more spam briefly) but keep account-creation defenses up.
Below the line (out of scope)
- Per-country legal takedown workflows.
- Encrypted DMs, where the server can't read content. We'd rely only on metadata and behavior there, which is worth mentioning if asked.
Some arithmetic. 1.2 billion items a day is far too many for humans: at 1,000 reviews per moderator per day, even reviewing 0.1% of them takes 1,200 moderators. So nearly every decision must be automatic, and human review is reserved for the uncertain band and for labels. On the model side, 10,000 posts per second with a 50 ms budget rules out a big transformer per post on the sync path; a distilled text model at a few milliseconds on CPU or a batched GPU call is fine, and anything heavier goes async.
A useful framing for your interviewer: spam detection is a cascade. Cheap checks stop the bulk at the door, mid-cost models handle most of the rest in real time, and expensive models and humans work on what's left, after the fact if necessary.
Framing It as an ML Problem
ML Objective
The business goal is a platform where users don't see spam and aren't bothered by bots, without hurting real users. In metrics: spam prevalence (the fraction of viewed content that is spam, measured by sampling and labeling impressions), bot prevalence among active accounts, and the false positive rate on real users (wrongly blocked posts, wrongly suspended accounts, measured through appeals and audits).
The models optimize something narrower:
- Content model:
P(spam | post, author, context). - Account model:
P(bot or spammer | account history, behavior).
We act on calibrated probabilities with per-action thresholds. Note that we target prevalence weighted by views, not counts. Removing one viral scam post seen by a million people matters more than removing a thousand that nobody saw, so the review queue and model thresholds can take predicted reach into account.
Inputs and Outputs
- Content model. Input: the text, links, media hashes, the author's account features, the context (reply to whom, in which community, DM to a stranger or a friend), and recent similar content. Output: spam probability plus a spam type (scam link, commercial promo, engagement bait, repeated content).
- Account model. Input: signup signals (device, IP, email/phone, time to fill the form), profile, behavior over time (posting rate, timing regularity, follow and unfollow patterns), the social graph, and the history of the account's content scores. Output: bot probability, updated on each significant event.
- Campaign detector. Input: recent content and accounts. Output: clusters of accounts and posts that act in a coordinated way, with a cluster-level score.
Choosing the ML Approach
Both models are binary classification (with a multi-class head for spam type). The content model is mostly a text classification problem plus metadata; the account model is tabular classification on behavioral features, where gradient-boosted trees shine. Campaign detection is clustering and graph analysis, because the signal is in the relationship between accounts, not in any one of them.
Anomaly detection plays a smaller role than in fraud, because spam is common enough to get plenty of labels. It's still useful for spotting new bot farms as sudden bursts of similar new accounts.
Data and Labels
Raw data: post and DM events, signup events, session telemetry from clients (with privacy limits), follow and engagement events, all on Kafka, landing in a data lake.
Spam labels are more plentiful than fraud labels but noisier. Sources:
- Moderator decisions on reviewed items. Highest quality, but biased toward what got flagged.
- User reports ("this is spam"). Plentiful and fast, but noisy: people report things they disagree with, and spammers report their competitors. Weight reports by the reporter's historical accuracy.
- Downstream outcomes. An account that is later suspended for spam makes most of its posts strong positives, retroactively.
- Honeypots and spam traps. Accounts nobody real would ever message; anything they receive is likely spam.
- Heuristic labeling functions. "Contains a URL on the known-scam domain list," "identical text from 50+ accounts in an hour," "account created and posted 100 times within 10 minutes." Each is noisy alone; weak supervision (Snorkel-style) combines them, learning each function's accuracy from their agreements, into probabilistic labels at a much larger scale than human review gives.
For negatives, we sample random content from accounts in good standing, plus a stream of random audit samples: a few thousand random posts a day labeled by moderators regardless of score. The audit set is the only unbiased estimate of prevalence and recall, so it's worth its cost.
Imbalance is milder than in fraud. Among items that reach the sync check, spam might be 1-5%, varying a lot by surface (DMs from strangers are much worse than replies between friends). We downsample negatives modestly and correct probabilities, as in the fraud post.
Leakage traps. Don't use features that only exist because the item was flagged (report counts at decision time are fine for re-scoring but must be computed as of the scoring moment). Don't train on "account was suspended" while also using "account age at suspension" as a feature. And split by time and by account, so the same spammer's near-identical posts don't land in both train and test.
If your interviewer asks where labels come from, don't stop at "user reports." The strong answer covers reviewer labels for quality, reports for volume, heuristics with weak supervision for scale, and a random audit sample for honest measurement.
Feature Engineering
Content features
- A text embedding from a multilingual transformer (a distilled XLM-R or a similar small encoder, fine-tuned on spam labels), plus simple counts: links, mentions, hashtags, emojis, phone numbers, all-caps ratio.
- URL features: domain age, domain reputation, redirect chain length, whether the domain is newly seen on the platform, the domain's spam rate over the last day. Many campaigns are really about the link.
- Near-duplicate counts: how many posts in the last hour have a SimHash or MinHash signature close to this one, and from how many distinct accounts. "500 accounts posted this in 10 minutes" is a very strong signal.
- Media hashes: perceptual hashes (PDQ-style) of images matched against known spam images.
Account features
- Age, email and phone verification, profile completeness, profile photo reused elsewhere, username pattern (random strings, name+digits).
- Activity: posts per hour, follows per hour, the fraction of posts with links, the fraction of replies to strangers, DMs sent to non-followers.
- Timing regularity: humans post in bursts with long gaps and a daily rhythm; scripts often post at near-constant intervals or around the clock. The entropy of inter-event gaps and the fraction of activity in the user's local night are cheap, effective features.
- History of the account's content scores (mean spam score of the last 50 posts), reports received, past enforcement.
Device, network and client
- IP and ASN reputation, datacenter vs residential vs mobile carrier, proxy/VPN flags, how many accounts used this IP or device today.
- Client integrity: did the request come from our app with a valid attestation (Play Integrity, App Attest), from a browser with a normal fingerprint, or straight from an API with no client at all?
- Session telemetry where allowed: time from opening the composer to posting, paste vs type, scroll behavior. Bots often post 200 ms after loading the page.
Graph features
- Follower/following ratio, how many followers are themselves likely bots, reciprocity, how many accounts in this account's signup cohort (same IP, device, hour) follow each other.
Context features
- Surface (post, reply, DM), relationship to the recipient (stranger, mutual follow), community rules and spam level.
Real-time vs batch. Rate counters, near-duplicate counts and per-IP account counts must be real-time (seconds), maintained by Flink or directly in Redis by the scoring service. Account aggregates update near-line (minutes). Graph features, domain reputation and the text model's fine-tuning run daily. A feature store holds definitions, the online store serves them, and the scoring service logs the vector it used so training sees the same values.
Modeling
Bad Solution: Blocklists and Rate Limits
Approach
Block posts with words or domains on a list, cap accounts at N posts per minute, and require a CAPTCHA at signup.
Challenges
Every platform needs these, but on their own they fail fast. Spammers misspell words ("fr33 cr7pto"), rotate domains daily, stay just below the rate limit, and pay CAPTCHA-solving services a fraction of a cent per solve. Keyword lists also hit real users (a post warning about a crypto scam contains the same words as the scam).
Good Solution: A Text Classifier Plus an Account GBDT
Approach
Train two models:
- A content classifier: a fine-tuned small transformer on post text, its output combined with metadata (links, URL reputation, near-duplicate count) in a light model. Logistic regression on TF-IDF n-grams is a reasonable baseline and is surprisingly strong for spam.
- An account model: a GBDT (LightGBM/XGBoost) over account, behavior, network and graph features, re-scored on signup, on each post, and periodically.
The content decision uses both: the account's bot score is a feature of the content model.
Challenges
It treats each post on its own. A campaign of 1,000 accounts each posting one slightly varied message looks harmless one at a time. And modern spam text is increasingly generated by LLMs: fluent, varied and grammatical, which weakens text-only features. The text model also costs real compute at 10,000 posts per second if it's large.
Great Solution: A Cascade With Campaign Detection
Approach
Organize detection as a cascade, from cheapest to most expensive, and add a cluster-level view:
- Stage 0, at the edge (sub-millisecond): rate limits, IP/ASN blocklists, exact-hash matches against known spam text and images, known-bad URLs. This stops the crudest bulk.
- Stage 1, synchronous (≤ 50 ms): a GBDT that takes account features, real-time counters, URL reputation, near-duplicate counts and a distilled text embedding (a small encoder, a few milliseconds on CPU via ONNX Runtime). It decides allow / reduce / hold / block.
- Stage 2, asynchronous (seconds to a minute): heavier models on anything not clearly clean: a larger multilingual transformer, image and OCR models for spam in images, an LLM-based classifier for the ambiguous cases, and the campaign detector. These can remove content or downgrade an account retroactively.
- Stage 3, humans: the uncertain band, ranked by predicted reach, plus appeals and the random audit sample.
The campaign detector clusters recent posts by MinHash LSH on text and by shared URLs, and clusters accounts by shared signup signals (IP, device, creation time, profile template). A cluster that's large, young and fast gets a cluster-level score, and every member inherits it. This catches campaigns where no single post is convincing.
Challenges
Async removal means some spam is visible for a minute. We limit the damage by holding distribution: a post with a borderline Stage 1 score is visible to its author and close connections but not pushed into feeds, search or recommendations until Stage 2 clears it. The cascade has more models to retrain and monitor, so ownership and shared tooling matter.
Against LLM-written spam, shift weight from what is said to who says it, how and with whom: account age, client integrity, timing, network, coordination. A fluent paragraph is cheap to generate; a thousand aged accounts with real-looking behavior are not.
Training
Losses. Binary cross-entropy for both models, with a multi-class softmax head for spam type on the content model. With weak-supervision labels we train on soft labels (the probability from the label model) or weight each example by label confidence.
Negative sampling. Random negatives from good-standing accounts, plus hard negatives: real posts that look spammy (legitimate sellers, posts about scams, enthusiastic fans posting many links). Hard negatives are what keep false positives down; mine them from overturned appeals and false positives found in audits.
Text model. Fine-tune a pretrained multilingual encoder on a few million labeled posts, then distill it into a smaller student for Stage 1, trained to match the teacher's logits on a large unlabeled sample. The teacher stays in Stage 2.
Cadence. Spam shifts daily. Retrain the GBDT daily on a sliding 30-day window with fresh labels; fine-tune the text model weekly; refresh URL and domain reputation hourly. Between retrains, analysts add rules and blocklist entries, which also become labeling functions so their knowledge reaches the next model.
Online learning is tempting but risky here: spammers can poison a model that learns from live reports by mass-reporting legitimate content. Prefer frequent batch retrains with label-quality checks.
Evaluation
Offline Metrics
- Precision at the auto-block threshold and recall at that precision. Hard actions need 99%+ precision, so the number that matters is how much spam we catch while keeping it.
- PR-AUC for the overall ranking, per surface (posts, replies, DMs) and per language.
- View-weighted recall: the share of spam impressions that would have been prevented, using logged impression counts.
- Calibration, since thresholds differ by action and surface.
- Evaluation on the audit set, not just on reviewed items, because reviewed items are a biased sample of hard cases.
Online Metrics and A/B Testing
- Spam prevalence in feeds, measured by labeling a random sample of impressions daily.
- False positive rate: appeals overturned per thousand actions, and audits of auto-actions.
- Report rate per thousand impressions, time to action for spam that does get through.
- Bot share of new signups that survive 30 days.
A/B testing is tricky because spammers aren't randomized users: one campaign hits both arms. Randomize by content author and keep tests short, or run the challenger in shadow mode and compare decisions on the same traffic, then label the disagreements. A holdback of a small percentage of borderline traffic from a new enforcement action (still caught by the old rules) lets you measure its effect on prevalence and engagement over time.
Serving
The sync check sits in the write path of every post and DM. The Integrity Service fetches features, runs Stage 1, returns an action, and emits an event for Stage 2.
Latency budget for the sync check, p99:
| Step | Budget |
|---|---|
| Stage 0 checks (hash lookups, blocklists, rate limits in Redis) | 3 ms |
| Online feature fetch (account, IP, URL, counters; parallel) | 12 ms |
| SimHash near-duplicate lookup (LSH buckets in Redis) | 5 ms (parallel) |
| Distilled text encoder on CPU (ONNX Runtime, 128 tokens) | 8 ms |
| GBDT inference | 1 ms |
| Policy and response | 3 ms |
| Headroom | ~20 ms |
At 21,600 writes per second at peak (posts plus DMs), a distilled encoder at around 8 ms of CPU time per item needs on the order of 200 cores just for text, which is a modest fleet. Running the full teacher transformer on the sync path would need GPUs and still blow the budget at the tail, which is why it lives in Stage 2.
Account scoring is mostly event-driven and asynchronous: the account model re-scores on signup, on every Nth post, on reports and on network changes, and writes the score to the online store, where Stage 1 reads it. A nightly batch re-scores all active accounts with the full feature set and the latest graph features, catching slow bots that never trip a real-time threshold.
Graceful degradation. If the text encoder is slow, Stage 1 runs without the embedding (the GBDT was trained with it sometimes missing). If the Integrity Service is down, posts are accepted with distribution held, and Stage 2 catches up from Kafka.
Potential Deep Dives
1) How do we detect coordinated campaigns?
Bad Solution: Exact-Duplicate Counting
Approach
Hash the normalized text and count identical hashes in the last hour. Over a threshold, block.
Challenges
Spammers add a random emoji, swap synonyms or have an LLM rewrite each post. Exact hashes miss all of that.
Good Solution: Near-Duplicate Detection With MinHash or SimHash
Approach
Compute a MinHash signature over word shingles (or a SimHash over tokens) and index it with locality-sensitive hashing in Redis: each post goes into a handful of LSH buckets, and posts sharing a bucket are near-duplicates with high probability. The count of near-duplicates and of distinct accounts behind them becomes a real-time feature. For paraphrases that share few words, embed the text and use approximate nearest-neighbor search (Faiss or an HNSW index over the last few hours of posts) in Stage 2. The same machinery is the core of the duplicate detection problem.
Challenges
It only finds content similarity. A campaign whose accounts post different text but all link the same new domain, or all follow and like the same target, isn't caught.
Great Solution: Account Graph Clustering
Approach
Build a graph of recent accounts where edges mean shared signals: same device or IP subnet at signup, created within minutes of each other, same profile template, posting near-duplicate content, linking the same new domain, engaging with the same targets in the same minutes. Run connected components or a community detection algorithm (Louvain, label propagation) every few minutes over a sliding window in Flink or Spark Structured Streaming. Score each cluster on size, account age, synchrony and content scores, and push the cluster score back to each member account.
Challenges
Real groups also coordinate: a fan club, a company's employees, a protest. Cluster scores need careful thresholds and human review before mass suspension, and the strongest edges should be the hard-to-fake ones (device, signup timing) rather than "liked the same post."
2) How do we stop bots before they post?
The cheapest spam to handle is from an account that never got created. Score signup with a dedicated model: device and IP reputation, client attestation, email domain (disposable domains), phone number type (VoIP numbers are cheap for bots), form timing, and how many accounts this device or IP created today. Then apply graduated friction:
- Low risk: create normally.
- Medium risk: CAPTCHA or a proof-of-work challenge, and a "new account" status with tight limits (no links, no DMs to strangers for a few days).
- High risk: require phone verification, or block.
Friction is economic: each step raises the spammer's cost per account. Phone verification with real SIMs costs them far more than a CAPTCHA solve. New-account limits also reduce what a bot can do before the account model has seen enough behavior.
3) How do we keep spammers from learning our thresholds?
Spammers probe: they post variants and watch which ones survive. Make that hard:
- Don't tell them. For borderline cases, reduce distribution silently instead of rejecting with an error, so the author can't tell what was caught. Hard blocks are reserved for clear cases, where the signal to them matters less.
- Delay enforcement on accounts in a suspected campaign, then act on the whole cluster at once, so they can't tell which signal gave them away.
- Randomize a small part of borderline decisions and refresh models daily, so a variant that worked yesterday may not work today.
- Watch for probing: accounts whose posts repeatedly score just under a threshold are themselves suspicious.
Being able to explain the trade-off between transparency and robustness wins points: real users deserve to know why a post was removed (and to appeal), while spammers shouldn't get a precise oracle. Most platforms tell users the policy, not the model's score.
4) How do we protect real users from false positives?
At 1.2 billion items a day, a 0.1% false positive rate is 1.2 million wrongly treated items daily. Keep it down with:
- An action ladder. Map score bands to the gentlest action that works: label or collapse, reduce distribution, hold for review, block, and only then suspend. Suspensions need a higher bar and usually an account-level score, not one post.
- Context-aware thresholds. A link in a DM to a stranger is riskier than the same link in a reply to a friend. Thresholds per surface and relationship.
- Trusted signals. Old accounts with a long clean history, verified accounts and mutual connections get more benefit of the doubt, which is exactly what hijacked accounts exploit, so pair it with ATO signals.
- Appeals as labels. Overturned appeals become high-value hard negatives for the next retrain, and a spike in appeals after a model launch is an automatic rollback trigger.
5) How do we monitor for drift and new attacks?
Monitor feature distributions (PSI) and score distributions per surface and language, the share of traffic in each action band, the report rate, and prevalence from the daily impression sample. A new campaign usually shows up first as a burst of new accounts from a new ASN or a new domain spiking in link counts, both of which are cheap to alarm on. When something new appears, analysts add a rule and label examples, and the next daily retrain picks them up.
What is Expected at Each Level?
Mid-level
You should separate account-level from content-level detection, propose a text classifier and a GBDT on account and behavior features, and explain why keyword lists alone fail. You should know that labels come from reports and moderators, that metrics should be precision and recall rather than accuracy, and that the sync check has to be fast, with heavier work async.
Senior
You should design the cascade (edge filters, fast model, async heavy models, humans) with a latency budget, and talk about near-duplicate detection for campaigns. Expect to discuss label quality (noisy reports, weak supervision, the audit sample), hard negatives, distillation for the sync path, retraining cadence, and an action ladder that keeps false positives low.
Staff+
You should frame it as an adversarial, economic problem: raise the attacker's cost per account and per post, and don't hand them an oracle. Expect to drive graph-based campaign detection, signup friction, view-weighted prevalence as the north-star metric, the transparency vs robustness trade-off, and how LLM-written spam shifts value from content features to behavioral and network ones. Strong candidates also cover operations: shadow launches, holdbacks, rollback on appeal spikes, and how rules and models work together.