How to rate-limit connections with iptables

Limit incoming connection rates per IP address using iptables connlimit and hashlimit modules.

How to rate-limit connections with iptables

Limit incoming connection rates per IP address using iptables hashlimit module.

Prerequisites

  • Root access on a Linux system with iptables.
  • The xt_hashlimit kernel module (loaded automatically on most distributions).

Step-by-Step: Rate-Limit Connections with iptables

  1. Add a hashlimit rule to the INPUT chain. iptables limits new SSH connections to 3 per minute per source IP:

    sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m hashlimit --hashlimit-above 3/min --hashlimit-burst 3 --hashlimit-mode srcip --hashlimit-name ssh_limit -j DROP
  2. Allow connections below the rate limit:

    sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT

    Place the DROP rule before the ACCEPT rule — iptables evaluates rules in order.

How to Verify Rate Limiting with iptables

Monitor the hashlimit counters:

cat /proc/net/ipt_hashlimit/ssh_limit