惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
T
Threat Research - Cisco Blogs
N
News and Events Feed by Topic
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 叶小钗
Security Latest
Security Latest
Spread Privacy
Spread Privacy
aimingoo的专栏
aimingoo的专栏
N
News and Events Feed by Topic
Webroot Blog
Webroot Blog
U
Unit 42
Cyberwarzone
Cyberwarzone
小众软件
小众软件
Scott Helme
Scott Helme
Engineering at Meta
Engineering at Meta
Microsoft Security Blog
Microsoft Security Blog
T
The Blog of Author Tim Ferriss
A
About on SuperTechFans
爱范儿
爱范儿
S
Schneier on Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Schneier on Security
Schneier on Security
Latest news
Latest news
GbyAI
GbyAI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
The Register - Security
The Register - Security
WordPress大学
WordPress大学
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
PCI Perspectives
PCI Perspectives
Jina AI
Jina AI
AI
AI
NISL@THU
NISL@THU
I
Intezer
G
GRAHAM CLULEY
B
Blog
S
Secure Thoughts
IT之家
IT之家
宝玉的分享
宝玉的分享
Recent Announcements
Recent Announcements
Y
Y Combinator Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
有赞技术团队
有赞技术团队
V2EX - 技术
V2EX - 技术
Recorded Future
Recorded Future
Hacker News - Newest:
Hacker News - Newest: "LLM"

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Add IP Fraud Scoring to Your Auth Flow
ABDULLAH AFZ · 2026-05-12 · via DEV Community

Credential stuffing bots hit login endpoints at thousands of requests per minute, rotating through IP addresses as they go. By the time your rate limiter reacts, the damage is done. An IP fraud score check sits before your auth logic, scores each IP from 0 to 100 and lets you decide whether to allow, challenge, or block.

This tutorial adds that check to a Node.js/Express and Python/Flask login route. You'll also get the cURL version for testing. The whole thing takes about 30 minutes to wire up.

TL;DR

  • An IP fraud score is a 0-100 rating aggregating VPN/proxy/Tor detection, known attacker history, bot activity, and cloud provider flags into a single number
  • The dedicated /v3/security endpoint returns a structured security object: threat score, VPN/proxy/Tor/relay flags, provider names ("Nord VPN", "922 Proxy"), confidence scores, and last-seen dates
  • Graduated thresholds: 0-19 allow, 20-44 log and flag, 45-79 force MFA, 80-100 block
  • Fail-open on the API check for login routes (if the scoring API is down, let users through with logging). Fail-closed for payment endpoints.
  • Cache results in Redis with a 5-minute TTL to avoid per-request API calls
  • Code below covers cURL, Node.js/Express middleware, and Python/Flask decorator

One API call before your auth logic flags risky IPs often seen in credential stuffing, residential proxy abuse, and known attacker traffic before they hit your password check. The response includes enough detail (provider names, confidence scores, timestamps) to build graduated rules, not just a binary block.

What the Security API Returns

Most IP reputation APIs give you a handful of boolean flags: is_vpn: true, is_proxy: false, done. That tells you what the IP is, but not how confident the detection is or which provider it belongs to.

The ipgeolocation.io Security API returns a structured object per lookup: threat score, anonymization flags, provider attribution, confidence scores, and last-seen timestamps. Here's what a flagged IP actually looks like:

{
  "ip": "2.56.188.34",
  "security": {
    "threat_score": 80,
    "is_tor": false,
    "is_proxy": true,
    "proxy_provider_names": ["Zyte Proxy"],
    "proxy_confidence_score": 90,
    "proxy_last_seen": "2025-12-12",
    "is_residential_proxy": true,
    "is_vpn": true,
    "vpn_provider_names": ["Nord VPN"],
    "vpn_confidence_score": 99,
    "vpn_last_seen": "2026-01-19",
    "is_relay": false,
    "relay_provider_name": "",
    "is_anonymous": true,
    "is_known_attacker": true,
    "is_bot": false,
    "is_spam": false,
    "is_cloud_provider": true,
    "cloud_provider_name": "Packethub S.A."
  }
}

Enter fullscreen mode Exit fullscreen mode

The difference matters for auth decisions. Knowing an IP is "a VPN" is less useful than knowing it's NordVPN with 99% confidence, last seen yesterday, and also flagged as a known attacker with a threat score of 80. The first gives you a boolean. The second gives you a policy.

is_residential_proxy is worth calling out specifically. Residential proxies route traffic through real ISP connections, so they look legitimate to basic VPN detectors. Services like 922 Proxy, Oxylabs, and Bright Data sell this access. If your fraud rules only check is_vpn and is_proxy, residential proxy traffic sails right through. The dedicated flag catches it.

Setup

You need Node.js 18+ or Python 3.8+, and an ipgeolocation.io API key with security access.

Tip: IPGeolocation, IPQS, Scamalytics, AbuseIPDB, and MaxMind minFraud all offer IP risk scoring with different pricing models, detection depth, and response shapes. I'm using ipgeolocation.io for these examples because the /v3/security endpoint returns provider attribution and confidence scores in one call, which keeps the graduated-response code clean.

Set your API key as an environment variable. Do not hardcode it.

export IPGEO_API_KEY="your_api_key_here"

Enter fullscreen mode Exit fullscreen mode

Install the dependencies you'll need:

# Node.js
npm install express ioredis

# Python
pip install flask requests

Enter fullscreen mode Exit fullscreen mode

Test with cURL First

Before writing middleware, call the endpoint directly to see the response shape for a known IP:

curl -s "https://api.ipgeolocation.io/v3/security?apiKey=${IPGEO_API_KEY}&ip=8.8.8.8" | python3 -m json.tool

Enter fullscreen mode Exit fullscreen mode

For 8.8.8.8 (Google Public DNS), you'll get a low threat score and is_cloud_provider: true with cloud_provider_name: "Google LLC". That's a clean IP doing exactly what you'd expect.

Try it with a known proxy or Tor exit IP if you have one handy. The threat_score jump and the flag combination tells you whether your thresholds will catch what you care about.

Node.js/Express Middleware

Here's the middleware. It runs before your login handler, checks the IP against the Security API, and attaches the score to the request object so downstream handlers can act on it.

// ip-risk-middleware.js
const API_KEY = process.env.IPGEO_API_KEY;
const SECURITY_URL = 'https://api.ipgeolocation.io/v3/security';

if (!API_KEY) {
  throw new Error('Missing IPGEO_API_KEY environment variable');
}

async function ipRiskCheck(req, res, next) {
  // Trust the first X-Forwarded-For entry if behind a reverse proxy.
  // Verify your proxy sets this correctly; spoofable if not.
  const clientIp =
    req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
    req.socket.remoteAddress;

  try {
    const response = await fetch(
      `${SECURITY_URL}?apiKey=${API_KEY}&ip=${clientIp}`,
      { signal: AbortSignal.timeout(1500) } // 1.5s timeout; don't let a slow API stall login
    );

    if (!response.ok) {
      // API error: fail open for login routes, log the failure
      console.error(`IP risk API returned ${response.status} for ${clientIp}`);
      req.ipRisk = { score: 0, flags: {}, failedOpen: true };
      return next();
    }

    const data = await response.json();
    const security = data.security ?? {};
    const score = security.threat_score ?? 0;

    // Attach the full security object for downstream handlers
    req.ipRisk = {
      score,
      flags: security,
      ip: clientIp,
    };

    // Graduated response based on threat score
    if (score >= 80) {
      console.warn(`BLOCKED: IP ${clientIp} scored ${score}`, {
        vpn: security.is_vpn,
        proxy: security.is_proxy,
        attacker: security.is_known_attacker,
      });
      return res.status(403).json({ error: 'Request blocked' });
    }

    if (score >= 45) {
      // Elevated risk: force MFA regardless of account settings
      req.requireMfa = true;
    }

    next();
  } catch (err) {
    // Network timeout or fetch failure: fail open, log it
    console.error(`IP risk check failed for ${clientIp}: ${err.message}`);
    req.ipRisk = { score: 0, flags: {}, failedOpen: true };
    next();
  }
}

module.exports = { ipRiskCheck };

Enter fullscreen mode Exit fullscreen mode

Wire it into your login route:

const express = require('express');
const { ipRiskCheck } = require('./ip-risk-middleware');

const app = express();
app.use(express.json());

// Apply the risk check to auth routes only.
// Running it on every route burns API quota on static assets.
app.post('/api/login', ipRiskCheck, (req, res) => {
  const { score, flags, failedOpen } = req.ipRisk;

  // Log every auth attempt with its risk score for later threshold tuning
  console.log(`Login attempt from ${req.ipRisk.ip}: score=${score}`, {
    failedOpen,
    vpn: flags.is_vpn,
    proxy: flags.is_proxy,
    residential_proxy: flags.is_residential_proxy,
    tor: flags.is_tor,
  });

  if (req.requireMfa) {
    return res.status(200).json({
      mfaRequired: true,
      reason: 'elevated_ip_risk',
    });
  }

  // Normal login flow continues here
  res.json({ success: true });
});

