Skip to content
masdzub.com
~/articles/nftables — one from the notebook

Rate-Limiting SYN Floods with nftables on an Nginx Server

Use nftables per-source rate limits, SYNPROXY, kernel SYN cookies, and Nginx backlog tuning to stop SYN floods. Includes full configs and troubleshooting.

masdzub@website:~$ cat ~/articles/using-nftables-to-rate-limit-syn-floods-on-an-nginx-web-server.aspx.md
# 1 file · 16 min read · topic: nftables · status: published

Introduction

A SYN flood against Nginx is stopped at the kernel packet path with an nftables meter that caps SYN packets per source IP, backed by SYN cookies so the listen backlog never fills. The recipe has four layers: enable SYN cookies and enlarge the backlog, add nftables rules that drop excess SYNs before they reach conntrack, optionally hand the handshake to SYNPROXY, and tune Nginx to accept the surviving connections without worker exhaustion. On a two-core VPS running Debian 12, this configuration absorbs a 200,000-packet-per-second SYN flood from a single hping3 source with no measurable increase in time-to-first-byte for real visitors.

Each layer has a real trade-off. SYN cookies drop some TCP options on the SYN-ACK, so throughput to legitimate clients can dip on older kernels. SYNPROXY consumes kernel memory per half-open connection and needs careful rule ordering. Per-IP rate limits fold under a distributed attack with ten thousand unique IPs, so the limit needs a global companion or a valid traffic baseline. The configurations below are the ones that survived those constraints in production on Debian 12, Ubuntu 22.04, and Rocky Linux 9.

How a SYN flood exhausts a server

The TCP three-way handshake begins with a client sending SYN. The kernel allocates a request socket, stores it in the SYN queue, and replies with SYN-ACK. When the client’s ACK arrives, the kernel moves the entry to the accept queue and Nginx can pick it up. Both queues have a finite size. net.ipv4.tcp_max_syn_backlog bounds the SYN queue. The listen() backlog argument combined with net.core.somaxconn bounds the accept queue.

A flood of SYNs without matching ACKs fills the SYN queue. Once it is full, the kernel drops new legitimate SYNs, and from the outside the server looks alive because SYN-ACK replies still leave but connections never complete. Nginx cannot help here because the application does not see a connection until the handshake finishes. The defense has to happen in the kernel, which is exactly the layer that nftables and SYN cookies operate on.

A second-order symptom appears on servers with connection tracking enabled. Every half-open connection consumes a nf_conntrack entry, so the flood fills the conntrack table before the SYN queue is exhausted. The kernel logs nf_conntrack: table full, dropping packet and drops all new connections until existing entries expire. Raising nf_conntrack_max and shortening the SYN_RECV timeout are both required to keep the table from filling under sustained flood.

Checking what the kernel already provides

Default settings on Debian 12 and Ubuntu 22.04 already enable SYN cookies and set reasonable queue limits. Before changing anything, read the current values:

sysctl net.ipv4.tcp_syncookies \
net.ipv4.tcp_max_syn_backlog \
net.core.somaxconn \
net.ipv4.tcp_synack_retries \
net.netfilter.nf_conntrack_max

A stock Debian 12 install returns tcp_syncookies = 1, tcp_max_syn_backlog = 128 on small-memory instances or 4096 on larger ones, somaxconn = 4096, tcp_synack_retries = 5, and nf_conntrack_max = 65536. The backlog values are small for a public web server, and nf_conntrack_max is small because every tracked connection consumes an entry.

Check the current queue usage with ss -s. The output looks like:

Total: 203
TCP: 142 (estab 89, closed 12, orphaned 0, timewait 3)
Transport Total IP IPv6
RAW 0 0 0
UDP 7 5 2
TCP 130 91 39

An estab count close to tcp_max_syn_backlog during a flood is the smoking gun. Also check nstat -az TcpExtSyncookiesSent TcpExtSyncookiesRecv TcpExtListenOverflows TcpExtListenDrops. A rising ListenOverflows means the accept queue is filling. A rising SyncookiesSent while the flood is active is expected; a SyncookiesSent count that stays high after the flood has ended points to a stuck queue that needs investigation.

Enabling SYN cookies and enlarging the queues

SYN cookies replace the per-connection state with a cryptographic hash of the source and destination tuple stored in the sequence number. The kernel sends a SYN-ACK whose sequence number encodes the handshake parameters. When the client’s ACK returns, the kernel verifies the hash and reconstructs the connection. This is why SYN cookies do not need a SYN queue at all.

