Linux Netfilter Conntrack Tuning: Fix Table Full Drops on High-Traffic Servers

Linux tutorial - IT technology blog
Linux tutorial - IT technology blog

Few failures are as deceptive as silent network drops during a traffic surge. Your API gateway throws HTTP 502s. Customers complain about timeouts. Yet CPU and memory look completely idle. When that happens, look at your kernel ring buffer. An entry reading nf_conntrack: table full, dropping packet in dmesg means Netfilter ran out of tracking slots. The kernel drops incoming layer-3 packets instantly—long before NGINX or your Go application ever sees a socket read.

Netfilter conntrack (nf_conntrack) tracks stateful connections for NAT, stateful iptables/nftables rules, and container networking engines like Kubernetes kube-proxy. When traffic ramps past 50,000 concurrent TCP sessions, stock distribution defaults crash into hard limits. Resolving this requires a deliberate balance between table capacity, timeout pruning, and selective bypasses.

Three Ways to Tackle Table Exhaustion

When high connection churn threatens to cap your tracking table, you have three primary engineering strategies:

1. Horizontal Table Expansion (Scaling Limits and Hash Buckets)

This approach raises nf_conntrack_max alongside its companion parameter hashsize. Instead of relying on distro defaults—typically 65,536 entries on a 4GB system or 262,144 on larger VMs—you scale the ceiling to 1,000,000 or 2,000,000 entries. Entries reside in an in-memory hash table. As long as average bucket chain depth stays below 4, lookups remain an efficient O(1) operation.

2. Aggressive Timeout Pruning

Out of the box, Linux retains an established TCP session for up to five days (432,000 seconds) after the last packet. Inactive or dead connections also linger in states like TIME_WAIT and CLOSE_WAIT for up to two minutes. Under this strategy, you keep table dimensions moderate. Instead, you tune sysctl timers to evict dead sockets before they clog the hash buckets.

3. Selective Bypass via Raw Table (NOTRACK)

Stateful inspection is essential for NAT gateways and complex security groups. Stateless public services, however, rarely need it. High-traffic edge proxies, Varnish caches, and public authoritative DNS servers don’t benefit from tracking every inbound handshake. By placing NOTRACK rules in the raw table, you tell Netfilter to skip connection tracking for specific ports or interfaces.

Pros & Cons

Approach 1: Horizontal Table Expansion

  • Pros: Preserves stateful firewall filtering and NAT rules across all services. Requires only a couple of sysctl and modprobe settings. Zero disruption to existing packet flows.
  • Cons: Reserves non-swappable kernel slab memory (kmalloc). Each tracked entry consumes roughly 320 to 352 bytes. Allocating 2,000,000 entries locks roughly 640–700 MB of system RAM exclusively for connection headers. If you bump nf_conntrack_max without increasing hashsize, bucket linked lists grow long. This spikes CPU cache misses and increases ksoftirqd overhead during traffic floods.

Approach 2: Aggressive Timeout Pruning

  • Pros: Reclaims table capacity immediately without spending extra system memory. Purges half-closed sessions left behind by abrupt client disconnections or network scans.
  • Cons: Aggressive limits risk killing legitimate idle TCP connections. Long-lived database connection pools, gRPC control channels, or idle WebSockets can drop with sudden TCP resets if client keepalives do not fire frequently enough.

Approach 3: Selective Bypass via NOTRACK

  • Pros: Eliminates tracking overhead entirely for targeted ports. Slashes softirq CPU usage and stops packet drops on extreme ingress paths handling over 150,000 packets per second.
  • Cons: Bypasses stateful matching (-m conntrack --ctstate ESTABLISHED,RELATED). Packets flagged with NOTRACK cannot undergo NAT, which breaks Docker bridge port mappings and Kubernetes kube-proxy iptables masquerading for those flows.

Recommended Production Setup

Production environments get the most resilient results by combining all three methods into a layered configuration:

  1. Scale limits to memory capacity: On an 8GB RAM host, raise nf_conntrack_max to 1,048,576. Set hashsize = nf_conntrack_max / 4 (262,144 buckets) so lookup chains stay short.
  2. Trim stale timeouts: Lower nf_conntrack_tcp_timeout_established from 432,000 down to 43,200 seconds (12 hours). Compress TIME_WAIT from 120 seconds down to 30 seconds. On our ingress nodes during a 45,000 req/s flash sale, this timeout trim alone dropped table utilization from 92% to 28%.
  3. Exempt stateless endpoints: If you run HAProxy or NGINX receiving high volumes on ports 80 and 443 with direct routing or host networking, exempt that ingress traffic using raw table rules.

