How to Detect Bot Traffic Using ASN Patterns? (Python & Node API Implementation)
For backend engineers, bot detection is often a cat-and-mouse game involving rate limits, WAF rules, and behavioral analysis. However, one of the most reliable and low-latency signals for identifying automated traffic is the Autonomous System Number (ASN).
While individual IP addresses are volatile and easily rotated, the ASN provides context about the network infrastructure itself. By analyzing ASN patterns, you can differentiate between a user browsing from a local ISP and a scraper script running on a cloud provider. This article explains how ASN patterns can be used to detect bot traffic, how the approach works internally, its limitations, and how to implement it using an IP intelligence API in production systems.

What is an ASN?
An Autonomous System (AS) is a large network or group of networks managed by a single entity, such as an Internet Service Provider (ISP), a university, or a cloud corporation. Each AS is assigned a unique ASN, a 16-bit or 32-bit number used in Border Gateway Protocol (BGP) routing to identify the network on the global internet.
For security engineering, the ASN is more descriptive than the IP address. If an IP belongs to AS16509 (Amazon.com), you know the traffic originates from a data center. If it belongs to AS7922 (Comcast), it is likely a residential user.
Examples of ASN operators:
| ASN Type | Example Operators |
|---|---|
| Cloud / Hosting | AWS, Google Cloud, Azure, DigitalOcean |
| Residential ISPs | Comcast, Airtel, Jio, AT&T |
| Enterprise Networks | Banks, universities, corporations |
| Mobile Networks | Vodafone, Verizon Wireless |
Why Bots Cluster Around Certain ASNs
Most automated traffic originates from environments that are:
- Cheap to provision
- Programmatically controllable
- Have stable IP ranges
These traits are typical of cloud hosting ASNs, not residential ISPs. As a result, a significant portion of malicious or automated traffic can be traced back to a small subset of ASNs.
This makes ASN-based filtering a powerful early-stage signal for bot detection.
Why ASN Patterns Matter for Bot Detection
Most bot operators do not run scripts from their home Wi-Fi. They use infrastructure that offers high bandwidth, low latency, and the ability to scale. This creates distinct "network signatures."
1. The Hosting vs. Residential Divide
The most common pattern is traffic originating from hosting providers (e.g., DigitalOcean, AWS, Hetzner) attempting to access consumer-facing endpoints like /login or /checkout. While some legitimate users use VPNs hosted on these networks, a high concentration of hosting-based traffic on a "human-only" route is a primary indicator of automation.
2. ASN "Clustering"
Bots often operate in clusters. A coordinated credential stuffing attack might rotate through 5,000 different IPv4 addresses, but all those IPs might belong to just two or three ASNs associated with cheap VPS providers. Blocking or flagging based on the ASN allows you to neutralize the entire block of infrastructure rather than playing "whack-a-mole" with individual IPs.
3. Geopolitical Inconsistencies
If your SaaS primarily serves users in the UK, but you see a spike in traffic from a Russian or Chinese ASN known for hosting "bulletproof" servers, the ASN provides immediate geographic and reputational context that a simple IP check might miss.
How ASN-Based Bot Detection Works
High-Level Flow
- Extract the client IP from the incoming request
- Look up ASN metadata for that IP
- Evaluate the ASN against known patterns
- Decide whether to allow, challenge, rate-limit, or block
What ASN Metadata Tells You
Our IP intelligence API typically provides:
- ASN number (e.g., AS15169)
- ASN organization name
- Network type (hosting, isp, mobile)
- Country and region context
- Abuser Score
From this data, you can infer whether traffic is likely to be:
- Human-driven (residential / mobile ASN)
- Automated or scripted (hosting / data center ASN)
- Abuse history of any ASN
Real-World Use Cases
Credential Stuffing Prevention
Attackers use botnets to test stolen passwords. These bots frequently use residential proxies to mimic human IPs. However, residential proxy providers often aggregate traffic through specific ASNs. By monitoring the "Login Failure Rate" per ASN, you can detect an attack even if no single IP address hits your rate limit.
Preventing Content Scraping
If you run a real estate or e-commerce platform, scrapers are a constant threat. Most scrapers run on headless browsers in data centers. By implementing a rule that forces a CAPTCHA for any request originating from a "Hosting" category ASN, you can significantly increase the cost for scrapers while leaving 99% of your actual customers unaffected.
Ad Fraud Mitigation
In the world of SaaS and marketing, "fake clicks" waste budget. Bots clicking on ads typically originate from data center ASNs. Filtering your conversion logs by ASN helps identify which traffic sources are delivering high-quality human leads versus automated "click farms."
Common Mistakes and Pitfalls
- Over-blocking Legitimate VPNs: Many privacy-conscious users use VPNs (like Mullvad or NordVPN). These VPNs often exit through ASNs owned by hosting companies (like M247 or Datacamp). If you block these ASNs entirely, you may alienate legitimate users.
- Ignoring IPv6: Bot operators are increasingly moving to IPv6 because the address space is massive and often less monitored. Ensure your ASN lookup tool supports both IPv4 and IPv6.
- Stale Data: ASN ownership can change, and new data centers are commissioned daily. Using a local, static CSV file for ASN lookups will quickly become inaccurate. Always use a live API or a frequently updated database.
Practical Implementation Using IP Intelligence
Example HTTP Request
curl "https://api.ip2geoapi.com/ip/8.8.8.8?key=YOUR_API_KEY"
API Response (showing only ASN part):
//---other response fields
.
.
"asDetails": {
"asn": 15169,
"abuser_score": "0.001 (Low)",
"descr": "GOOGLE, US",
"country": "us",
"active": true,
"org": "Google LLC",
"domain": "google.com",
"abuse": "[email protected]",
"type": "hosting",
"created": "2000-03-30",
"updated": "2012-02-24",
"rir": "ARIN"
}
.
.
//---other response fields
Simple Decision Logic:
if asn.type == "hosting":
flag_as_high_risk()
elif asn.type == "isp" or asn.type == "mobile":
allow_request()
This logic is intentionally simple. In production systems, ASN signals are typically combined with rate limits, headers, and behavioral metrics.
Detecting Bot Traffic Using ASN & IP-API: Python & Flask Implementation
from flask import Flask, request, jsonify
import requests
import ipaddress
app = Flask(__name__)
API_KEY = "YOUR_API_KEY"
API_URL = "https://api.ip2geoapi.com/ip/{ip}?key={key}"
def get_client_ip(req):
"""
Extract client IP from Flask request.
Priority: X-Forwarded-For → X-Real-IP → remote_addr
"""
xff = req.headers.get("X-Forwarded-For")
if xff:
ip = xff.split(",")[0].strip()
if is_valid_ip(ip):
return ip
xri = req.headers.get("X-Real-IP")
if xri and is_valid_ip(xri):
return xri
if is_valid_ip(req.remote_addr):
return req.remote_addr
return None
def is_valid_ip(ip):
try:
ipaddress.ip_address(ip)
return True
except ValueError:
return False
def lookup_ip(ip):
resp = requests.get(
API_URL.format(ip=ip, key=API_KEY),
timeout=2
)
resp.raise_for_status()
return resp.json()
@app.route("/protected")
def protected():
client_ip = get_client_ip(request)
if not client_ip:
return jsonify({"allow": False, "reason": "invalid_ip"}), 403
intel = lookup_ip(client_ip)
asn = intel.get("asn", {})
network_type = asn.get("type")
if network_type == "hosting":
return jsonify({
"allow": False,
"reason": "hosting_asn",
"ip": client_ip,
"asn": asn.get("number"),
"org": asn.get("organization"),
}), 403
return jsonify({
"allow": True,
"ip": client_ip,
"asn": asn.get("number"),
"org": asn.get("organization"),
})
if __name__ == "__main__":
app.run()
Decision logic:
| ASN Type | Action |
|---|---|
| hosting | block / challenge |
| isp / mobile | allow |
Tip: You can make use of abuser_score field to make it more efficient. If you want to block traffic solely on hosting ASN, you can use security.isHosting field too.
Node Implementation - Simple Express Bot Detection Using ASN
const express = require("express");
const axios = require("axios");
const net = require("net");
const app = express();
const API_KEY = "YOUR_API_KEY";
const API_URL = "https://api.ip2geoapi.com/ip/%s?key=%s";
function isValidIP(ip) {
return net.isIP(ip) !== 0;
}
function getClientIP(req) {
const xff = req.headers["x-forwarded-for"];
if (xff) {
const ip = xff.split(",")[0].trim();
if (isValidIP(ip)) return ip;
}
const xri = req.headers["x-real-ip"];
if (xri && isValidIP(xri)) return xri;
if (isValidIP(req.socket.remoteAddress)) {
return req.socket.remoteAddress;
}
return null;
}
async function lookupIP(ip) {
const url = API_URL
.replace("%s", ip)
.replace("%s", API_KEY);
const res = await axios.get(url, { timeout: 2000 });
return res.data;
}
app.get("/protected", async (req, res) => {
try {
const clientIP = getClientIP(req);
if (!clientIP) {
return res.status(403).json({ allow: false, reason: "invalid_ip" });
}
const intel = await lookupIP(clientIP);
const asn = intel.asn || {};
const networkType = asn.type;
if (networkType === "hosting") {
return res.status(403).json({
allow: false,
reason: "hosting_asn",
ip: clientIP,
asn: asn.number,
org: asn.organization,
});
}
return res.json({
allow: true,
ip: clientIP,
asn: asn.number,
org: asn.organization,
});
} catch (err) {
return res.status(500).json({ allow: false, reason: "lookup_failed" });
}
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
How ip2geoapi.com Can Help
To perform these checks effectively, you need a high-speed, reliable source of truth. ip2geoapi.com provides precise IP intelligence that includes ASN, ISP, and organization data in a single millisecond-response.
We understand the needs of developers and startups, which is why we offer a free tier of 100,000 requests per month. This is one of the most generous quotas in the industry, allowing you to implement robust bot detection without immediate overhead. Our API is designed for high-concurrency environments, ensuring your backend stays fast while staying secure.
Conclusion
ASN-based detection is a practical, low-cost method for identifying bot traffic patterns. By understanding which networks requests originate from, backend systems gain valuable context before deeper analysis.
Key takeaways:
- Bots frequently operate from hosting and data center ASNs
- ASN metadata is easy to integrate and computationally cheap
- False positives exist and must be handled carefully
- Combining ASN signals with other checks yields the best results
With accurate ASN intelligence from services like ip2geoapi.com, teams can significantly reduce bot traffic while maintaining a smooth experience for legitimate users.