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

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 聂微东
Jina AI
Jina AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
罗磊的独立博客
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
阮一峰的网络日志
阮一峰的网络日志
雷峰网
雷峰网
博客园 - 叶小钗
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
Last Week in AI
Last Week in AI
S
SegmentFault 最新的问题
博客园 - 【当耐特】
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
量子位
宝玉的分享
宝玉的分享
V
Visual Studio Blog
博客园_首页
IT之家
IT之家
V
V2EX
腾讯CDC
aimingoo的专栏
aimingoo的专栏
博客园 - 司徒正美
Microsoft Security Blog
Microsoft Security Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Blog — PlanetScale
Blog — PlanetScale
I
InfoQ
有赞技术团队
有赞技术团队
J
Java Code Geeks
Recorded Future
Recorded Future
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
H
Help Net Security

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
Anomaly Detector
Uchechukwu E · 2026-04-27 · via DEV Community

I Built a Tool That Catches Hackers in Real Time — Here's How It Works


Have you ever wondered how websites protect themselves from being flooded with fake traffic? Or how a server "knows" that something suspicious is happening?

I just built a tool that does exactly that — and in this post, I'll explain every part of it in plain English. No security background needed. Let's go.


What Is This Project?

Imagine you run a cloud storage website. Thousands of people visit it every day. Most of them are normal users uploading files, logging in, browsing around.

But one day, someone decides to attack your website. They write a script that sends thousands of requests per second from one IP address, trying to crash your server or sneak past your security. This is called a DDoS attack (Distributed Denial of Service).

My tool sits between the internet and the website, watches every single request coming in, and asks one question:

"Does this look normal — or is something weird happening?"

If something looks weird, it automatically blocks the attacker and sends me a message on Slack.


The Big Picture

Here's the flow in simple terms:

Someone visits the website
        ↓
Nginx (the traffic cop) lets them through and writes a note about it
        ↓
My tool reads those notes in real time
        ↓
It checks: "Is this normal traffic, or a spike?"
        ↓
If it's a spike → Block the IP + Send Slack alert
If it's normal  → Do nothing, keep watching

Enter fullscreen mode Exit fullscreen mode

The "notes" Nginx writes are called access logs — one line per request, saved to a file.


Part 1: Reading the Log File (The Monitor)

Every time someone visits the website, Nginx writes a line to a log file that looks like this:

{"source_ip":"45.33.12.99","timestamp":"2025-04-25T10:32:01","method":"GET","path":"/login","status":200,"response_size":1452}

Enter fullscreen mode Exit fullscreen mode

That's one visitor, at one moment in time.

My tool opens that file and reads it line by line, forever — like someone sitting next to a printer watching pages come out. In Python, this is called "tailing" a file.

with open("/var/log/nginx/hng-access.log") as f:
    f.seek(0, 2)  # Jump to the end (don't replay old history)
    while True:
        line = f.readline()
        if not line:
            time.sleep(0.05)  # No new line yet, wait a tiny bit
            continue
        process(line)  # We got a new request!

Enter fullscreen mode Exit fullscreen mode

Simple, right? It just keeps checking for new lines forever.


Part 2: The Sliding Window (Counting Recent Requests)

Now that we can read each request, we need to answer: "How many requests came in the last 60 seconds?"

A naive approach would be to count all requests in the last minute. But that resets every 60 seconds and loses accuracy.

Instead, I use a sliding window — think of it like a moving spotlight that always shows you exactly the last 60 seconds.

Here's the idea using a real-world analogy:

Imagine a bouncer at a club keeping a paper roll. Every time someone enters, they write the time on the roll. Every few seconds, they tear off the old end (entries older than 60 seconds). The number of entries left = people who arrived in the last 60 seconds.

In Python, I use a deque (double-ended queue) — a list you can add to on the right and remove from the left efficiently:

from collections import deque
import time

window = deque()  # Our "paper roll"

def record_request():
    now = time.time()
    window.append(now)  # Write the time on the roll

    # Tear off old entries (older than 60 seconds)
    cutoff = now - 60
    while window and window[0] < cutoff:
        window.popleft()

    # How many requests in the last 60 seconds?
    rate = len(window) / 60
    return rate  # requests per second

Enter fullscreen mode Exit fullscreen mode

I maintain one of these windows per IP address and one globally (all IPs combined).


Part 3: The Baseline (Learning What "Normal" Looks Like)

Here's the clever part. We can't just say "more than 10 requests per second is an attack" — because maybe your website normally gets 50 requests per second at peak hours, and only 2 at night.

So instead of hardcoding a number, my tool learns what normal looks like over time.

Every second, it records the current traffic rate. It keeps the last 30 minutes of these recordings. Every 60 seconds, it calculates:

  • Mean — the average traffic rate over the last 30 minutes
  • Standard deviation — how much the traffic varies

Think of it like a teacher grading on a curve. If the average test score is 70, a score of 95 is unusually high. If everyone scores between 85–95, then 95 is totally normal.

import math

samples = [2.1, 1.9, 2.3, 2.0, 1.8, ...]  # One sample per second, last 30 min

mean   = sum(samples) / len(samples)        # Average rate
stddev = math.sqrt(sum((x - mean)**2 for x in samples) / len(samples))

Enter fullscreen mode Exit fullscreen mode

The tool also tracks traffic per hour separately. So if rush hour is always busier, it compares against rush hour data — not the quiet overnight average.


Part 4: Detecting the Attack (The Z-Score)

Now we have the current rate and we know what "normal" looks like. How do we decide if something is an attack?

I use a z-score — a simple math formula that answers:

"How many standard deviations above normal is this?"

z_score = (current_rate - mean) / stddev

Enter fullscreen mode Exit fullscreen mode

If z_score > 3.0, that means the current rate is so far above normal that there's only a 0.1% chance it's a coincidence. That's our signal to act.

I also have a backup rule: if the rate is more than 5 times the average, it's flagged regardless of the z-score. Whichever rule fires first wins.

Real example:

  • Normal traffic: mean = 5 req/s, stddev = 1.5
  • Attacker sending: 50 req/s
  • Z-score = (50 - 5) / 1.5 = 30 → Way above 3.0 → 🚨 ATTACK DETECTED

There's also a bonus feature: if an IP is sending lots of error responses (like hitting bad login attempts over and over), we tighten the thresholds even further for that IP specifically.


Part 5: Blocking the Attacker (iptables)

Once we've decided an IP is an attacker, we need to stop them immediately.

iptables is a built-in Linux tool that acts like a firewall. You can tell it: "Drop all traffic from this IP address — don't even respond to them."

My tool runs this command in Python:

import subprocess

def ban_ip(ip):
    subprocess.run(["iptables", "-I", "INPUT", "-s", ip, "-j", "DROP"])
    print(f"Blocked: {ip}")

Enter fullscreen mode Exit fullscreen mode

That's it. One command. The attacker's packets are now silently dropped by the operating system — they never even reach the web server.

You can verify it worked with:

sudo iptables -L INPUT -n

Enter fullscreen mode Exit fullscreen mode

You'll see a line like:

DROP  all  --  45.33.12.99  0.0.0.0/0

Enter fullscreen mode Exit fullscreen mode


Part 6: Auto-Unban (Giving Second Chances)

What if we accidentally blocked a real user? Or the attacker stopped and wants to try again?

My tool uses a backoff schedule — bans get longer each time the same IP misbehaves:

Offense Ban Duration
1st time 10 minutes
2nd time 30 minutes
3rd time 2 hours
4th time Permanent

Every 30 seconds, the tool checks: "Has anyone's ban expired?" If yes, it removes the iptables rule and sends a Slack notification.


Part 7: Slack Notifications

Every time something happens — a ban, an unban, or a global traffic surge — my tool sends a message to a Slack channel so I know about it immediately.

It looks like this:

🚨 IP BANNED
• IP: 45.33.12.99
• Condition: z-score=18.4
• Current rate: 120.00 req/s
• Baseline mean: 5.20 req/s
• Ban duration: 10 min
• Time: 2025-04-25T14:22:01

Enter fullscreen mode Exit fullscreen mode

This uses Slack's "Incoming Webhooks" feature — you post a JSON message to a special URL, and it appears in your Slack channel.


Part 8: The Live Dashboard

Finally, the whole system has a web dashboard you can open in your browser. It shows:

  • Current global requests per second
  • The baseline mean and standard deviation
  • CPU and memory usage of the server
  • List of currently banned IPs
  • Top 10 most active IP addresses

It refreshes automatically every 3 seconds so you always see what's happening live.


Putting It All Together

Here's the whole system in one picture:

                        ┌─────────────────────────┐
Internet requests  ───► │  Nginx (reverse proxy)  │
                        │  writes JSON log lines  │
                        └──────────┬──────────────┘
                                   │ log file
                        ┌──────────▼──────────────┐
                        │     Monitor Thread       │
                        │  tails log line by line  │
                        └──────────┬──────────────┘
                                   │ parsed request
                        ┌──────────▼──────────────┐
                        │    Detector Thread       │
                        │  z-score & rate check    │
                        └──────┬──────────┬────────┘
                               │          │
               ┌───────────────▼─┐    ┌───▼──────────────┐
               │  Blocker        │    │  Notifier         │
               │  iptables DROP  │    │  Slack alert      │
               └────────┬────────┘    └───────────────────┘
                        │
               ┌────────▼────────┐
               │  Unbanner       │
               │  removes rule   │
               │  after timeout  │
               └─────────────────┘

Enter fullscreen mode Exit fullscreen mode

Every component runs in its own thread — meaning they all run simultaneously, like workers in a factory each doing their own job at the same time.


What I Learned

Building this taught me a few things I hadn't truly understood before:

  1. Security is about patterns, not rules. The most powerful part of this system isn't the blocking — it's the baseline that learns what's normal. A hardcoded rule would break on the first unusual-but-legitimate traffic spike.

  2. Simple data structures go a long way. A deque + a timestamp is enough to build a production-grade sliding window. You don't need a database.

  3. Linux tools are powerful. iptables has been in Linux for decades. One shell command blocks an IP at the kernel level — nothing the attacker sends can get through.


Want to Build It Yourself?

The full code is available at: https://github.com/ucheenyi/hng-detector

The README has step-by-step setup instructions starting from a fresh Linux server.


Thanks for reading! If you found this helpful, drop a like or comment — I'd love to hear what you're building.