Implementation Guide

Step 1: Check Current Limits and Drop Counters

Start by auditing your current table utilization:

# View current active tracked connections
sysctl net.netfilter.nf_conntrack_count

# View current maximum allowed connections
sysctl net.netfilter.nf_conntrack_max

# Check the active hash table bucket count
cat /sys/module/nf_conntrack/parameters/hashsize

Next, confirm whether the kernel has dropped packets due to an exhausted table:

# Check kernel logs for drop alerts
dmesg -T | grep -i "nf_conntrack: table full"

# Inspect drop counters directly from the netfilter stats file
cat /proc/net/stat/nf_conntrack

In /proc/net/stat/nf_conntrack, column 1 is total entries, and column 4 tracks dropped packets. Any non-zero value in column 4 indicates dropped connections.

Step 2: Calculate Kernel Memory Overhead

Never raise limits blindly. Check your budget first. Each conntrack entry consumes roughly 320 bytes in kernel slab memory:

  • 262,144 entries ≈ 84 MB RAM
  • 524,288 entries ≈ 168 MB RAM
  • 1,048,576 entries ≈ 336 MB RAM
  • 2,097,152 entries ≈ 672 MB RAM

Allocating 524,288 entries on a 4GB instance costs roughly 4.2% of total RAM. That is a safe trade-off for a dedicated web server or database proxy.

Step 3: Apply Sizing and Timeouts at Runtime

The hashsize parameter is a kernel module option managed through /sys, while nf_conntrack_max uses sysctl:

# 1. Update hashsize first (target 1:4 ratio with max)
echo 131072 | sudo tee /sys/module/nf_conntrack/parameters/hashsize

# 2. Update the max connection threshold
sudo sysctl -w net.netfilter.nf_conntrack_max=524288

# 3. Reduce idle and transitional TCP timeouts (values in seconds)
sudo sysctl -w net.netfilter.nf_conntrack_tcp_timeout_established=43200
sudo sysctl -w net.netfilter.nf_conntrack_tcp_timeout_time_wait=30
sudo sysctl -w net.netfilter.nf_conntrack_tcp_timeout_close_wait=30
sudo sysctl -w net.netfilter.nf_conntrack_tcp_timeout_fin_wait=30
sudo sysctl -w net.netfilter.nf_conntrack_tcp_timeout_syn_recv=15

Step 4: Persist Configurations Across Reboots

Runtime changes revert upon reboot. Write your sysctl parameters to a drop-in configuration file:

sudo tee /etc/sysctl.d/99-conntrack-tuning.conf << 'EOF'
# Conntrack table size limit
net.netfilter.nf_conntrack_max = 524288

# TCP connection lifetime tuning (seconds)
net.netfilter.nf_conntrack_tcp_timeout_established = 43200
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 30
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 30
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 30
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 15
EOF

Because hashsize is a module option rather than a standard sysctl knob, set it in modprobe.d:

sudo tee /etc/modprobe.d/conntrack.conf << 'EOF'
options nf_conntrack hashsize=131072
EOF

Apply the new sysctl values immediately:

sudo sysctl --system

Step 5: Exempt Stateless Ingress Traffic (Optional)

If your node runs an edge reverse proxy and does not depend on NAT for public web traffic, bypass tracking on ports 80 and 443:

# Bypass conntrack for ingress and return web traffic on eth0
sudo iptables -t raw -A PREROUTING -i eth0 -p tcp -m multiport --dports 80,443 -j NOTRACK
sudo iptables -t raw -A OUTPUT -o eth0 -p tcp -m multiport --sports 80,443 -j NOTRACK

For modern systems running nftables, add a raw priority chain rule:

table ip raw {
    chain prerouting {
        type filter hook prerouting priority -300; policy accept;
        iifname "eth0" tcp dport { 80, 443 } notrack
    }
}

Step 6: Monitor Table Health Under Load

Inspect active states using the conntrack command-line tool (package: conntrack on Debian/Ubuntu, conntrack-tools on RHEL/Rocky):

# Show summary counters, drop stats, and search failures
conntrack -S

# Breakdown of tracked TCP connections by state
conntrack -L -p tcp 2>/dev/null | awk '{print $4}' | sort | uniq -c | sort -nr

A properly tuned table keeps average bucket depth under 4 and prevents dropped packets during unexpected traffic spikes—all without wasting gigabytes of system memory.

Share: