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

推荐订阅源

J
Java Code Geeks
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
M
MIT News - Artificial intelligence
G
Google Developers Blog
P
Proofpoint News Feed
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
爱范儿
爱范儿
罗磊的独立博客
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
博客园 - 叶小钗
Vercel News
Vercel News
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
C
Check Point Blog
美团技术团队
宝玉的分享
宝玉的分享
Microsoft Security Blog
Microsoft Security Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

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
Detecting & Blocking Anomalous Traffic with Cloud Anomaly...
Joseph Joshu · 2026-04-28 · via DEV Community

Joseph Joshua

A lightweight, containerized anomaly detection system that monitors traffic in real time, detects abuse patterns, and automatically blocks malicious IPs at the host firewall level.


I built a real-time anomaly detection system that monitors nginx access logs, computes adaptive rolling baselines per time window, detects traffic anomalies using statistical methods (z-score + spike multipliers), and automatically blocks malicious IPs using host-level iptables rules. The system includes Slack alerts and a live dashboard for observability and debugging.


🧠 Background / Motivation

Modern systems face constant threats such as:

  • DDoS attacks
  • Credential stuffing
  • API abuse and scraping bots
  • Sudden traffic spikes that degrade service

Most production solutions rely on expensive managed WAFs or cloud security tools. I wanted to build a low-cost, self-hosted anomaly detection engine that runs entirely on a VPS using logs, statistics, and system-level enforcement.

Constraints:

  • Must be containerized (Docker-based)
  • Must run on low-cost VPS infrastructure
  • Must use logs (not packet inspection tools)
  • Must enforce bans at host level (not only inside containers)
  • Must provide real-time visibility and debugging

🏗️ What I Built

A full-stack anomaly detection pipeline composed of:

  • Detector Service (Python)
  • Baseline Engine (rolling statistical model)
  • Blocker Service (iptables enforcement on host)
  • Dashboard (real-time monitoring UI)
  • Slack Alerting System (incident notifications)

⚙️ How It Works

Nginx logs every request in structured JSON format.

{
  "ip": "1.2.3.4",
  "endpoint": "/",
  "status": 200,
  "timestamp": 1710000000
}

Enter fullscreen mode Exit fullscreen mode


🔄 From Logs to Detection

Once nginx writes request logs, the detector continuously processes them in real time.

Each incoming log entry goes through the following pipeline:

  1. Parse JSON log entry
  2. Extract IP, timestamp, and status code
  3. Update per-second counters
  4. Feed values into rolling baseline engine
  5. Evaluate anomaly conditions

This pipeline runs continuously with minimal latency, ensuring near real-time detection.


📉 Rolling Baseline Behavior

The system does not rely on fixed thresholds. Instead, it learns traffic behavior over time.

For each time window, the baseline tracks:

  • Average request rate (mean)
  • Variance (standard deviation)
  • Traffic distribution per second

This allows the system to adapt dynamically to traffic changes.

Example behavior:

  • Normal traffic period → stable baseline
  • Gradual increase → baseline adjusts slightly
  • Sudden spike → deviation becomes statistically significant

⚠️ Anomaly Decision Process

Every second, the detector evaluates:

  • Current request rate vs baseline mean
  • Z-score deviation
  • Spike multiplier threshold
  • Error rate deviation

If any condition exceeds configured thresholds, the IP or system state is flagged.

This ensures:

  • Low false positives during normal usage
  • Fast reaction to sudden abuse patterns

🚫 Blocking Execution Flow

When an anomaly is confirmed, the system does not block immediately inside the application layer.

Instead, it uses a decoupled enforcement pipeline:

  1. IP is added to a shared ban queue
  2. Host worker process reads queue
  3. Firewall rule is applied at kernel level

This ensures:

  • Separation of detection and enforcement
  • Reliability even if app crashes
  • Immediate packet-level blocking

🔥 Why Host-Level Blocking Matters

Blocking inside containers or application code is not sufficient because:

  • Traffic may already be routed through Docker bridge
  • App-level blocking still consumes resources
  • Reverse proxies may already forward requests

Using iptables DOCKER-USER ensures:

Traffic is dropped before it reaches the container network stack

This makes enforcement fast and reliable.


📊 Observability Layer

To ensure visibility, the system exposes:

  • Live request rate graphs
  • Current baseline values
  • Active banned IP list
  • Recent anomaly events

The dashboard updates in real time based on detector outputs.


🧪 Testing Strategy (k6)

The system is validated using controlled load testing:

  • Gradual ramp-up tests
  • Sudden spike injection
  • Sustained high traffic simulation

This ensures:

  • Baseline accuracy
  • Proper Z-score calibration
  • Reliable ban triggering

🧩 System Reliability Design

Several mechanisms improve stability:

  • Warm-up period (prevents early noise)
  • Duplicate ban suppression
  • Rolling window smoothing
  • Queue-based enforcement (decoupled architecture)

These ensure the system remains stable under continuous load.


🧭 Summary of Flow

  1. Nginx logs requests
  2. Detector parses logs
  3. Baseline is updated
  4. Anomaly detected using statistical rules
  5. IP is queued for blocking
  6. Host worker applies firewall rule
  7. Slack alert is sent
  8. Dashboard reflects updated state

Visit repo for code workflow: https://github.com/izzyjosh/cloud-anomaly-detector