app.listen(3000, () => console.log('Running on :3000'));

Enter fullscreen mode Exit fullscreen mode

A few things to note. AbortSignal.timeout(1500) caps the API call at 1.5 seconds. IPGeolocation.io's public status page reports low average API response times, so 1.5 seconds is intentionally conservative. Network hiccups still happen, and a stalled risk check should never block a user from logging in. The middleware fails open: if the API is unreachable, the user gets through with failedOpen: true logged so you can audit later.

If you're behind Cloudflare, Nginx, or an AWS ALB, make sure trust proxy is configured in Express (app.set('trust proxy', 1)) so Express resolves the client IP from X-Forwarded-For correctly. Without it, req.socket.remoteAddress gives you the proxy's IP, not the client's. Only trust X-Forwarded-For when your edge proxy overwrites incoming forwarded headers. Never trust a client-supplied forwarded header directly.

Python/Flask Equivalent

Same logic, different runtime. This uses a decorator pattern so you can apply it selectively to routes.

# ip_risk.py
import os
import functools
import requests
from flask import request, jsonify, g

API_KEY = os.environ.get('IPGEO_API_KEY')
SECURITY_URL = 'https://api.ipgeolocation.io/v3/security'

if not API_KEY:
    raise RuntimeError('Missing IPGEO_API_KEY environment variable')


def check_ip_risk(f):
    @functools.wraps(f)
    def decorated(*args, **kwargs):
        # Behind a reverse proxy, X-Forwarded-For holds the real client IP.
        # Take the first entry; later entries are intermediate proxies.
        client_ip = (
            request.headers.get('X-Forwarded-For', '').split(',')[0].strip()
            or request.remote_addr
        )

        try:
            resp = requests.get(
                SECURITY_URL,
                params={'apiKey': API_KEY, 'ip': client_ip},
                timeout=(1.0, 1.5),  # 1s connect, 1.5s read
            )
            resp.raise_for_status()
            data = resp.json()
            security = data.get('security', {})
            score = security.get('threat_score', 0)
        except (requests.RequestException, ValueError) as err:
            # Fail open: API down should not lock users out of login
            print(f'IP risk check failed for {client_ip}: {err}')
            g.ip_risk = {'score': 0, 'flags': {}, 'failed_open': True}
            return f(*args, **kwargs)

        g.ip_risk = {
            'score': score,
            'flags': security,
            'ip': client_ip,
            'failed_open': False,
        }

        if score >= 80:
            print(f'BLOCKED: {client_ip} scored {score}')
            return jsonify({'error': 'Request blocked'}), 403

        if score >= 45:
            g.require_mfa = True

        return f(*args, **kwargs)

    return decorated

Enter fullscreen mode Exit fullscreen mode

Apply it to your login route:

from flask import Flask, g, jsonify
from ip_risk import check_ip_risk

app = Flask(__name__)


@app.route('/api/login', methods=['POST'])
@check_ip_risk
def login():
    risk = g.ip_risk

    app.logger.info(
        'Login attempt from %s: score=%d, failed_open=%s',
        risk.get('ip'),
        risk['score'],
        risk.get('failed_open'),
    )

    if getattr(g, 'require_mfa', False):
        return jsonify({'mfa_required': True, 'reason': 'elevated_ip_risk'})

    # Normal login flow
    return jsonify({'success': True})

Enter fullscreen mode Exit fullscreen mode

The timeout=(1.0, 1.5) tuple sets a 1-second connection timeout and 1.5-second read timeout. Python's requests library hangs indefinitely without an explicit timeout, which is the kind of bug that doesn't surface until your login endpoint stops responding at 2 AM.

Cache Results with Redis

Calling the Security API on every single login request works fine under moderate traffic, but it's wasteful. An IP's threat score doesn't change second-to-second. A 5-minute Redis cache cuts your API usage dramatically without meaningfully delaying threat detection.

// Add to ip-risk-middleware.js
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');

const CACHE_TTL = 300; // 5 minutes in seconds

async function getCachedRisk(ip) {
  try {
    const cached = await redis.get(`ip-risk:${ip}`);
    return cached ? JSON.parse(cached) : null;
  } catch {
    return null; // Redis down: skip cache, hit API
  }
}

