Imagine your web server suddenly starts getting hammered by thousands of requests from one IP address. Without any protection, your server slows down, legitimate users get blocked out, and you have no idea it's even happening until it's too late. That's the problem I set out to solve by building a real-time anomaly detection engine alongside a Nextcloud server. The tool watches every single HTTP request coming through Nginx, learns what "normal" traffic looks like over time, and automatically blocks attackers using iptables — the Linux firewall built into every server. No third-party tools, no Fail2Ban, just pure detection logic built from scratch in Python.
The core of the system is two ideas working together: a sliding window and a rolling baseline. The sliding window is a Python deque that holds the timestamps of every request in the last 60 seconds — one per IP, one globally. When a new request arrives, its timestamp is added to the back; anything older than 60 seconds is evicted from the front. Dividing the count by 60 gives the current requests-per-second rate. The baseline is a 30-minute rolling average of per-second rates, recalculated every 60 seconds, with separate slots for each hour of the day so the system knows that midnight traffic is naturally lighter than noon. When a new request comes in, the detector computes a z-score: (current_rate - mean) / stddev. If that score exceeds 3.0, or the rate is more than 5 times the baseline mean, the IP is flagged as an attacker. The response is immediate — the system runs iptables -I INPUT -s <attacker_ip> -j DROP, which tells the Linux kernel to silently drop every packet from that IP at the network level, before it even reaches the application. A Slack alert fires within seconds, and the ban is automatically lifted on a backoff schedule: 10 minutes for the first offense, 30 minutes for the second, 2 hours for the third, and permanent after that.
Top comments (0)