net.ipv4.tcp_syncookies has three settings. 0 disables them, 1 enables them only when the SYN queue overflows, and 2 enables them unconditionally. The conditional mode in 1 is the right choice for a normal server because it avoids the option loss for legitimate clients until a flood actually starts. Set it to 1 unless the server sits under constant attack, in which case 2 removes the last bit of per-SYN state.

Drop a file into /etc/sysctl.d/ so the settings survive a reboot:

/etc/sysctl.d/99-syn-flood.conf
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 65536
net.core.somaxconn = 65535
net.ipv4.tcp_synack_retries = 3
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_abort_on_overflow = 0
net.netfilter.nf_conntrack_max = 262144
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 30

Load them with sysctl --system and verify with sysctl -p /etc/sysctl.d/99-syn-flood.conf. tcp_synack_retries = 3 sends three SYN-ACK retries over seven seconds before giving up, enough for a client on a slow link and short enough that half-open entries turn over quickly. tcp_fin_timeout = 15 reduces time spent in FIN-WAIT-2. nf_conntrack_tcp_timeout_syn_recv = 30 halves the default half-open timeout, which doubles the recovery rate during a flood.

The larger nf_conntrack_max matters because conntrack still tracks established connections after SYN cookies accept them. On a server with 10,000 concurrent users, the table needs at least 100,000 entries with headroom. The value of 262144 assumes 4 GB of RAM, since each entry costs roughly 300 bytes of kernel memory outside the hash table.

The nftables rate-limit rule

The core defense is a per-source SYN limit enforced in the input hook. This configuration drops SYNs above 20 packets per second from any single IP, with a burst allowance of 50:

/etc/nftables.conf
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
chain input {
type filter hook input priority filter; policy accept;
# Accept established and related traffic early
ct state established,related accept
ct state invalid counter drop
# Always allow loopback
iif lo accept
# Allow ICMP and essential protocols
ip protocol icmp accept
ip6 nexthdr icmpv6 accept
# Rate-limit pure SYN packets per source IP
tcp flags & (fin|syn|rst|ack) == syn \
meter syn_flood size 65536 \
{ ip saddr timeout 30s limit rate 20/second burst 50 } \
counter accept
# Drop any remaining SYN packets above the per-IP limit
tcp flags & (fin|syn|rst|ack) == syn \
counter drop
# Allow the rest of the traffic to listening services
tcp dport { 22, 80, 443 } accept
udp dport { 53, 123 } accept
}
}

Load the ruleset with nft -f /etc/nftables.conf. The meter keyword creates a dynamic set keyed on ip saddr, and limit rate 20/second applies per set entry. The timeout 30s argument releases each entry 30 seconds after the last packet, so a scanner that rotates IP every second does not exhaust memory. The size 65536 ceiling costs about 8 MB of kernel memory and covers legitimate source IPs plus a reasonable burst of scanners. If the set overflows, nft either drops packets silently or logs nft: Get Operation caused a table full, depending on version. Either outcome is safer than letting the SYN queue absorb the attack.

The meter and limit combination reads as one rule, but nftables evaluates the limit before the action. A packet under the rate hits the accept, while a packet over the rate fails the limit and falls through to the drop. This is the canonical negation pattern in nftables, and reordering the two rules breaks it.

Adjust the rate to match the traffic profile. A marketing site behind Cloudflare sees one IP for every thousand visitors because of the proxy, so the per-IP limit needs to be much higher, often 200 or 500 per second. A direct-connect API server with real client IPs can stay at 20. The burst should be about 2.5 times the rate to absorb connection pools that open several sockets at once.

SYNPROXY for offloading the handshake

Rate limiting alone drops excess SYNs at the firewall, but every accepted SYN still consumes a kernel request socket and generates a SYN-ACK. On very large floods this still burns CPU. SYNPROXY takes over the handshake: the kernel replies with a SYN-ACK containing a valid cookie, and only after the client’s ACK is verified does the kernel allocate the request socket and forward the connection to Nginx.

SYNPROXY in nftables requires kernel 4.4 or newer for the synproxy statement, and it depends on the nf_conntrack and nft_synproxy modules. The configuration works alongside the rate-limit rule:

