Linux Kernel Network Tuning & Hairpin NAT Troubleshooting
// 01. The Hairpin NAT (NAT Loopback) Dilemma
Hairpin NAT refers to the scenario where an internal machine on a private subnet attempts to access another internal server using its external, public IP address (or external DNS record). Without proper hairpin translation rules, the gateway forwards the request to the server, but the server sees the client's internal IP and responds directly over the local LAN.
Because the client sent packets to Public IP A, but receives replies from Private IP B, the client kernel immediately sends a RST packet and terminates the connection.
// 02. The iptables SNAT Solution
To resolve this in Linux gateways, both DNAT (Destination NAT) and SNAT (Source NAT) must be executed in tandem:
# 1. DNAT: Rewrite public IP to private server IP in PREROUTING
iptables -t nat -A PREROUTING -d 203.0.113.10 -p tcp --dport 443 \
-j DNAT --to-destination 10.0.1.50:443
# 2. SNAT: Rewrite private source IP to router IP in POSTROUTING
iptables -t nat -A POSTROUTING -s 10.0.1.0/24 -d 10.0.1.50 -p tcp --dport 443 \
-j MASQUERADE Now, the target server sends reply packets back through the gateway, which correctly translates the public source address back before returning to the client.
// 03. High-Throughput Linux sysctl Tuning
When handling 100k+ concurrent TCP connections across edge proxy nodes or load balancers, the default Linux network stack parameters bottleneck performance:
# /etc/sysctl.d/99-network-tuning.conf net.core.somaxconn = 65535 net.ipv4.tcp_max_syn_backlog = 65535 net.ipv4.tcp_tw_reuse = 1 net.ipv4.ip_local_port_range = 1024 65535 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 net.ipv4.tcp_congestion_control = bbr
Enabling Google's BBR congestion control algorithm alongside socket reuse prevents connection saturation and substantially improves throughput over lossy transatlantic links.