Real-World Problem: When Firewalls Choke Under Pressure
A few years ago, a modest 4-core production VPS hosting our internal tools ground to a dead halt at 3:00 AM. That incident taught me a blunt lesson: running an active firewall is meaningless if it collapses under pressure.
Our initial deployment looked ordinary. We rolled out Ubuntu, installed Fail2ban, and kept the stock iptables action. Within two hours, automated scanners discovered port 22. Botnets began hitting SSH and Nginx login endpoints with roughly 4,000 authentication attempts per minute. Fail2ban reacted immediately, writing ban rule after ban rule into iptables.
Then our uptime monitoring triggered critical alerts. Legitimate HTTP requests started timing out with 504 Gateway errors. Interactive SSH sessions took over 15 seconds just to show a password prompt, and server load averages surged past 24. Bandwidth was clear, and RAM usage hovered under 25%. Our own firewall had choked, paralyzed by roughly 18,000 linear iptables rules.
Root Cause Analysis: Why Standard iptables Rules Fail at Scale
To fix this bottleneck, look at how the Linux netfilter subsystem handles rule chains. By default, Fail2ban appends an individual rule for every banned IP into a custom chain:
iptables -A f2b-sshd -s 198.51.100.42 -j REJECT --reject-with icmp-port-unreachable
iptables -A f2b-sshd -s 198.51.100.43 -j REJECT --reject-with icmp-port-unreachable
# ... repeated 10,000+ times
Standard iptables traverses rules sequentially using an O(N) linked-list search. Every single incoming network packet must inspect each rule from top to bottom until it finds a match or falls through to the default policy.
At scale, this linear lookup creates severe system bottlenecks:
- CPU Saturation: At 1,000 banned IPs, the kernel performs up to 1,000 comparisons per packet. When bans reach 25,000 IPs under a modest 20 Mbps flood (~15,000 packets per second), the
ksoftirqdkernel thread easily burns 80% to 90% of a CPU core on packet comparisons alone. - Network Latency: Valid traffic suffers measurable delays on every TCP handshake. In our production tests, local ping response times jumped from 0.8 ms to over 35 ms as rules accumulated.
- Management Freezes: Storing tens of thousands of rules in a monolithic table turns routine operations sluggish. Running
iptables -L -nor restarting the daemon can lock up the terminal for 30 to 60 seconds while the kernel reconstructs memory structures.
Solutions Compared: Finding the Right Scaling Strategy
When defending a server against distributed brute-force attacks and low-volume application DoS, three architectures stand out:
1. Vanilla Fail2ban with Default iptables
This is the stock configuration on Ubuntu, Debian, and Rocky Linux. It works well enough for personal side projects dealing with a few dozen failed logins a week. However, once a botnet rotates through 15,000 compromised residential IPs, sequential rule evaluation destroys network throughput.
2. Cloud Edge Firewalls and CDNs (Cloudflare, AWS WAF)
Offloading bans to edge providers drops junk traffic before it reaches your network interface. This offers outstanding protection for HTTP/HTTPS web endpoints. Unfortunately, it leaves non-HTTP services like raw SSH, SFTP, mail servers, and custom TCP sockets completely unprotected unless you pay for expensive enterprise proxy tiers.
3. Fail2ban Paired with ipset (In-Kernel Hash Sets)
ipset is a dedicated companion tool for iptables. It stores IP addresses, subnets, and port numbers inside dynamic hash tables managed directly within kernel memory. Instead of checking thousands of individual rules, iptables evaluates one single condition:
iptables -A INPUT -m set --match-set f2b-sshd src -j DROP
Hash lookups execute at O(1) constant time. Checking a packet against a set of 10 IPs takes virtually the exact same CPU time—around 50 to 100 nanoseconds—as matching it against 100,000 IPs.
Best Approach: Step-by-Step Implementation Guide
Configuring Fail2ban to use ipset by default allows your server to drop tens of thousands of hostile hosts with negligible CPU overhead.
Step 1: Install ipset and Fail2ban
Start by refreshing your repositories and installing the required packages. On Ubuntu and Debian:
sudo apt update
sudo apt install -y fail2ban ipset
On RHEL, AlmaLinux, or Rocky Linux:
sudo dnf install -y epel-release
sudo dnf install -y fail2ban ipset
Verify that your running kernel supports the required modules:
sudo ipset list
If the command executes cleanly without missing module warnings, your system is ready.
Step 2: Configure Fail2ban to Use ipset by Default
Never edit /etc/fail2ban/jail.conf directly, because package updates overwrite upstream files. Place your custom configuration in /etc/fail2ban/jail.local instead:
sudo nano /etc/fail2ban/jail.local
Insert the following hardened configuration:
[DEFAULT]
# Whitelist localhost and your trusted administrative IPs
ignoreip = 127.0.0.1/8 ::1 203.0.113.50
# Base ban parameters: 1 hour ban, 10-minute window, 5 failed attempts
bantime = 1h
findtime = 10m
maxretry = 5
# Route bans through ipset hash tables rather than individual iptables chains
banaction = iptables-ipset-proto4
banaction_allports = iptables-ipset-proto4
# Exponential ban progression for persistent attackers
bantime.increment = true
bantime.factor = 2
bantime.maxtime = 5w
[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = systemd
[nginx-botsearch]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 2
Two directives make the difference here:
banaction = iptables-ipset-proto4tells Fail2ban to invoke the built-in ipset script at/etc/fail2ban/action.d/iptables-ipset-proto4.conf.bantime.increment = trueautomatically doubles ban times for returning offenders, keeping temporary tables clean while sidelining chronic attackers for up to 5 weeks.
Step 3: Restart and Validate the Service
Apply your configuration changes by restarting the service:
sudo systemctl restart fail2ban
sudo systemctl enable fail2ban
Confirm the SSH jail is active and parsing logs:
sudo fail2ban-client status sshd
Check that Fail2ban initialized the hash set inside kernel memory:
sudo ipset list -name
The output will list f2b-sshd. Next, inspect your active firewall rules:
sudo iptables -L INPUT -v -n
Instead of a cluttered list of single-IP rules, you will see a clean match statement:
target prot opt in out source destination
DROP all -- * * 0.0.0.0/0 0.0.0.0/0 match-set f2b-sshd src
Step 4: Testing the Setup Safely
Verify that ban commands write directly into the hash set. Manually ban a reserved documentation IP (RFC 5737):
sudo fail2ban-client set sshd banip 198.51.100.99
Query the contents of the set:
sudo ipset list f2b-sshd
The kernel returns the active member record along with an automatic expiration counter:
Name: f2b-sshd
Type: hash:ip
Revision: 4
Header: family inet hashsize 1024 maxelem 65536 timeout 3600
Members:
198.51.100.99 timeout 3594
Because the set uses native kernel timeouts, individual records clean themselves up automatically. Remove the test IP to finish verification:
sudo fail2ban-client set sshd unbanip 198.51.100.99
Step 5: Preserving Firewall Sets Across Reboots
Fail2ban restores active bans from its SQLite database (/var/lib/fail2ban/fail2ban.sqlite3) on boot. Even so, saving kernel sets avoids brief windows of exposure while services initialize during reboots.
On Ubuntu and Debian systems, install the persistence helpers:
sudo apt install -y netfilter-persistent ipset-persistent
sudo systemctl enable netfilter-persistent
You can also export and restore active sets manually at any time using standard shell redirects:
sudo ipset save > /etc/iptables/ipsets
sudo ipset restore < /etc/iptables/ipsets
Operational Summary and Key Takeaways
Pairing Fail2ban with ipset transforms an ordinary Linux host into a resilient firewall capable of tracking over 50,000 hostile addresses. Replacing sequential O(N) rules with constant-time O(1) hash tables keeps CPU usage near zero, keeping your server fast and responsive even under intense distributed brute-force attacks.

