nf_conntrack under pressure: how the table fails
How the Linux conntrack table hashes, evicts and races, why Kubernetes nodes meet each failure, and a rootless lab on Linux 7.2 that reproduces them.
Connection tracking is the part of the Linux network stack that Kubernetes depends on most and documents least. Every packet to a ClusterIP is rewritten by a DNAT rule whose decision lives in a conntrack entry; every reply finds its way back to the client through the same entry; every masquerade to an address outside the cluster needs one. kube-proxy in its iptables and nftables modes is, from the kernel's point of view, a rule set that tells conntrack what to remember.
The thing doing the remembering is a single hash table per host. It is shared by every network namespace on the node, accounted per namespace against one global limit, protected by a fixed array of spinlocks, and filled by an insertion protocol that deliberately leaves a window in which two CPUs can create the same connection. Each of those properties has a failure mode, and each failure mode has its own counter that most dashboards do not export. This article walks the code paths in Linux v7.2, which is the kernel the lab runs, and ties each one to a counter you can read and a namespace experiment you can repeat.
My position, stated up front: on a current kernel the famous DNS race is mostly solved, and the remaining risk on a busy node is the table itself. It fills with flows that finished long ago, it evicts in a way that protects the wrong entries for some workloads, and its chain length is a failure mode in its own right. Tuning nf_conntrack_max upward without understanding the other two is how a node trades a loud failure for a quiet one.
What the kernel stores for a flow
A connection is identified by a tuple. struct nf_conntrack_tuple splits it into a source half that NAT may rewrite (struct nf_conntrack_man: address, port or ICMP id, layer 3 protocol) and a destination half that it may not: address, port, layer 4 protocol number and a direction byte1. Between the protocol number and the direction sits an empty struct, __nfct_hash_offsetend. It occupies no memory and exists only so the hash function can say "hash everything up to here" and leave the direction out12.
struct nf_conntrack_tuple {
struct nf_conntrack_man src; /* u3 address, u port/id, l3num */
struct {
union nf_inet_addr u3;
union { __be16 all; /* tcp, udp, icmp, sctp, gre ... */ } u;
u_int8_t protonum;
struct { } __nfct_hash_offsetend; /* hash input ends here */
u_int8_t dir; /* ORIGINAL or REPLY */
} dst;
};
/* Connections have two entries in the hash table: one for each way */
struct nf_conntrack_tuple_hash {
struct hlist_nulls_node hnnode;
struct nf_conntrack_tuple tuple;
};The connection itself is struct nf_conn, and the field that matters for this article is tuplehash[IP_CT_DIR_MAX]: an array of two nf_conntrack_tuple_hash nodes, one for the original direction and one for the reply. Both nodes are linked into the same hash table, usually in different buckets. That is why the kernel documentation warns that a table holding nf_conntrack_max connections holds twice as many hash nodes, and why the default sizing aims at an average chain length of two rather than one3.
The reply tuple is where NAT becomes visible. When kube-proxy's rules send a packet for 10.96.0.10:53 to a pod at 10.244.1.7:53, the original tuple keeps the Service address and the reply tuple records the pod address as its source. A reply from the pod hashes to the reply node, the kernel finds the connection, and the reverse translation follows from comparing the two tuples. Nothing about NAT is stored separately; the two tuples are the NAT state.
Lifecycle lives in ct->status, a bit field defined in the UAPI header4. Five bits explain almost every behaviour below.
| Bit | Name | Set when | Why it matters here |
|---|---|---|---|
| 1 | IPS_SEEN_REPLY | A packet matched the reply tuple | Required before UDP can switch to the 120 s replied timeout; the switch also needs traffic after the two-second stream_ts mark |
| 2 | IPS_ASSURED | UDP: replied and still active after two seconds; TCP: a valid ACK takes the connection to ESTABLISHED | Assured entries are never evicted by early_drop() |
| 3 | IPS_CONFIRMED | The entry was inserted into the hash table | Unconfirmed entries are invisible to other CPUs |
| 10 | IPS_FIXED_TIMEOUT | Timeout must not be refreshed by traffic | Used for clash entries that should die in one second |
| 12 | IPS_NAT_CLASH | Entry lost an insertion race under NAT | Shares bit 12 with IPS_UNTRACKED; kernel-internal only |
The UDP rule for IPS_ASSURED is in nf_conntrack_udp_packet(). Before confirmation it stamps stream_ts = 2 * HZ + jiffies; once a reply has been seen and the clock has passed that stamp, the entry gets the 120 second replied timeout and the assured bit5. A DNS query and its answer finish well inside two seconds, so ordinary DNS flows are never assured, and the answer refreshes the entry with the same 30 second unreplied timeout as the query5. For TCP the bit is set in nf_conntrack_tcp_packet() when a valid ACK moves the connection from SYN_RECV into ESTABLISHED6. Remember both rules; they decide who survives when the table is full.
One hash table for every namespace
nf_conntrack_hash is a single array of hlist_nulls_head, allocated once in nf_conntrack_init_start()7. There is no per-namespace table. hash_conntrack_raw() runs SipHash over the tuple bytes up to __nfct_hash_offsetend, with a random key generated once per boot; it XORs the conntrack zone id into the first key word and net_hash_mix(net) into the second, so the same tuple in two namespaces lands in different buckets of the same array7. reciprocal_scale() then maps the 32 bit hash onto the bucket count without a division. The current shape dates from v6.5, when the hashing was changed to stop folding ports into addresses before hashing because that made colliding tuples easy to construct2.
Lookups are lockless. ____nf_conntrack_find() walks a bucket under RCU and compares candidates with nf_ct_key_equal(), which checks the tuple, the zone, the confirmed bit and the namespace7. Because nf_conn objects come from a SLAB_TYPESAFE_BY_RCU cache, an entry can be freed and reused for a different connection while a reader is looking at it. The table defends against that with nulls markers: nf_ct_alloc_hashtable() terminates every bucket with a nulls value equal to the bucket index, and a reader that reaches the end of a chain and finds a different index knows it was dragged onto another chain and starts over7. That restart is the search_restart counter.
Writers take locks, but not one per bucket. nf_conntrack_locks is an array of CONNTRACK_LOCKS, which is 1024 spinlocks, and a bucket's lock is its index modulo 10247. Inserting a connection needs two buckets, one per direction, so nf_conntrack_double_lock() takes both locks in index order and then checks the nf_conntrack_generation seqcount; if a resize happened in the meantime it drops the locks and recomputes both hashes7. A resize, triggered by writing nf_conntrack_buckets or the hashsize module parameter from the initial namespace, calls nf_conntrack_all_lock(), which takes the global nf_conntrack_locks_all_lock, sets nf_conntrack_locks_all, and then locks and immediately unlocks each of the 1024 striped locks to wait out their current holders78. From that point every writer that calls nf_conntrack_lock() sees the flag, falls into the slow path and blocks on the global lock, so every conntrack insert and delete on the host waits until the rehash of every entry into the new array has finished7. That is cheap on an idle box and an unpleasant pause on a busy one, which is the practical reason to size the table at boot.
How the table is sized
int max_factor = 8;
if (!nf_conntrack_htable_size) {
nf_conntrack_htable_size
= (((nr_pages << PAGE_SHIFT) / 16384)
/ sizeof(struct hlist_head));
if (BITS_PER_LONG >= 64 &&
nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
nf_conntrack_htable_size = 262144;
else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
nf_conntrack_htable_size = 65536;
if (nf_conntrack_htable_size < 1024)
nf_conntrack_htable_size = 1024;
max_factor = 1;
}
...
nf_conntrack_max = max_factor * nf_conntrack_htable_size;Any 64 bit machine with more than 4 GiB of RAM gets 262144 buckets and, because no size was given, a limit equal to the bucket count73. The lab host, with 62 GiB, reports exactly nf_conntrack_buckets = 262144 and nf_conntrack_max = 262144. If you pass hashsize= to the module, the old factor of 8 applies instead, so an explicit bucket count silently multiplies the designed load per bucket by eight: at a full table, 16 hash nodes per bucket instead of 2, because every entry is hashed once per direction. The comment in the source explains the choice: a factor of one keeps the average chain at two entries.
Accounting per namespace, limit per host
The entry count is not global. __nf_conntrack_alloc() increments cnet->count, which lives in the per-namespace struct nf_conntrack_net, and compares it with the global nf_conntrack_max7. Outside the initial namespace the nf_conntrack_max and nf_conntrack_buckets sysctls are registered read-only, and nf_conntrack_count points at that namespace's own counter8. The consequence is easy to miss: every namespace that tracks connections may hold up to nf_conntrack_max entries of its own, and all of them share the host's buckets and locks. The limit protects each namespace from itself. It does not bound the table.
A namespace also tracks nothing until a rule needs it. The conntrack hooks are registered per namespace through nf_ct_netns_get() when a rule that depends on conntrack is loaded9. In the lab (norule.sh), a fresh namespace sent 100 UDP datagrams and conntrack -C stayed at 0; after adding one ct state new counter rule, another 100 datagrams produced 100 entries. A pod whose namespace has no NAT or state rules costs the table nothing. A pod that loads such rules inside its own namespace gets its own allowance in the shared table.
Chain length is a failure mode of its own
Since v5.15 the kernel refuses to grow a chain without bound. The commit that introduced the check reasoned that with the new defaults chains would average two entries, which allowed a hard ceiling of 64, and added the chaintoolong statistic10. A later change made the ceiling random so that an observer could not learn from drops which tuples share a bucket11. The random range was then too low: in v6.3 Eric Dumazet raised the floor to 50 after customers on GKE 1.25 and 1.26 hit conntrack failures traced to the random limit, with a commit message that tabulates how low limits fail at modest load factors12. In v7.2, __nf_conntrack_confirm() draws max_chainlen = MIN_CHAINLEN + get_random_u32_below(MAX_CHAINLEN), which is 50 to 79, walks both target buckets, and on overflow increments chaintoolong and insert_failed and drops the packet7. The test is if (chainlen++ > max_chainlen), so the refusal comes only when a bucket already holds more than max_chainlen + 1 other nodes, roughly 52 to 81.
Here kube-proxy deserves a closer look. At v1.37.2 it computes a desired nf_conntrack_max of 32768 per CPU with a floor of 131072, caps the result at 1048576, writes it only if the current value is lower, and raises hashsize only if the current bucket count is below a quarter of the new maximum1314. Applied to the kernel defaults above, that gives the following design points.
| Node | Kernel buckets and max | kube-proxy desired max | Buckets after kube-proxy | Hash nodes per bucket when full |
|---|---|---|---|---|
| 4 CPUs, 16 GiB | 262144 / 262144 | 131072 (floor; not written, current is higher) | 262144 | 2 |
| 16 CPUs, 64 GiB | 262144 / 262144 | 524288 | 262144 (not below 524288 / 4) | 4 |
| 64 CPUs, 256 GiB | 262144 / 262144 | 1048576 (capped from 2097152) | 262144 (not below 1048576 / 4) | 8 |
Eight is still far from a floor of 50, so on a host with one busy namespace kube-proxy's rule is safe. The table is the wrong mental model, though, because it assumes one namespace. Every namespace that tracks connections adds its own population to the same 262144 buckets, and none of them is visible in the host's nf_conntrack_count. If you raise the limit by hand, raise the bucket count with it and keep 2 * nf_conntrack_max / nf_conntrack_buckets close to the kernel's own design point of two.
Allocation, early drop and the full table
A new connection is born in resolve_normal_ct(). The tuple is hashed once with hash_conntrack_raw(), the lookup misses, and init_conntrack() inverts the tuple and calls __nf_conntrack_alloc()7. That function does the accounting first, with atomic_inc_return(&cnet->count), so that two CPUs cannot both slip under the limit. If the new count exceeds nf_conntrack_max, it calls early_drop(net, hash) before allocating anything7.
early_drop() is narrower than its name suggests. It looks at up to NF_CT_EVICTION_RANGE, which is 8, consecutive buckets starting at the new connection's own bucket. In each bucket early_drop_list() deletes every entry that belongs to the same namespace, is confirmed, is not dying and is not assured, and the scan stops at the first bucket that yielded at least one deletion7. At the default design load of two nodes per bucket, that is a look at about sixteen hash nodes, shared with every other namespace. If none qualifies, the allocation fails: the kernel sets a flag for the garbage collector, decrements the count, logs nf_conntrack: table full, dropping packet (in v7.2, table full in netns %u outside the initial namespace), and returns -ENOMEM7. nf_conntrack_in() turns that into NF_DROP and increments drop7.
The flag changes how the garbage collector behaves. gc_worker() normally walks buckets for at most 10 ms per run and reaps expired entries. Once early_drop is set, it computes nf_conntrack_max95 = nf_conntrack_max / 100u * 95u and, in any namespace whose count is at or above that mark, also kills confirmed entries that are not assured or whose protocol tracker says they can go7. For TCP, tcp_can_early_drop() answers yes for FIN_WAIT, LAST_ACK, TIME_WAIT, CLOSE and CLOSE_WAIT6.
What ASSURED protects, and what it does not
Put the two rules together and the eviction policy is clear: when the table is full, the kernel sacrifices unreplied and short-lived flows to protect established ones. That is the right policy against a SYN flood or a port scan, and it explains the first half of the lab, where 300000 unreplied UDP flows hit a limit of 262144 and nothing was dropped at all: early_drop absorbed 37861 evictions and the count settled at 262139. A repeat run gave 37856 evictions and a count of exactly 262144; the small difference comes from early_drop_list() clearing every eligible entry in a bucket rather than one.
It is the wrong policy when the protected population is itself the problem. Assured entries are only removed by their timers or by an explicit delete, so a table full of long-idle established TCP connections cannot make room for a new SYN. The second half of the lab loaded 262144 assured UDP entries through conntrack -R and then sent 1000 new datagrams: all 1000 sendto() calls failed with EPERM, and drop rose by exactly 1000. A locally generated packet dropped in LOCAL_OUT is reported to the application as a permission error, which is a misleading thing to find in an application log at 03:00.
Timers are therefore the real capacity control, and the defaults are generous in exactly the place that hurts.
| Sysctl | Kernel default | kube-proxy v1.37.2 default | Comment |
|---|---|---|---|
nf_conntrack_udp_timeout | 30 s3 | left as is unless configured15 | Every UDP flow that has not become a stream, answered or not: each ordinary DNS query and its answer hold an entry this long5 |
nf_conntrack_udp_timeout_stream | 120 s3 | left as is unless configured15 | Replied UDP still active after two seconds |
nf_conntrack_tcp_timeout_established | 432000 s, five days3 | 24 h14 | A peer that vanishes without FIN or RST holds an assured entry this long |
nf_conntrack_tcp_timeout_close_wait | 60 s3 | 1 h14 | Raised on purpose so SNAT state outlives lazy socket closes; early-droppable under pressure |
The CLOSE_WAIT row is the interesting one. kube-proxy raises it from one minute to one hour, and the comment in its defaults explains why: if the entry expires while the local socket is still half open, the eventual FIN is no longer SNAT'd, the remote side keeps stale state, and a later connection reusing the same source pair can be refused14. That is a reasonable trade, and the kernel limits its cost, because CLOSE_WAIT is one of the states tcp_can_early_drop() gives up under pressure6. The established timeout has no such escape hatch. I would rather see it at a few hours on nodes that front many short-lived clients than at a day, provided the workloads use keepalives shorter than that.
The insertion race
Conntrack does not insert a connection when it creates it. It creates the entry when the first packet reaches the conntrack hook, NF_IP_PRI_CONNTRACK at -200 in PRE_ROUTING or LOCAL_OUT, lets the rest of the rule set run with that private entry attached to the packet, including DNAT at NF_IP_PRI_NAT_DST (-100), and inserts it only when the packet leaves through nf_confirm at NF_IP_PRI_CONNTRACK_CONFIRM in POST_ROUTING or LOCAL_IN916. Until then the entry is, in the words of the netfilter maintainers, private to the CPU17. The design avoids taking bucket locks for packets that the rule set is going to drop anyway, and it lets NAT rewrite the reply tuple freely before anyone can see it.
The price is a window. If a second packet with the same original tuple arrives on another CPU before the first is confirmed, its lookup misses too and it gets its own private entry. Both reach __nf_conntrack_confirm(). That function reuses the original-direction hash that __nf_conntrack_alloc() stashed in the unused pprev slot of the reply node, computes the reply hash fresh because NAT may have changed the reply tuple, takes both bucket locks and walks both chains7. The loser finds the winner and calls nf_ct_resolve_clash().
- If the protocol tracker does not set
allow_clash, the packet is dropped and bothdropandinsert_failedare incremented. TCP never sets it76. - If the two entries match in both directions,
__nf_ct_resolve_clash()merges them: the loser's accounting is folded into the winner, the packet is re-pointed at the winner, andclash_resolveis incremented. For NAT'd flows this has worked since v4.19, when Martynas Pumputis re-enabled it for the case of two threads writing to the same UDP socket18. - If only the original direction clashes and the reply tuple is unique, which is what happens when two packets of one flow were DNAT'd to different backends,
nf_ct_resolve_clash_harder()inserts the loser in the reply direction only, fakes the original node withhlist_nulls_add_fake(), setsIPS_FIXED_TIMEOUT | IPS_NAT_CLASHand a one second timeout, and incrementsclash_resolve7. This arrived in v5.617.
UDP has allowed clashes for a long time; ICMP joined in v7.0, with a commit message that calls the change not strictly required but harmless for a stateless protocol19. The commit that added the third case draws the race as a timeline on two CPUs, which is the clearest description of it I know:
CPU A: CPU B:
1. 10.2.3.4:42 -> 10.8.8.8:53 (A)
2. 10.2.3.4:42 -> 10.8.8.8:53 (AAAA)
3. Apply DNAT, reply changed to 10.0.0.6
4. 10.2.3.4:42 -> 10.8.8.8:53 (AAAA)
5. Apply DNAT, reply changed to 10.0.0.7
6. confirm/commit to conntrack table, no collisions
7. commit clashing entryWhy DNS is the workload that hits it
Three independent design choices line up. First, glibc's stub resolver sends the A and AAAA queries for a name together: in send_dg() at glibc 2.42, unless single-request mode is on, both queries go out in one sendmmsg() call on one socket20. One socket means one source port, so both packets carry the same original tuple. Second, the Service in front of the cluster DNS server picks a backend at random per new connection: kube-proxy's iptables mode uses -m statistic --mode random --probability, and its nftables mode uses numgen random mod N in a DNAT map2122. Two unconfirmed entries for the same tuple therefore pick independent backends. Third, pods in a cluster typically run with options ndots:5 and a multi-entry search path23, so a single lookup of an external name can become several such query pairs.
Before v5.6, the case where both packets were in flight and drew different backends could not be merged and ended in a drop, counted in insert_failed. The resolver then waited for its timeout, five seconds by default according to resolv.conf(5), before trying again24. glibc even has code for the aftermath: if it times out after receiving only one of the two answers, it sets an internal flag and retries in single-request mode, and failing that in single-request-reopen mode, which closes the socket and opens a new one between the two queries20.
The workarounds follow from the mechanism. options single-request makes glibc wait for the first answer before sending the second query, by which time the first entry is confirmed and the second packet finds it. single-request-reopen goes further and uses a new socket, hence a new tuple, for the second query24. use-vc moves the lookup to TCP, which never races in this way because the handshake serialises the flow24. NodeLocal DNSCache, stable since Kubernetes v1.18, removes the DNAT and the conntrack entry for the pod-to-cache hop altogether; its documentation cites both the races and UDP DNS entries filling the table as reasons25.
On a kernel at v5.6 or later, I do not recommend the resolver options as a fix. The race is resolved in the kernel at the cost of a short-lived hidden entry, and changing resolver behaviour for every pod to work around a solved problem adds latency for nothing. NodeLocal DNSCache is still worth deploying on large nodes, but for the second reason in its documentation: a node that issues many DNS queries per second keeps each of them in the table for 30 seconds whether or not it was answered, because nf_conntrack_udp_packet() refreshes any flow that has not outlived its two second stream mark with nf_conntrack_udp_timeout5. At a steady query rate the table therefore holds about thirty seconds' worth of queries at any moment, and moving that traffic off conntrack is the cheapest table capacity you can buy.
Reading conntrack -S without fooling yourself
conntrack -S shows the in-kernel statistics26. The kernel answers that request with a ctnetlink dump, ctnetlink_ct_stat_cpu_dump(), which emits one message per possible CPU from the per-CPU counters of the requesting socket's namespace27. /proc/net/stat/nf_conntrack is created per namespace under net->proc_net_stat, and ct_cpu_seq_show() prints the same counters as one row of %08x hexadecimal fields per CPU8. Both are namespace-scoped, so on a node run them in the host namespace, and for a pod that tracks its own connections, inside that pod's namespace. Two of the counters do not mean what their names suggest, which I only noticed because the lab printed zeros where I expected thousands.
| Counter | Incremented in | Read it as |
|---|---|---|
found | nf_conntrack_tuple_taken() | NAT checking whether a candidate tuple is in use. Not a count of successful lookups |
insert | nf_conntrack_hash_check_insert() | Entries inserted through ctnetlink or other non-packet paths. Packet-path confirmations do not touch it; in every lab.sh run insert stayed at 0 through three scenarios of 20000 flows and became 1 after one conntrack -R line |
invalid | nf_conntrack_in() | Packets conntrack could not classify or a tracker rejected; for TCP, often window tracking |
insert_failed | __nf_conntrack_confirm(), nf_ct_resolve_clash() | A confirm that lost: unresolvable clash, dying entry or chain too long. Always read with drop and chaintoolong |
drop | nf_conntrack_in(), nf_confirm() (seqadj failure)9, nf_ct_resolve_clash(), nf_confirm_cthelper() | Packets dropped by conntrack itself, including the table-full path |
early_drop | early_drop() | Entries evicted to make room. Non-zero means the namespace reached its limit, even if nothing was dropped |
search_restart | ____nf_conntrack_find(), nf_conntrack_tuple_taken() | Lockless lookups, including NAT's check for a free tuple, that restarted after landing on a recycled entry |
clash_resolve | __nf_ct_resolve_clash(), nf_ct_resolve_clash_harder() | Races that were absorbed without a drop |
chaintoolong | __nf_conntrack_confirm(), nf_conntrack_hash_check_insert() | Insertions refused because the walk of a target bucket exceeded the random limit drawn from 50 to 79 (a chain of more than max_chainlen + 1 nodes). The /proc header labels this column chainlength |
The rule I use: early_drop going up is the warning, drop going up is the incident, and chaintoolong going up means the bucket count is wrong, not the limit. A ratio of nf_conntrack_count to nf_conntrack_max alone says nothing about the last two, and on the host it says nothing at all about other namespaces. Also remember that conntrack -C and nf_conntrack_count include entries that conntrack -L hides: the lab's NAT run counted about 10000 more entries than it listed, every one of them a clash entry with a one second lease.
Lab: three failures in a rootless namespace
Every number in this article that is not from a cited source came from this lab. Host: Fedora Linux 43 Workstation, kernel 7.2.13-100.fc43.x86_64, 20 CPUs, 62 GiB RAM, rootless Podman with the registry.fedoraproject.org/fedora:43 image. In the container: conntrack-tools 1.4.9, libnetfilter_conntrack 1.1.1, nftables 1.1.3, iproute 6.14.0, gcc 15.3.1, Python 3.14.8 and glibc 2.42. The container runs with --network none and the capabilities NET_ADMIN and NET_RAW, which it holds only inside its own user and network namespaces, so nothing touches the host's rules. It does share the host's hash table, which is the point.
mkdir ctlab && cd ctlab
cat > Containerfile <<'EOF'
FROM registry.fedoraproject.org/fedora:43
RUN dnf -y install conntrack-tools nftables iproute gcc python3 && dnf clean all
EOF
podman build -t ctlab:f43 .The race needs two packets of a new flow in flight on two CPUs at once. Production traffic produces that occasionally; the program below produces it on purpose. Two threads pinned to CPUs 2 and 3 spin on a shared generation counter. For each iteration the main thread prepares a new flow, bumps the counter, and both threads send the first packet of that flow at the same instant. In UDP mode each flow is a fresh socket bound to a distinct source port, so every iteration is a new tuple. In TCP mode a raw socket sends two identical hand-built SYN segments, because no ordinary TCP socket ever sends its SYN twice in parallel.
// race.c: two threads on two CPUs send the first packet of the same flow at
// the same moment, so both packets miss the conntrack table and race to
// confirm. Usage: race udp|tcp ITERATIONS DST_IP
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static atomic_int gen, done;
static int fd, tcp_mode;
static struct sockaddr_in dst;
static unsigned char pkt[40];
static unsigned short csum(const unsigned char *p, int len, unsigned int sum) {
for (; len > 1; len -= 2, p += 2) { uint16_t v; memcpy(&v, p, 2); sum += v; }
if (len) sum += *p;
while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
return (unsigned short)~sum;
}
static void build_syn(unsigned short sport) {
struct iphdr *ip = (struct iphdr *)pkt;
struct tcphdr *th = (struct tcphdr *)(pkt + 20);
memset(pkt, 0, sizeof pkt);
ip->version = 4; ip->ihl = 5; ip->ttl = 64; ip->protocol = IPPROTO_TCP;
ip->tot_len = htons(40);
ip->saddr = inet_addr("10.0.0.1"); ip->daddr = dst.sin_addr.s_addr;
th->source = htons(sport); th->dest = htons(80);
th->seq = htonl(1); th->doff = 5; th->syn = 1; th->window = htons(64240);
// TCP pseudo-header: source, destination, zero, protocol, TCP length.
// Copied into a uint16_t array so the sum reads it without aliasing a struct.
unsigned char ph[12];
uint16_t w[6], len = htons(20);
memcpy(ph, &ip->saddr, 4); memcpy(ph + 4, &ip->daddr, 4);
ph[8] = 0; ph[9] = IPPROTO_TCP; memcpy(ph + 10, &len, 2);
memcpy(w, ph, sizeof w);
unsigned int sum = 0;
for (unsigned i = 0; i < 6; i++) sum += w[i];
th->check = csum(pkt + 20, 20, sum);
}
static void *worker(void *arg) {
cpu_set_t set; CPU_ZERO(&set); CPU_SET((int)(long)arg, &set);
pthread_setaffinity_np(pthread_self(), sizeof set, &set);
int seen = 0;
for (;;) {
int g;
while ((g = atomic_load(&gen)) == seen) ;
if (g < 0) return NULL;
seen = g;
if (tcp_mode) sendto(fd, pkt, sizeof pkt, 0, (void *)&dst, sizeof dst);
else send(fd, "q", 1, 0);
atomic_fetch_add(&done, 1);
}
}
int main(int argc, char **argv) {
if (argc != 4) { fprintf(stderr, "usage: race udp|tcp N DST\n"); return 2; }
tcp_mode = strcmp(argv[1], "tcp") == 0;
int n = atoi(argv[2]);
dst.sin_family = AF_INET; dst.sin_port = htons(53);
inet_pton(AF_INET, argv[3], &dst.sin_addr);
if (tcp_mode) {
fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (fd < 0) { perror("raw socket"); return 1; }
}
pthread_t a, b;
pthread_create(&a, NULL, worker, (void *)2L);
pthread_create(&b, NULL, worker, (void *)3L);
for (int i = 1; i <= n; i++) {
if (tcp_mode) {
build_syn((unsigned short)(10000 + i % 50000));
} else {
struct sockaddr_in src = { .sin_family = AF_INET,
.sin_port = htons(10000 + i % 50000) };
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0 || bind(fd, (void *)&src, sizeof src) < 0 ||
connect(fd, (void *)&dst, sizeof dst) < 0) { perror("udp"); return 1; }
}
atomic_store(&done, 0);
atomic_store(&gen, i);
while (atomic_load(&done) < 2) ;
if (!tcp_mode) close(fd);
}
atomic_store(&gen, -1);
pthread_join(a, NULL); pthread_join(b, NULL);
return 0;
}The namespace gets a dummy interface with a client address and two backend addresses, and a route for a fake Service range. The nftables rule is the same construct kube-proxy's nftables mode writes: a DNAT whose target is chosen by numgen random mod 2 from a map22. The driver script runs three scenarios of 20000 flows each: UDP straight to a backend, UDP to the fake ClusterIP through the random DNAT, and raw TCP SYNs straight to a backend.
cat > lab.nft <<'EOF'
table ip lab {
chain out {
type nat hook output priority dstnat; policy accept;
ip daddr 10.96.0.10 udp dport 53 dnat to numgen random mod 2 map { 0 : 10.0.0.2, 1 : 10.0.0.3 }
}
}
EOF
cat > lab.sh <<'EOF'
set -e
gcc -O2 -pthread -o /tmp/race /lab/race.c
ip link set lo up
ip link add dummy0 type dummy && ip link set dummy0 up
ip addr add 10.0.0.1/24 dev dummy0
ip addr add 10.0.0.2/32 dev dummy0
ip addr add 10.0.0.3/32 dev dummy0
ip route add 10.96.0.0/12 dev dummy0
nft -f /lab/lab.nft
stats() { conntrack -S | awk '{for(i=2;i<=NF;i++){split($i,kv,"=");s[kv[1]]+=kv[2]}} END{printf "insert=%d insert_failed=%d drop=%d clash_resolve=%d",s["insert"],s["insert_failed"],s["drop"],s["clash_resolve"]}'; }
run() {
conntrack -F 2>/dev/null || true
before=$(stats)
/tmp/race "$1" 20000 "$2"
echo "$1 -> $2: before[$before] after[$(stats)] count=$(conntrack -C) listed=$(conntrack -L 2>/dev/null | wc -l)"
}
run udp 10.0.0.2
run udp 10.96.0.10
run tcp 10.0.0.2
echo "-I -p udp -s 10.0.0.1 -d 10.0.0.9 --sport 4000 --dport 53 --timeout 60" > /tmp/one.txt
conntrack -R /tmp/one.txt
echo "after one conntrack -R line: $(stats)"
EOF
for k in 1 2 3; do
podman run --rm --cap-add NET_ADMIN,NET_RAW --network none \
-v "$PWD":/lab:Z localhost/ctlab:f43 bash /lab/lab.sh
done| Scenario | clash_resolve | insert_failed and drop | count minus listed |
|---|---|---|---|
| UDP, no NAT | 19916 / 19929 / 19921 | 0 / 0 / 0 | 0 / 0 / 0 |
| UDP, random DNAT over 2 backends | 19947 / 19926 / 19922 | 0 / 0 / 0 | 9936 / 10053 / 10035 |
| TCP SYN, no NAT | 0 / 0 / 0 | 19618 / 19586 / 19552 | 0 / 0 / 0 |
Three things are worth reading out of that table. The harness is effective: in about 99.6 percent of UDP iterations both packets missed the table and raced to confirm, so this is a worst case by construction, not an estimate of how often production traffic races. The DNAT run splits as the code predicts: roughly half of the clashes drew the same backend and were merged, and the other half drew different backends and became hidden reply-only entries, visible as the gap between conntrack -C and conntrack -L in the moment before their one second timeout. And the TCP run shows the path that DNS packets took before v5.6: no allow_clash, so the loser is dropped and counted in both insert_failed and drop. The few hundred TCP iterations that did not fail are most likely the ones where the two sends did not overlap.
The table-full experiment needs no C. A Python loop sends one datagram to each of N distinct destinations routed into the dummy interface, so every packet is a new unreplied flow, and counts sendto() failures by errno. The second phase uses conntrack -R to load 262144 entries that are already assured, then tries again. norule.sh sends 100 datagrams before and 100 after loading a single conntrack rule, and the host shell reads its own nf_conntrack_count before the fill and again while the container holds a full table.
cat > spray.py <<'EOF'
# spray.py N: one UDP datagram to each of N distinct destinations, so every
# packet creates a new conntrack entry. Prints how many sendto() calls failed.
import errno, socket, sys
n = int(sys.argv[1])
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
fails = {}
for i in range(n):
dst = "10.%d.%d.%d" % (97 + (i >> 16), (i >> 8) & 255, i & 255)
try:
s.sendto(b"q", (dst, 53))
except OSError as e:
fails[errno.errorcode[e.errno]] = fails.get(errno.errorcode[e.errno], 0) + 1
print("sent=%d failed=%s" % (n, fails or "{}"))
EOF
cat > fill.sh <<'EOF'
set -e
ip link set lo up
ip link add dummy0 type dummy && ip link set dummy0 up
ip addr add 10.0.0.1/24 dev dummy0
ip route add 10.96.0.0/11 dev dummy0
nft add table inet lab
nft add chain inet lab out '{ type filter hook output priority 0; }'
nft add rule inet lab out ct state new counter
stats() { conntrack -S | awk '{for(i=2;i<=NF;i++){split($i,kv,"=");s[kv[1]]+=kv[2]}} END{printf "insert_failed=%d drop=%d early_drop=%d",s["insert_failed"],s["drop"],s["early_drop"]}'; }
echo "max=$(cat /proc/sys/net/netfilter/nf_conntrack_max) buckets=$(cat /proc/sys/net/netfilter/nf_conntrack_buckets)"
echo "A0 $(stats) count=$(conntrack -C)"
python3 /lab/spray.py 300000
echo "A1 $(stats) count=$(conntrack -C)"
conntrack -F 2>/dev/null
for d in 1 2 3 4 5; do for p in $(seq 1024 65535); do
echo "-I -p udp -s 10.0.0.1 -d 10.96.0.$d --sport $p --dport 53 --timeout 600 --status ASSURED,SEEN_REPLY"
done; done | head -n 262144 > /tmp/assured.txt
conntrack -R /tmp/assured.txt
echo "B0 $(stats) count=$(conntrack -C)"
python3 /lab/spray.py 1000
echo "B1 $(stats) count=$(conntrack -C)"
touch /lab/full && sleep 10
EOF
cat > norule.sh <<'EOF'
set -e
ip link set lo up
ip link add dummy0 type dummy && ip link set dummy0 up
ip addr add 10.0.0.1/24 dev dummy0
ip route add 10.96.0.0/11 dev dummy0
python3 /lab/spray.py 100
echo "no rule: count=$(conntrack -C)"
nft add table inet lab
nft add chain inet lab out '{ type filter hook output priority 0; }'
nft add rule inet lab out ct state new counter
python3 /lab/spray.py 100
echo "one rule: count=$(conntrack -C)"
EOF
podman run --rm --cap-add NET_ADMIN,NET_RAW --network none \
-v "$PWD":/lab:Z localhost/ctlab:f43 bash /lab/norule.sh
rm -f full
echo "host before: $(cat /proc/sys/net/netfilter/nf_conntrack_count)"
podman run --rm --cap-add NET_ADMIN,NET_RAW --network none \
-v "$PWD":/lab:Z localhost/ctlab:f43 bash /lab/fill.sh &
until [ -e full ]; do sleep 1; done
echo "host while full: $(cat /proc/sys/net/netfilter/nf_conntrack_count)"
waithost before: 163
max=262144 buckets=262144
A0 insert_failed=0 drop=0 early_drop=0 count=0
sent=300000 failed={}
A1 insert_failed=0 drop=0 early_drop=37856 count=262144
B0 insert_failed=0 drop=0 early_drop=37856 count=262144
sent=1000 failed={'EPERM': 1000}
B1 insert_failed=0 drop=1000 early_drop=37856 count=262144
host while full: 147The arithmetic closes: 300000 flows minus 37856 evictions is 262144 entries. Note what the container could not do. Its namespace reads nf_conntrack_max as 262144 and cannot change it, because the sysctl is read-only outside the initial namespace8, yet it filled a quarter of a million entries of its own into the host's buckets while the host's own nf_conntrack_count, read from the host shell, stayed in the hundreds: 163 before the run and 147 while the container held 262144 entries. Run the same experiment on a Kubernetes node and the node's conntrack metrics will look healthy throughout.
Two kernel differences matter if you repeat this on another version. On kernels before v7.0, ICMP does not set allow_clash, so an ICMP variant of the race behaves like the TCP run; I used raw TCP for that path because on v7.2 ICMP clashes are resolved19. On kernels before v6.19, nf_conntrack_max = 0 disables the limit entirely; since v6.19 the sysctl rejects 0 and the limit check is unconditional28.
What I would change on a node
Size buckets and limit together, at boot, from the initial namespace. Setting nf_conntrack_max alone moves the eviction point and leaves the chains to grow; setting hashsize alone switches the kernel to its factor of 8 on the next module load. Choose both, keep the designed chain near two, and apply them before workloads start, because a resize blocks every conntrack writer on the host until the rehash finishes7. If kube-proxy runs with its defaults, compute what it will write on your largest node shape before you decide your own values, since it only ever raises the limit and only raises the bucket count when it falls below a quarter of that limit13.
Shorten the timers before raising the limit. The established TCP timeout is the single largest lever, the UDP timeouts matter on DNS-heavy nodes, and both are exposed through kube-proxy's conntrack settings, which leave them untouched when set to zero15. A table that is full of five-day-old idle connections is not too small.
Alert on rates of early_drop, drop, insert_failed and chaintoolong, collected per namespace for any namespace that loads NAT or state rules, rather than on the ratio of count to max in the host namespace. The ratio is the metric everybody exports, and the lab shows it can stay near zero while another namespace holds a quarter of a million entries.
Check the kernel before changing the resolver. On v5.6 and later, UDP clashes under random DNAT are absorbed, and a clash_resolve counter that climbs while insert_failed stays flat is the kernel doing its job. On older kernels, single-request-reopen or NodeLocal DNSCache are the fixes, and the second also takes DNS off the table for good25.
Remember that kube-proxy cleans up after itself only for UDP. Its CleanStaleEntries() deletes UDP entries for Service addresses whose DNAT target is no longer a serving endpoint, because a one-way UDP flow would otherwise refresh its entry forever and keep sending to a deleted pod29. TCP entries to dead endpoints stay until their timer or an RST removes them, which is one more reason the established timeout deserves attention.
Whatever values you settle on, keep them in the same Git repository that Argo CD reconciles for the cluster, next to the kube-proxy configuration that will try to overwrite them. Conntrack settings are node state, and node state that lives only in someone's shell history comes back wrong on the next node pool. The table will still fail eventually; the goal is that when it does, it fails loudly, in a counter someone is watching, in the namespace where the problem actually is.
المراجع
- include/net/netfilter/nf_conntrack_tuple.h (Linux v7.2) Linux kernel source
- netfilter: conntrack: don't fold port numbers into addresses before hashing (commit eaf9e7192ec9, in v6.5) Linux kernel git history
- Documentation/networking/nf_conntrack-sysctl.rst (Linux v7.2) Linux kernel documentation
- include/uapi/linux/netfilter/nf_conntrack_common.h (Linux v7.2) Linux kernel source
- net/netfilter/nf_conntrack_proto_udp.c (Linux v7.2) Linux kernel source
- net/netfilter/nf_conntrack_proto_tcp.c (Linux v7.2) Linux kernel source
- net/netfilter/nf_conntrack_core.c (Linux v7.2) Linux kernel source
- net/netfilter/nf_conntrack_standalone.c (Linux v7.2) Linux kernel source
- net/netfilter/nf_conntrack_proto.c (Linux v7.2) Linux kernel source
- netfilter: refuse insertion if chain has grown too large (commit d7e7747ac5c2, in v5.15) Linux kernel git history
- netfilter: conntrack: make max chain length random (commit c9c3b6811f74, in v5.15) Linux kernel git history
- netfilter: conntrack: adopt safer max chain length (commit c77737b736ce, in v6.3) Linux kernel git history
- pkg/proxy/conntrack/sysctls.go (Kubernetes v1.37.2) Kubernetes source
- pkg/proxy/apis/config/v1alpha1/defaults.go (Kubernetes v1.37.2) Kubernetes source
- kube-proxy command line reference Kubernetes documentation
- include/uapi/linux/netfilter_ipv4.h (Linux v7.2) Linux kernel source
- netfilter: conntrack: allow insertion of clashing entries (commit 6a757c07e51f, in v5.6) Linux kernel git history
- netfilter: nf_conntrack: resolve clash for matching conntracks (commit ed07d9a021df, in v4.19) Linux kernel git history
- netfilter: nf_conntrack: enable icmp clash support (commit f7becf0dad8f, in v7.0) Linux kernel git history
- resolv/res_send.c (glibc 2.42) GNU C Library source, GitHub mirror
- pkg/proxy/iptables/proxier.go (Kubernetes v1.37.2) Kubernetes source
- pkg/proxy/nftables/proxier.go (Kubernetes v1.37.2) Kubernetes source
- Debugging DNS Resolution Kubernetes documentation
- resolv.conf(5) Linux man-pages project
- Using NodeLocal DNSCache in Kubernetes Clusters Kubernetes documentation
- conntrack(8), conntrack-tools 1.4.9 Debian manpages
- net/netfilter/nf_conntrack_netlink.c (Linux v7.2) Linux kernel source
- netfilter: conntrack: disable 0 value for conntrack_max setting (commit 2b749f257645, in v6.19) Linux kernel git history
- pkg/proxy/conntrack/cleanup.go (Kubernetes v1.37.2) Kubernetes source