Most antibot systems are a pile of if-statements. Check the user agent. Count the headers. Score the fingerprint. Cross a threshold, get blocked. These checks live server-side, so an attacker can’t read them directly, but they can still map them from the outside.
Static rules produce deterministic outputs: the same input gets the same verdict every time. An attacker sends a request and gets blocked. They change one thing and try again. If they’re still blocked, that variable matters; if they get through, it doesn’t. Repeat until every check is mapped. The block-or-allow output is enough to reverse-engineer the rules through trial and error.
A neural network makes that process much harder.
The Spectrum Problem
A rule says “fewer than 5 headers = bot.” Four headers get blocked, five get allowed, and an attacker finds the edge in two requests.
A neural network outputs a probability. Four headers might produce 0.87, five might produce 0.72, six might produce 0.41. The model evaluates every feature simultaneously, and the output shifts continuously based on combinations the attacker can’t isolate.
Changing one variable also doesn’t predictably change the output. Adding a header might drop the score from 0.87 to 0.72, or it might do nothing, depending on what other headers are present. The model learned feature interactions rather than individual thresholds, so binary searching on a single variable gets the attacker nowhere.
Server-side rules are hidden too, so secrecy isn’t what makes ML harder to debug from the outside. The difference is that its logic can’t be broken down into independent checks.
Adaptability
ML also scales with complexity automatically.
Adding a new signal to a rule-based system means writing new if-statements for every combination. “If TLS fingerprint is wrong AND header order is wrong AND timing is suspicious…” - the number of rules grows combinatorially. You either write a thousand rules or you accept that some combinations slip through.
Adding a new signal to an ML model means adding one feature to the extraction function and retraining. The model works out how the new signal interacts with everything else on its own, learning the decision boundary from the examples you give it.
My training takes 2 seconds on a laptop CPU. The model file is 5KB. When attackers change their tooling, I collect new traffic, retrain, and deploy. The model adapts to patterns I never anticipated.
The Setup
I’m using HTTP headers as features. Client-side fingerprints can be spoofed by JavaScript, whereas headers are sent by the browser before any client code runs, which makes them a useful server-side signal.
The feature extractor pulls 8 signals from each request:
def extract_features(headers_dict, header_order):
features = {
'has_user_agent': float('User-Agent' in headers_dict),
'has_accept': float('Accept' in headers_dict),
'has_accept_language': float('Accept-Language' in headers_dict),
'has_accept_encoding': float('Accept-Encoding' in headers_dict),
'has_connection': float('Connection' in headers_dict),
'has_sec_ch_ua': float('sec-ch-ua' in headers_dict),
'header_count': float(len(headers_dict)),
'header_order_score': float(check_header_order(header_order)),
}
return features
Six presence checks, a header count, and an order score. That last one is interesting.
Header Order as a Signal
Browsers send headers in a predictable order. Chrome sends Host, then Connection, then sec-ch-ua, then the rest. This order is baked into the browser’s networking stack, so a page has no control over it.
Bot libraries use their own orders. Python requests sends User-Agent first. Go’s net/http alphabetizes headers. Curl has its own order. A bot can spoof every header value perfectly and still give itself away through ordering.
EXPECTED_CHROME_ORDER = [
'Host', 'Connection', 'sec-ch-ua', 'sec-ch-ua-mobile',
'sec-ch-ua-platform', 'Upgrade-Insecure-Requests',
'User-Agent', 'Accept', 'Accept-Encoding', 'Accept-Language'
]
The check_header_order function compares every pair of headers against this expected order and returns a score between 0.0 and 1.0. Chrome gets 1.0. A bot with randomized headers gets something like 0.3.
A rule-based system would say “order score below 0.5 = bot.” The ML model learns its own threshold, and more importantly, it learns how order interacts with the other 7 features, which produces a gradient instead of a hard cutoff.
Training Data
You need labeled data. I built a traffic generator that creates two types of entries:
Bots come in four profiles. Empty headers (raw socket scripts). Minimal headers (python requests defaults). Correct headers but wrong order. And partial headers with random subsets missing. Each one mimics a real class of bot tooling I’ve seen in the wild.
Humans get full Chrome headers with realistic values - proper sec-ch-ua, correct Accept-Language, the right number of headers in the right order.
500 of each, shuffled, dumped to a JSONL file. Each entry is 8 numbers and a label.
The Network
Three layers, kept small on purpose since 8 features and 1000 samples don’t justify anything bigger.
class BotDetectorNet(nn.Module):
def __init__(self):
super().__init__()
self.network = nn.Sequential(
nn.Linear(8, 16), # 8 features → 16 neurons
nn.ReLU(),
nn.Linear(16, 8), # 16 → 8
nn.ReLU(),
nn.Linear(8, 1), # 8 → 1 output
nn.Sigmoid() # squash to 0-1 probability
)
Linear layers are the neurons. ReLU is the activation that lets it learn non-linear patterns. Sigmoid at the end gives a probability between 0 (human) and 1 (bot).
The training loop is textbook PyTorch:
for epoch in range(100):
model.train()
predictions = model(X_train).squeeze()
loss = criterion(predictions, y_train)
optimizer.zero_grad()
loss.backward()
optimizer.step()
These few lines do all the learning. The model starts random, sees the data 100 times, and gradually adjusts its weights to minimize prediction error.
Results
Epoch | Loss | Accuracy
------------------------------
10 | 0.5584 | 52.5%
20 | 0.3587 | 99.0%
30 | 0.1083 | 100.0%
...
100 | 0.0004 | 100.0%
100% accuracy on the test set by epoch 30. The model is extremely confident - 0.9998 for a bot request, 0.0002 for a human one.
That’s partly because the training data is clean and the boundary is sharp. Real-world traffic would be messier, but it demonstrates the pipeline.
Wiring It Into Flask
The model saves to a .pth file - a serialized dictionary of all learned weights. Loading it for inference is three lines:
model = BotDetectorNet()
model.load_state_dict(torch.load('model.pth', weights_only=True))
model.eval()
The Flask route calls predict() on every request before any other checks run:
@main.route('/login', methods=['POST'])
def login():
headers_dict = dict(request.headers)
header_order = list(request.headers.keys())
ml_result = predict(headers_dict, header_order)
if ml_result['is_bot']:
bot_request_counts[request.remote_addr] += 1
if bot_request_counts[request.remote_addr] > BOT_THRESHOLD:
return "Access Denied", 403
Note the threshold. The model flags every bot request, but blocking is delayed: the first 10 requests from a flagged IP go through, and request 11 gets blocked.
The Threshold Trick
If you block the first bot request, the attacker knows immediately that something triggered. They change one thing, try again, and see if it passes. Even with ML’s spectrum advantage, immediate blocking hands them a binary signal and a fast feedback loop.
If you let the first 10 through, the attacker thinks everything is fine. Their script works, so they scale up. Then request 11 gets blocked even though nothing changed between request 10 and 11. From their side the system looks non-deterministic, and with no change in their own requests to point to, they have nothing to isolate.
bot_request_counts = defaultdict(int)
BOT_THRESHOLD = 10
if ml_result['is_bot']:
bot_request_counts[request.remote_addr] += 1
if bot_request_counts[request.remote_addr] > BOT_THRESHOLD:
return "Access Denied", 403
This compounds the spectrum advantage. The model’s continuous probability makes it hard to isolate what triggered detection. The delayed threshold makes it hard to isolate when. Together, the attacker has almost nothing to work with.
Testing
Curl sends 4 headers with no sec-ch-ua and wrong order. Chrome sends 10+ with correct order and full client hints. The model distinguishes them trivially:
curl: bot_probability: 0.9345, is_bot: True
Chrome: bot_probability: 0.0, is_bot: False
Running a loop from the terminal shows the threshold:
Request 1-9: 400 (passed ML, failed downstream validation)
Request 10-15: 403 (ML threshold kicked in)
Meanwhile, submitting the login form from Chrome returns 200 - Welcome test!. The model correctly identifies the browser, and the threshold never triggers.
ML + Rules
The ML model runs alongside the existing rule-based BotDetector, and the two complement each other.
Rules catch known patterns with certainty. If navigator.webdriver is true, that’s a bot, and confirming it requires no training data or probability estimate.
ML catches unknown patterns through learned correlations. A stealth bot might get each individual signal close enough to pass the rules while getting the combination slightly wrong. The model picks up on this because it evaluates the full feature vector at once.
An attacker has to beat both systems. Rules provide a hard floor where known bot signatures are always caught. ML adds coverage above that floor, catching things you never wrote rules for, with verdicts that don’t decompose into “which check did I fail.”
Limitations
The 100% accuracy is misleading. The training data has a clean boundary - Chrome humans vs obvious bots. Real traffic includes Firefox (no sec-ch-ua), Safari (different header set), mobile browsers, legitimate API clients, search engine crawlers. A production model needs much more diverse training data and would land somewhere in the 95-98% range.
The feature set is minimal. 8 header signals demonstrates the concept, but production systems would add TLS fingerprinting (JA3/JA4 hashes), request timing patterns, endpoint access patterns, and behavioral signals across sessions. Each new feature makes the model’s decision boundary higher-dimensional, which means more combinations the attacker has to get right simultaneously, none of which they can test in isolation.
And the threshold needs persistence. Right now bot_request_counts is an in-memory dict that resets when the server restarts. Production would use Redis, and would track per-fingerprint rather than just per-IP.
What I Learned
The ML model itself is the easy part: three layers, a short training loop, 2 seconds to train. The hard part is the data pipeline - generating representative training data, labeling correctly, knowing when to retrain.
The insight that stuck with me is about what probing feels like from the attacker’s side. Rules can be just as accurate as ML for known patterns, but they produce cliffs, and an attacker probing them gets clean binary feedback that maps directly to individual checks. ML produces gradients, so the same probing returns a continuous signal that reflects the entire feature space at once. Because the logic can’t be separated into parts, the debugging surface is fundamentally different.
In practice, that can be the difference between an attacker who maps your defenses in an afternoon and one who’s still guessing after a week.
Source: github.com/B9ph0met/antibot-sim