table inet filter {
chain raw_prerouting {
type filter hook prerouting priority raw; policy accept;
# Skip conntrack for incoming SYNs on HTTP and HTTPS
tcp dport { 80, 443 } tcp flags syn notrack
}
chain prerouting {
type filter hook prerouting priority filter - 1; policy accept;
# Hand untracked SYNs to the synproxy module
tcp dport { 80, 443 } \
ct state invalid,untracked \
synproxy mss 1460 wscale 7 timestamp sack-perm
}
}

The two-chain structure is what makes SYNPROXY work. The raw_prerouting chain at priority raw (-300) runs before connection tracking. tcp flags syn notrack tells conntrack to skip the SYN, which prevents the kernel from allocating a conntrack entry before SYNPROXY has verified the client. The prerouting chain at priority filter - 1 runs after conntrack, sees the packet as untracked, and hands it to synproxy with the MSS, window scale, timestamp, and SACK options the proxy advertises to the client.

The -1 priority offset is easy to miss. If both chains were at filter (priority 0), SYNPROXY would run before the packet was marked notrack, and the kernel would create conntrack entries for every SYN, defeating the purpose. The offset places the SYNPROXY chain just before the regular filter chain so the notrack mark is visible.

SYNPROXY has a memory cost: the kernel allocates a synproxy structure per active half-open connection, roughly 256 bytes. On a VPS with 2 GB of RAM, a flood of one million half-open connections would exhaust memory, so the nftables rule should still be paired with a global rate limit. In practice SYNPROXY handles floods up to the memory limit better than the SYN queue because per-entry cost is lower and entries turn over on the client ACK rather than the SYN-ACK timeout.

The nf_conntrack module must be loaded before the ruleset loads. Check with lsmod | grep nf_conntrack and load with modprobe nf_conntrack nft_synproxy if missing. On systems that do not ship the connection tracking module, SYNPROXY is unavailable and the rate-limit rule is the only option.

Tuning Nginx for the surviving connections

Once the firewall has filtered the flood, Nginx needs to accept the surviving connections without exhausting its worker pool. The listen directive takes a backlog argument that sets the accept queue for that socket:

/etc/nginx/nginx.conf
user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 16384;
multi_accept on;
use epoll;
}
http {
client_header_timeout 10s;
client_body_timeout 15s;
keepalive_timeout 30s;
keepalive_requests 1000;
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
limit_req_zone $binary_remote_addr zone=req_per_ip:10m rate=10r/s;
server {
listen 80 backlog=65535;
listen 443 ssl backlog=65535;
limit_conn conn_per_ip 50;
limit_req zone=req_per_ip burst=20 nodelay;
# ... rest of server config
}
}

The listen backlog=65535 value needs to match or exceed net.core.somaxconn. If somaxconn is lower than the backlog argument, the kernel silently uses the smaller value. Nginx logs worker_connections are not enough if the number of accepted connections exceeds worker_connections multiplied by the number of worker processes. A two-core server with worker_processes auto (2 workers) and worker_connections 16384 caps at 32,768 concurrent connections, which covers any realistic traffic profile. worker_rlimit_nofile must be at least twice worker_connections to account for client plus upstream file descriptors.

The limit_conn_zone and limit_req_zone directives add two more layers of filtering per source IP. limit_conn conn_per_ip 50 blocks any client with more than 50 concurrent connections, which catches browser tab spam and misbehaving scrapers. limit_req zone=req_per_ip burst=20 nodelay allows 10 requests per second with a burst of 20, generous for a human browsing and tight for a scripted attack. nodelay serves the burst without queueing, so real users see no latency.

multi_accept on makes each worker accept multiple connections per event loop iteration, which speeds up drain of the accept queue after a flood. use epoll is the default on Linux, but stating it explicitly helps during an audit that might otherwise wonder if select or poll is active on an older host.

Testing the configuration

Generate a SYN flood from a separate host with hping3:

sudo hping3 -S --flood -V -p 80 203.0.113.10

Watch the counters on the target:

watch -n1 'nft list ruleset -a | grep -A3 "meter syn_flood"'
watch -n1 'nstat -az TcpExtSyncookiesSent TcpExtSyncookiesRecv TcpExtListenOverflows'
watch -n1 'conntrack -C'

SyncookiesSent should rise immediately and stay high while the flood runs. ListenOverflows should stay near zero if SYN cookies work and the queue is not filling. If ListenOverflows rises with the flood, the accept queue is still overflowing, which usually means the nginx.conf backlog is not applied or somaxconn is smaller than expected.

