IP Intelligence at the Edge: Real-Time Risk Decisions with Cloudflare Workers, WAF, and API Gateways
Running IP risk checks in your application server adds latency to every request. Moving those checks to the edge — Cloudflare Workers, WAF rules, or API gateway policies — means you enforce geography-based access control, block VPN and proxy traffic, and apply risk scores before the request ever reaches your origin. The technical challenge is doing all of this in under 50ms per request, including the external API call.
Edge IP Intelligence: Key Metrics
Why Move IP Intelligence to the Edge
The standard architecture for IP-based risk evaluation looks like this: user sends a request, your application server receives it, extracts the IP, calls an external geolocation API, waits 30-200ms for the response, then makes an allow/block decision. This works, but it has three problems:
Latency compounds through your stack
The external API call sits on the critical path of every request. If the API takes 50ms and your server needs 20ms to process the result, every protected endpoint adds 70ms of latency. Under load, this compounds with connection pooling limits and DNS resolution.
Bad traffic reaches your origin
When your application server makes the allow/block decision, the request has already traversed your CDN, hit your load balancer, and consumed a connection on your origin. Blocking at the edge means obvious threats — VPN traffic from sanctioned regions, requests from data center IPs, known proxy networks — never touch your infrastructure at all.
Scaling becomes an API-volume problem
If every user request triggers an API call, your lookup volume scales linearly with traffic. Edge enforcement lets you short-circuit most requests with a single check, reserving deeper analysis for the traffic that actually needs it.
Three Edge Enforcement Patterns
There is no single "right" architecture. The best approach depends on your existing infrastructure, your latency budget, and the depth of IP analysis you need. Here are three patterns, from simplest to most sophisticated:
1WAF Rule with IP Intelligence Header
Use your CDN or WAF to make the IP lookup, attach the result as a request header, and write allow/block rules based on those headers. This works well when your WAF supports external API calls or when you can push IP reputation data into the WAF configuration.
# Cloudflare WAF Rule (via API)
# Block traffic from flagged countries + VPN
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/rulesets" \
-H "Authorization: Bearer TOKEN" \
-d '{
"name": "block-vpn-high-risk",
"kind": "zone",
"phase": "http_request_firewall_custom",
"rules": [{
"expression": "ip.geoip.country in {\"XX\" \"YY\"} and cf.threat_score gt 20",
"action": "block",
"description": "Block VPN traffic from high-risk regions"
}]
}'Limitation: WAF-native geolocation is less precise than dedicated IP intelligence APIs and typically lacks VPN/proxy classification, threat levels, and ASN intelligence. For stronger signals, you need the API-enrichment approach below.
2Cloudflare Workers with API Enrichment
Deploy a Cloudflare Worker that calls your IP intelligence API on every request, evaluates the response against your risk policy, and returns allow/block/challenge decisions. This gives you full access to VPN detection, threat levels, ASN data, and ISP intelligence — not just the WAF's built-in geolocation.
// Cloudflare Worker: Edge IP risk evaluation
export default {
async fetch(request: Request): Promise<Response> {
const clientIp = request.headers.get('cf-connecting-ip');
if (!clientIp) return fetch(request);
const apiKey = 'YOUR_API_KEY';
const apiBase = 'https://ip-info.app/api/v1/geolocate';
try {
const resp = await fetch(
`${apiBase}/${clientIp}`,
{ headers: { 'x-api-key': apiKey } }
);
const data = await resp.json();
if (data.isVPN) {
return new Response('Access denied: VPN detected',
{ status: 403 });
}
if (data.threatLevel === 'high') {
return Response.redirect(
new URL('/challenge?reason=high_risk', request.url)
);
}
// Attach intelligence as headers
const newHeaders = new Headers(request.headers);
newHeaders.set('X-IP-Country', data.countryCode);
newHeaders.set('X-IP-ASN', String(data.asn));
newHeaders.set('X-IP-Threat', data.threatLevel || 'unknown');
return fetch(request, { headers: newHeaders });
} catch (err) {
return fetch(request); // Fail open
}
},
};Strength: Full access to IP intelligence data including VPN detection, threat scoring, and ASN intelligence. Latency budget: The external API call adds 15-35ms. Combined with Worker execution overhead, total edge decision time stays under 50ms for most requests.
3API Gateway Policy with Stepped Risk Response
For platforms running their own API gateway (Kong, AWS API Gateway, Envoy, APISIX), integrate the IP intelligence check as a gateway plugin or policy step. This pattern supports stepped responses: low-risk traffic passes through with headers, medium-risk traffic gets rate-limited, and high-risk traffic gets blocked.
// API Gateway plugin pattern (pseudo-code)
async function ipRiskPolicy(request, response) {
const ip = request.ip;
const geo = await ipIntelClient.lookup(ip);
switch (geo.threatLevel) {
case 'critical':
return response.block(403, 'Threat IP detected');
case 'high':
return response.challenge('Verify identity');
case 'medium':
// Allow with strict rate limiting
response.setHeader('X-RateLimit-Limit', '10');
break;
case 'low':
// Enrich and pass through
response.setHeader('X-User-Country', geo.countryCode);
response.setHeader('X-User-ISP', geo.aso);
break;
}
// Log for SIEM / analytics pipeline
await analytics.track({
ip, country: geo.countryCode,
isVPN: geo.isVPN, threat: geo.threatLevel,
asn: geo.asn, path: request.path,
});
}Handling VPN and Proxy Traffic at the Edge
Blocking all VPN traffic is tempting but dangerous. A significant share of legitimate users connects through corporate VPNs, mobile carrier NAT pools, or privacy services like Apple Private Relay and Cloudflare WARP. A blanket VPN block alienates real customers — particularly in enterprise and privacy-conscious markets.
The practical approach is a stepped policy that combines multiple IP signals rather than relying on a single binary flag:
| Signal | Source | Action |
|---|---|---|
| isVPN = true | IP intelligence API | Flag for additional review, do not block outright |
| threatLevel = high/critical | IP intelligence API | Block or challenge with CAPTCHA |
| ASN belongs to known data center | ASN intelligence | Block for login/checkout, allow for public pages |
| Country mismatch with session history | Session + IP comparison | Flag for step-up authentication |
| Connection type = mobile/corporate | Connection type analysis | Lower risk weight, allow with headers |
Keeping Edge Latency Under 50ms
The biggest latency risk in edge IP intelligence is the external API call. Here are proven strategies to keep total decision time within a tight budget:
Cache aggressively with short TTLs
Cache IP lookup results in the Worker with a 60-300 second TTL. Most users make multiple requests within a session — only the first request hits the external API. Subsequent requests resolve from cache in under 1ms. Use the IP address as the cache key and set TTLs based on your risk tolerance.
Fail open, never fail closed
If the external API call times out or returns an error, allow the request through. Blocking legitimate traffic because your API provider had a brief outage is worse than letting a few suspicious requests through. Log the failure for monitoring and alerting.
Only enrich when it matters
Not every request needs a full IP intelligence check. Static assets, health check endpoints, and public read-only pages can skip enrichment entirely. Only call the API on authentication events, checkout flows, API mutations, and other sensitive operations.
Where Edge IP Intelligence Creates the Most Value
Fraud prevention at checkout
Evaluate every payment attempt at the edge. Block VPN traffic from carding-prone regions, challenge requests from data center IPs, and pass clean traffic to your payment processor with enriched headers.
Geographic content access control
Enforce licensing restrictions, regional content availability, or compliance boundaries without adding latency to your application server. The decision happens at the CDN edge, not in your code.
Login and session protection
Flag impossible-travel logins (country changes between sessions), challenge VPN users with step-up auth, and pass threat-level data to your identity provider for risk-adaptive authentication.
Analytics and business intelligence
Attach country, city, ASN, ISP, and connection-type headers to every request. Your analytics pipeline can segment traffic without client-side tracking, supporting cookieless measurement.
Start Building Your Edge IP Intelligence Layer
Test the API response times and data quality with your own traffic patterns. The live demo supports IPv4 and IPv6 addresses — try it with IPs from your production logs.