async function setCachedRisk(ip, security) {
  try {
    await redis.set(
      `ip-risk:${ip}`,
      JSON.stringify(security),
      'EX',
      CACHE_TTL
    );
  } catch {
    // Cache write failure is non-critical; log and move on
  }
}

Enter fullscreen mode Exit fullscreen mode

Then in the middleware, check the cache before calling the API:

// Inside ipRiskCheck, before the fetch call:
const cached = await getCachedRisk(clientIp);
if (cached) {
  req.ipRisk = { score: cached.threat_score ?? 0, flags: cached, ip: clientIp };
  // Apply the same threshold logic as the non-cached path
  if (cached.threat_score >= 80) {
    return res.status(403).json({ error: 'Request blocked' });
  }
  if (cached.threat_score >= 45) {
    req.requireMfa = true;
  }
  return next();
}
// ...existing fetch call, then after parsing:
await setCachedRisk(clientIp, security);

Enter fullscreen mode Exit fullscreen mode

Five minutes is a reasonable default. If you're seeing active attacks that rotate IPs faster than that, drop it to 60 seconds. If your traffic is low enough that you're under quota anyway, skip the cache entirely and keep the code simpler.

Setting Your Fraud Score Thresholds

The threshold bands I've used above are based on what ipgeolocation.io documents:

  • 0-19: Low risk. Clean residential IP, no flags. Allow normally.
  • 20-44: Some signals. Maybe a datacenter IP or a consumer VPN. Log it, maybe flag for review, but don't add friction yet.
  • 45-79: Elevated. Multiple flags firing, or a known proxy service. Force MFA. A legitimate user clears MFA in seconds. A bot doesn't.
  • 80-100: High confidence. Known attacker, active proxy with provider attribution, or multiple overlapping anonymization signals. Block the request.

Start permissive. Deploy the middleware in log-only mode (no blocking, no MFA forcing) for a week. Look at the score distribution for your actual traffic. If 10% of your legitimate users come through corporate VPNs and score 30-40, you don't want your MFA threshold at 30. Tune based on your data, not on defaults.

For payment endpoints, flip the logic: fail-closed instead of fail-open. If the scoring API is down and you can't verify the IP, hold the transaction for manual review rather than letting it through. The risk calculus is different when money moves.

Edge Cases Worth Handling

Corporate NAT and shared IPs. A large office with 500 employees behind one public IP looks like a single entity to any IP-based system. If someone on that network triggered a flag last week, the whole office inherits it. Graduated responses handle this better than hard blocks. Score 35 with MFA is a minor inconvenience for a real employee. A hard block at the same score locks out the whole building.

VPN users who aren't malicious. Journalists, security researchers, and privacy-conscious developers use commercial VPNs daily. The is_vpn: true flag alone shouldn't trigger a block. Pair it with threat_score: a NordVPN IP with a score of 15 is a privacy-conscious user. The same VPN range with a score of 75 and is_known_attacker: true is a different story.

iCloud Private Relay and similar services. Apple's iCloud Private Relay, Cloudflare WARP, and Chrome's IP Protection are growing. The is_relay flag distinguishes these from traditional VPNs. Blocking relay traffic means blocking a meaningful chunk of iOS users. Unless you have a specific reason (geo-compliance, content licensing), treat relay IPs as low-risk.

Cloud provider IPs. Your CI/CD pipeline, webhook senders, and monitoring services all originate from AWS, GCP, or Azure ranges. The is_cloud_provider flag with cloud_provider_name helps you whitelist known sources. A login attempt from "Google LLC" infrastructure is suspicious. A health check from the same range is expected.

GDPR and IP logging. If you serve EU users, storing IP addresses with threat scores counts as personal data processing under GDPR. Set a retention policy (30-90 days for security logs is defensible), document the legitimate interest basis, and make sure your privacy policy covers it.

Wrapping Up

Drop the middleware into your auth routes, deploy in log-only mode for a week, and look at your actual score distribution before turning on the blocks. The thresholds above are starting points. Your traffic patterns will tell you where to tighten.

For high-traffic services, add the Redis cache from the start. For payment flows, switch to fail-closed and hold transactions when the API is unreachable. When traffic outgrows the API tier, batch analysis with the bulk endpoint (up to 50,000 IPs per POST) handles post-incident forensics without burning your real-time quota.