From a second host with a normal browser, load the server during the flood and check the page load time. If pages return in under a second, the rules are working. If they time out, either the rate limit is too tight for the real traffic or SYNPROXY is malfunctioning. A curl -w '%{time_total}\n' -o /dev/null -s https://203.0.113.10/ during the flood gives a number instead of a feel.

For a scapy-based generator that runs without hping3:

from scapy.all import IP, TCP, send
import random
target = "203.0.113.10"
for i in range(100000):
src = f"198.51.100.{random.randint(1,254)}"
pkt = IP(src=src, dst=target) / TCP(
sport=random.randint(1024, 65535), dport=80, flags="S"
)
send(pkt, verbose=False)

The random source IPs simulate a distributed attack better than hping3 --flood from a single source, which the per-IP meter stops in a fraction of a second. A distributed test verifies that the meter handles many distinct keys without exhausting the set.

Troubleshooting real failures

The first deployment on Rocky Linux 9 produced this error when loading the ruleset:

Error: Could not process rule: Operation not supported

The cause was a kernel that did not have CONFIG_NFT_SYNPROXY compiled in, which is the case on some minimal cloud images. modprobe nft_synproxy and modprobe nf_conntrack fix the error on kernels that include the modules. On Debian 12 and Ubuntu 22.04 the modules autoload through the nftables service, and the error does not appear.

A second failure appears during a flood when conntrack fills:

nf_conntrack: table full, dropping packet

This is a kernel message in dmesg that means nf_conntrack_max has been reached. Raise the value and shorten the timeout, which the sysctl snippet above does. If the table still fills, the ct state invalid drop rule is not catching enough traffic. Adding ct state untracked counter drop to the raw chain catches non-TCP traffic before conntrack.

SYNPROXY rules that silently do nothing usually mean the notrack rule is not running. Verify with nft monitor trace while a test SYN arrives from a separate host. The trace shows which chains the packet traverses. If the SYN appears in prerouting with ct state new instead of untracked, the raw_prerouting chain is at the wrong priority or has an accept statement that fires before the notrack. Move the notrack up, and confirm the chain policy is accept.

A third failure is a ruleset that silently drops all connections after a restart. flush ruleset at the top of /etc/nftables.conf wipes the running ruleset before loading the new one, so if the new ruleset fails to parse, the server has no firewall at all. Test changes with nft -c -f /etc/nftables.conf in check mode before applying. The check prints syntax errors and exits non-zero, letting a reload script abort instead of leaving the host exposed.

The nft list ruleset -a output shows a handle for each rule, which is needed to modify rules individually with nft replace rule and nft delete rule. During an incident, nft add rule inet filter input handle 12 counter drop inserts emergency rules without rewriting the file. The handle numbers change on every reload, so scripts that delete by handle must re-query the handle immediately before the delete.

Trade-offs and when not to use this

The setup has four costs. SYN cookies lose the TCP window scaling option on the SYN-ACK on kernels before the window-scale preservation patch, which caps throughput per connection at 64 KB in flight, so large file downloads to well-connected clients run slower until the kernel catches up. SYNPROXY adds kernel memory per half-open connection and requires more careful rule ordering than plain rate limiting. Per-IP rate limits are weak against a distributed attack because a botnet with 10,000 unique IPs fits under a 20/s per-IP limit at 0.002 packets per second per IP. Nginx-level limits duplicate some of the firewall work and consume a small amount of per-worker CPU on every request.

On Cloudflare or another reverse proxy in front of Nginx, the ip saddr in nftables is the proxy IP, not the client IP, so the per-IP meter rate-limits indiscriminately across the whole user base. In that case, either disable the per-IP meter and rely on a global limit, or enable the real_ip module in Nginx and move the per-client limit to Nginx. set_real_ip_from 173.245.48.0/20 and real_ip_header CF-Connecting-IP restore the client IP for Nginx’s own limit_req and limit_conn zones, but the nftables meter still sees the proxy IP.

The cleanest architecture for a proxied server is to rate-limit at the proxy and reserve nftables for port filtering and global SYN rate limits. The proxy absorbs the volumetric part of the flood, and the origin server handles a small, pre-filtered trickle. For a direct-connect server under 10,000 SYN per second, the nftables per-IP rule plus SYN cookies is enough without SYNPROXY. SYNPROXY becomes worthwhile around 50,000 sustained SYN per second, which is where kernel SYN-ACK generation starts competing with Nginx for CPU. The configuration above scales to that point without modification, and below it the SYNPROXY chains can be dropped without touching the rest of the ruleset.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.