kube-proxy in iptables, IPVS and nftables modes
kube-proxy v1.37 in three modes, traced to the kernel: linear chains, IPVS hash tables, nftables verdict maps, and why update cost decides at scale.
Every kube-proxy mode does the same three things to a packet addressed to a Service: it recognises the virtual IP and port, picks an endpoint, and rewrites the destination. Measured per packet, all three modes are fast enough for most clusters, and the per-packet difference only becomes visible with tens of thousands of Services 1. The difference that hurts earlier is on the other side of the API: what it costs the node to change the rules when a Deployment rolls, an endpoint goes unready or a namespace is deleted. That cost is set by the kernel interface each mode writes to, and this article follows it down to the functions that do the work.
Versions matter here because the answer moved between releases. Everything below is pinned to Kubernetes v1.37.2, the current patch release on the date of writing, and to Linux v7.2. On those versions iptables is still the default mode, nftables has been GA since 1.33, and ipvs is deprecated with a published removal schedule 1 2 3.
What a Service virtual IP is on the wire
A ClusterIP is allocated by the API server from the service-cluster-ip-range and is not answered by any single host; kube-proxy makes it exist by programming packet processing on every node 1. No interface owns the address in the iptables and nftables modes. A packet to 10.96.0.10:53 leaves the client pod with that destination, reaches the node's netfilter hooks, and is destination-NATed to an endpoint such as 10.244.1.7:53 before routing decides where it goes.
Where that happens is fixed by netfilter, and the iptables and nftables modes use the same hooks. kube-proxy's design note for the nftables backend states the rule for that backend: DNAT for traffic arriving from pods or from off the node happens in prerouting, because the chosen endpoint decides whether the packet then takes the input path or the forward path; DNAT for traffic from host-network processes happens in output; masquerading happens in postrouting, because SNAT to the outgoing interface's address needs the final routing decision 4. The iptables proxier places its rules the same way: its jump table sends the nat table's built-in PREROUTING and OUTPUT chains to KUBE-SERVICES and POSTROUTING to KUBE-POSTROUTING 5. IPVS mode is the exception, covered in its own section below: IPVS translates on the LOCAL_IN and LOCAL_OUT hooks, not in prerouting, which is why that mode needs the kube-ipvs0 interface. Return traffic is un-NATed by conntrack, which stored both tuples of the connection when the first packet was translated.
That last point is why per-packet cost is really per-connection cost. In nf_nat_inet_fn() the registered NAT hook entries, which is where kube-proxy's chains run, are only consulted for a packet in state IP_CT_NEW, IP_CT_RELATED or IP_CT_RELATED_REPLY whose conntrack entry has no NAT binding yet for that manipulation type: HOOK2MANIP maps postrouting and input to source NAT, and prerouting and output to destination NAT, and nf_nat_initialized(ct, maniptype) checks the binding for that type. Established packets skip straight to applying the stored mapping 6. The published kube-proxy latency comparisons therefore measure the first packet of a new connection, not every packet 7.
iptables mode: a linear program replaced as a whole
In iptables mode kube-proxy builds a tree of user-defined chains in the nat table. KUBE-SERVICES holds one rule per Service IP and port. Each rule jumps to a per-service chain KUBE-SVC-<hash>, which jumps to one KUBE-SEP-<hash> chain per endpoint, which performs the DNAT. Variants exist for Local traffic policy (KUBE-SVL-), external destinations (KUBE-EXT-) and loadBalancerSourceRanges (KUBE-FW-) 5.
The chain names are not random. portProtoHash() takes SHA-256 of the service port name concatenated with the protocol, encodes it in base32 and keeps the first 16 characters, because iptables chain names must stay under 29 characters; endpoint chains hash the endpoint address in as well 5. The name is therefore stable across restarts and across nodes, which is what makes partial updates possible later.
-A KUBE-SERVICES -m comment --comment "ns/s1:p80 cluster IP" -m tcp -p tcp -d 10.96.0.2 --dport 80 -j KUBE-SVC-RSV66BG4AU7ASL5X
-A KUBE-SVC-RSV66BG4AU7ASL5X -m statistic --mode random --probability 0.5000000000 -j KUBE-SEP-IXMXCMLNLUD6UQAQ
-A KUBE-SVC-RSV66BG4AU7ASL5X -j KUBE-SEP-TG74IBJ2EQJ7LGFX
-A KUBE-SEP-IXMXCMLNLUD6UQAQ -s 10.244.0.3/32 -j KUBE-MARK-MASQ
-A KUBE-SEP-IXMXCMLNLUD6UQAQ -p tcp -m tcp -j DNAT --to-destination 10.244.0.3:8080Load balancing is a cascade of independent coin flips. writeServiceToEndpointRules() gives the rule for endpoint i of n the match -m statistic --mode random --probability 1/(n-i) and leaves the last rule unconditional, so each endpoint ends up with probability 1/n 5. In the kernel, statistic_mt() in net/netfilter/xt_statistic.c evaluates that match as (get_random_u32() & 0x7FFFFFFF) < info->u.random.probability, one random draw per rule visited 8. The -s <endpoint>/32 -j KUBE-MARK-MASQ rule in each endpoint chain handles hairpin traffic, a pod reaching itself through its own Service, which must be masqueraded so the reply returns through the node.
Packet evaluation is ipt_do_table() in net/ipv4/netfilter/ip_tables.c: starting at the hook's entry point it walks a contiguous blob of struct ipt_entry records, runs ip_packet_match() and every extension match of each entry, and advances with ipt_next_entry() until a target returns a verdict 9. KUBE-SERVICES is a list, so a new connection to the Service whose rule sits last pays a comparison against every Service ahead of it. The February 2025 Kubernetes blog post on the nftables mode, written while the mode was still beta and ahead of its GA in 1.33, states this as O(n) in the number of Services, with best, average and worst case set mostly by the position of the Service IP in KUBE-SERVICES 7.
How iptables rules reach the kernel
The legacy iptables interface, used by the iptables-legacy binaries, has no notion of adding one rule. iptables-restore on that backend hands the kernel a complete table through the IPT_SO_SET_REPLACE socket option. do_replace() copies the whole blob from user space, translate_table() validates every entry, resolves jumps and checks for loops, and __do_replace() calls xt_replace_table() 9. In v7.2 the swap itself is do_replace_table() in net/netfilter/x_tables.c: it publishes the new xt_table_info with table->private = newinfo, then spins on every possible CPU until that CPU's xt_recseq sequence counter is even, meaning no packet is still walking the old blob, before the old one is freed 10. On this legacy path the work is proportional to the size of the table, not to the size of the change.
Most distributions now ship the nf_tables flavour of the iptables binaries, which keep the iptables command-line interface but use the nftables kernel API; KEP-3866 notes that by 2022 this had left the legacy kernel API mostly dead 11. The lab host for this article ran iptables v1.8.11 (nf_tables), which is the case that matters today, and on it do_replace_table() is never reached: an iptables-nft-restore is committed by the same nf_tables_commit() as an nft -f, described in the nftables section below. KEP-3866 explains why the switch does not rescue kube-proxy: the iptables-nft binaries add no new syntax, so nftables features such as maps are unavailable, and the compatibility constraints of the iptables binaries' user-facing API keep them from many of the performance improvements of nftables 11. The update cost does not disappear with the legacy API. It moves into the size of the transaction, as the next section and Lab 2 show.
Partial sync, and why it is still O(n)
Until Kubernetes 1.26 every sync rewrote every rule. KEP-3453 changed syncProxyRules() to send iptables-restore only the chains of Services whose Service or EndpointSlice changed since the last sync; it went alpha in 1.26, beta in 1.27, and the Kubernetes documentation describes the minimal update as the behaviour since 1.28 12 1. The mechanism in v1.37.2 is a buffer swap: for an unchanged Service the per-service and per-endpoint chain lines are written into skippedNatChains and skippedNatRules, discard buffers that only exist so the metrics still count them 5.
The swap happens after the Service's KUBE-SERVICES rule has been written. The top-level chains are declared and filled on every sync, and the restore runs with --noflush, under which iptables-restore flushes any user-defined chain that the input declares 5 13. So every partial sync still carries one KUBE-SERVICES rule per Service. The nftables announcement puts it plainly: the update stays O(n) in the number of Services, with a smaller constant than before 7. The lab below measures that constant.
Three more details of the sync loop matter in large clusters. A full resync is forced every FullSyncPeriod, one hour, except in large-cluster mode 14 5. Large-cluster mode switches on when the node sees more than largeClusterEndpointsThreshold, 1000 endpoints; it drops the per-rule comments, which the source comment says can shrink the ruleset by 40 percent or more, and it runs the stale-chain cleanup, which needs an iptables-save, at most once per syncPeriod 5. Syncs run through a BoundedFrequencyRunner built with minSyncPeriod (default 1s) as the minimum interval between syncs, syncPeriod (default 30s) as the retry interval after a failed sync, and FullSyncPeriod, one hour, as the maximum interval 5 15 1. The source comment calls that hour arbitrary, because syncPeriod also goes to ipt.Monitor, which creates a canary chain in the mangle, nat and filter tables, checks the mangle canary every syncPeriod, and once it disappears waits up to five seconds for the other two to go as well before it triggers a resync 5 16. The documentation now advises removing large minSyncPeriod overrides that were set before partial sync existed 1.
IPVS mode: a kernel load balancer bolted to iptables
IPVS was added to kube-proxy to escape the linear KUBE-SERVICES walk. It replaces that walk with the kernel's Layer 4 load balancer, which keeps virtual services and connections in hash tables 1. In v7.2 the service table is a resizable struct ip_vs_rht hashed on protocol, address and port by ip_vs_svc_hashval(), and the connection table is another ip_vs_rht. When the connection table is first allocated, ip_vs_rht_desired_size() returns the minimum size, 1 << IP_VS_CONN_TAB_MIN_BITS, 256 buckets; the table is then resized with the connection count, scaled by the conn_lfactor sysctl, and the conn_tab_bits module parameter, default CONFIG_IP_VS_TAB_BITS = 12, caps its maximum size 17 18 19 20 21. Updates are per object: kube-proxy adds or removes one virtual or real server through the IPVS generic netlink interface, so an endpoint change does not rewrite anything else.
The cost shows up in how packets reach IPVS. ip_vs_core.c registers ip_vs_in_hook() on NF_INET_LOCAL_IN at priority NF_IP_PRI_NAT_SRC - 1 and on NF_INET_LOCAL_OUT at NF_IP_PRI_NAT_DST + 2; there is no IPVS hook in PREROUTING that would see forwarded traffic 19. A packet is only offered to IPVS if routing has already decided it is for this host. That is why kube-proxy creates the dummy interface kube-ipvs0 and binds every ClusterIP, external IP and load-balancer IP to it 22. The nftables announcement names exactly this, that kube-ipvs0 must carry every Service address, as one of the awkward fits between IPVS and Service semantics 7.
IPVS also cannot express everything a Service needs, so the mode is a hybrid. Masquerading, NodePorts, loadBalancerSourceRanges and traffic-policy handling are iptables rules that match against ipsets such as KUBE-CLUSTER-IP, a hash:ip,port set commented 'Kubernetes service cluster ip + port for masquerade purpose' 22 23. kube-proxy also sets net/ipv4/vs/conntrack=1 so IPVS keeps netfilter conntrack entries for the masquerade path, plus expire_nodest_conn and expire_quiescent_template, and sets conn_reuse_mode to 0 only on kernels in the affected range 22. KEP-3866 considered fixing up the ipvs mode instead of writing a new backend and rejected it on deprecation grounds, not performance grounds: the mode makes extensive use of the iptables API in addition to the IPVS API, so while it solves the performance problems of the iptables mode, it does not address the iptables deprecation, and it would have to be rewritten as IPVS plus nftables 11. The KEP adds that IPVS, like iptables, is no longer an actively developed technology 11.
The schedulers are IPVS's distinctive feature: rr by default, plus wrr, lc, wlc, lblc, lblcr, sh, dh, sed, nq and mh 1 22. In practice they promise more than they deliver, and the nftables announcement explains why: kube-proxy runs independently on every node, so each node's least-connection state knows nothing about connections opened from other nodes 7. A cluster-wide balancing decision cannot be made from one node's view.
The project has made its decision. The documentation lists the mode as deprecated since 1.35, and KEP-5495 gives the reason, a lack of SIG Network maintainers for the IPVS code; v1.37.2 carries the KubeProxyIPVS feature gate, marked deprecated and still enabled by default; the documentation states that the mode will be disabled by default from 1.40 and removed in 1.43 3 2 1. My recommendation is direct: do not build a new cluster on IPVS mode, and treat an existing one as migration work with a deadline.
nftables mode: one map lookup and a transaction
The nftables backend owns one table per address family, table ip kube-proxy and table ip6 kube-proxy, and nothing outside it. Other components are told never to modify that table and to order their own chains against it by base-chain priority: kube-proxy DNATs on type nat chains at priority dstnat on the prerouting and output hooks and masquerades at srcnat on postrouting 4. This ownership model is the first structural change. iptables has a single shared nat table with built-in chains and a global lock; nftables has no default tables, and the announcement cites private tables as removing the lock contention between components 11 7.
Dispatch is a single rule in the services chain: ip daddr . meta l4proto . th dport vmap @service-ips 24. It builds a concatenated key from destination address, layer 4 protocol and destination port, and looks that key up in the verdict map service-ips, declared with type ipv4_addr . inet_proto . inet_service : verdict. Each element maps one Service address and port to goto service-<hash>-<namespace>/<name>/<protocol>/<port> 24 7. NodePorts use a second map, service-nodeports, keyed on protocol and port only.
Which data structure holds the map is chosen by the kernel, not by kube-proxy. nft_select_set_ops() in net/netfilter/nf_tables_api.c iterates the registered set types, asks each for an estimate of lookup and memory cost through ops->estimate, and under the performance policy keeps the type with the lowest lookup class 25. The resizable hash type nft_set_rhash_type supports maps and estimates its lookup as NFT_SET_CLASS_O_1 26. That is the kernel-level reason the KEP describes dispatch as roughly O(1) instead of O(n) 11.
chain services {
ip daddr . meta l4proto . th dport vmap @service-ips
fib daddr type local ip daddr != 127.0.0.0/8 meta l4proto . th dport vmap @service-nodeports
}
map service-ips {
type ipv4_addr . inet_proto . inet_service : verdict
elements = { 10.96.0.2 . tcp . 80 : goto service-UYFJ3IM6-ns/s1/tcp/p80 }
}
chain service-UYFJ3IM6-ns/s1/tcp/p80 {
meta l4proto tcp dnat ip addr . port to numgen random mod 2 map { 0 : 10.244.0.3 . 8080, 1 : 10.244.0.4 . 8080 }
}The second line of services is only installed when --nodeport-addresses matches all addresses; with the nftables default of primary the rule matches ip daddr @nodeport-ips instead 24 1. The per-service chain shows the second structural change. In v1.37.2, a Service without session affinity has no per-endpoint chains at all: writeServiceToEndpointDNATs() writes one rule that DNATs to the result of looking up numgen random mod N in an anonymous map of index to address and port, and a single-endpoint Service gets a plain dnat to because, as the source comment puts it, inserting maps is O(n) or worse 24. In the kernel, nft_ng_random_gen() returns reciprocal_scale(get_random_u32(), priv->modulus) + priv->offset 27, one draw per new connection where the iptables cascade drew once per rule visited.
Session affinity is where per-endpoint chains come back. With ClientIP affinity, writeServiceToEndpointJumps() first tests the source address against one dynamic set per endpoint, affinity-<hash>, created with the timeout flag and a timeout of sessionAffinityConfig.clientIP.timeoutSeconds; if none matches, a numgen random mod N vmap picks an endpoint chain, which records the client with update @affinity-<hash> { ip saddr } and DNATs 24. Hairpin traffic no longer needs a rule per endpoint either: local endpoints are added to a hairpin-connections set keyed on source, destination, protocol and port, and one rule in the masquerading chain masquerades ct status dnat packets that match it 24.
How nftables updates reach the kernel
kube-proxy writes nftables through sigs.k8s.io/knftables v0.0.22. A sync builds a knftables.Transaction and Run() pipes its text to nft -f -; reads exec nft --json list .... When the UseNetlink option is set, only ListAll() and List() go to netlink instead; ListRules(), ListElements() and ListCounters() still exec nft --json, and the option's own comment in newInternal() reads TODO: Only some commands are implemented. 28. In v1.37.2 that option is driven by the NFTablesNetlink feature gate, beta and enabled by default since 1.37 29 2. It does not take the binary out of the sync path: on every full sync, setupNFTables() calls readOrReset() on seven element stores (eight with localhost NodePorts enabled), and each one calls ListElements(), which execs nft --json list for its map or set 24. So some reads go through netlink by default, the per-map element reads of a full sync still go through nft, and every write goes through it.
What goes into the transaction is the minimum. nftElementStorage mirrors the contents of each map and set in memory: readOrReset() loads them during a full sync, ensureElem() emits an add element only when a key is missing or its value changed, and cleanupLeftoverKeys() emits a delete element for every key the sync did not touch 24. For chains, ensureChain() emits add chain plus flush chain only when skipServiceUpdate is false, that is when the Service or its endpoints changed 24. A sync for one changed Service therefore contains that Service's chain and the elements whose values differ, and nothing about the other Services. This is the property the iptables backend cannot have, because KUBE-SERVICES must be rewritten whole.
One wart is visible in the source. Stale service chains are flushed in the sync that orphans them and deleted in a later sync at least one second afterwards, because on kernels before 6.2 deleting a map element that points to a chain does not immediately release the chain's reference 24. If you list the table right after a scale-down, empty chains are expected.
On the kernel side the transaction is applied by nf_tables_commit(). Objects carry a two-bit generation mask; new objects are created inactive in the current generation and active in the next, and the commit flips gencursor so the whole batch becomes visible at once 30. Rules are stored per chain as a blob. Step 1 of the commit, 'Allocate space for next generation rules_gen_X[]', calls nf_tables_commit_chain_prepare() only for chains that a NEWRULE or DELRULE transaction touched, so only those chains get a new blob. Step 2, 'Make rules_gen_X visible to packet path', then walks every chain of every table in the network namespace and calls nf_tables_commit_chain() on each. That call returns early for a chain with no pending change, so the walk is cheap per chain, but its length is the number of chains in the namespace, not the size of the change 25. On an iptables-nft node both backends end in this function and both pay that walk. What differs is the transaction. A one-Service nftables sync touches one service chain and a few map elements. An iptables-nft partial sync declares KUBE-SERVICES, so the chain is flushed and refilled: one rule deletion for each of its n rules, one NEWRULE for each of the n rules written back, and in step 1 a new blob for an n-rule chain. Lab 2 counts those rule events. Only the iptables-legacy backend goes through do_replace_table() instead, which swaps the entire table and waits for every CPU 10. Partial sync in the iptables proxier cannot remove the n-rule rewrite on either backend.
Behaviour that changes when you switch
The nftables mode is not a drop-in copy of iptables mode, and some defaults differ on purpose 7. These are the differences that break things during a migration, as documented for v1.37 1:
| Behaviour | iptables mode | nftables mode |
|---|---|---|
| NodePort addresses | All local IPs by default | --nodeport-addresses primary: the node's primary IPv4 and IPv6 addresses only |
| Host firewall | Adds accept rules per NodePort for aggressive firewalls | Adds none; the host firewall must allow the NodePort range |
| Conntrack workaround | Installs a workaround for a pre-6.1 kernel bug that resets long-lived TCP connections | None by default; --conntrack-tcp-be-liberal if iptables_ct_state_invalid_dropped_packets_total shows you depend on it |
NodePort on 127.0.0.1 | Works when --nodeport-addresses includes it | Alpha gate KubeProxyNFTablesLocalhostNodePorts plus primary,localhost |
| Minimum kernel | Any supported | 5.13, checked at startup |
The kernel check lives in getNFTablesInterface(). It refuses to start below 5.13 because it uses the kernel version as a proxy for the host's nft binary being 1.0.1 or newer; older nft binaries can be made unusable by tables that newer ones write. The check can be bypassed with KUBE_PROXY_NFTABLES_SKIP_KERNEL_VERSION_CHECK, which I would only do after confirming the host nft version by hand 29. Switching modes does not need a node reboot: a kube-proxy restarted in nftables mode deletes the iptables or IPVS rules of the previous mode, and the reverse holds when switching back 7.
The other migration risk is not in kube-proxy at all. The announcement warns that the pod network or NetworkPolicy implementation may not yet support kube-proxy in nftables mode; components that do not interact with or override kube-proxy's iptables rules should not care, and monitoring tools may report less data 7. Check every component that touches netfilter on the node before you switch, and look for rules that jump into KUBE-SERVICES or match the masquerade mark. kube-proxy's README is explicit that the mark is not part of its public API 4.
Lab 1: reading the rules on kind
This lab shows the real rules kube-proxy writes. It uses kind v0.33.0, whose default node image is kindest/node:v1.37.0 31; the proxier sources of v1.37.0 and v1.37.2 are identical for both backends. kubeProxyMode accepts iptables, nftables, ipvs and none 32. The commands below were inspected against the sources cited here but not executed: kind could not be installed in the environment this article was written in. Replace docker with podman if kind runs on Podman.
for mode in iptables nftables; do
cat > kind-$mode.yaml <<EOF
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
kubeProxyMode: "$mode"
EOF
kind create cluster --name kp-$mode --config kind-$mode.yaml
kubectl --context kind-kp-$mode create deployment web --image=registry.k8s.io/pause:3.10 --replicas=3
kubectl --context kind-kp-$mode expose deployment web --port=80 --target-port=8080
# kube-proxy writes Service rules only for ready endpoints, so wait for all three pods
kubectl --context kind-kp-$mode rollout status deployment/web --timeout=180s
done
# iptables mode: the KUBE-SERVICES rule, the KUBE-SVC cascade and the KUBE-SEP DNATs
docker exec kp-iptables-control-plane iptables-save -t nat | grep -E 'default/web'
# nftables mode: the dispatch map and the per-service chain
docker exec kp-nftables-control-plane nft list map ip kube-proxy service-ips
docker exec kp-nftables-control-plane nft list table ip kube-proxy | grep -A3 'chain service-.*default/web'
# Fourth endpoint: scale, wait for the new pod to be ready, then repeat the dumps above
for mode in iptables nftables; do
kubectl --context kind-kp-$mode scale deployment web --replicas=4
kubectl --context kind-kp-$mode rollout status deployment/web --timeout=180s
doneWhat to look for: in the iptables cluster, three KUBE-SEP- chains and two --probability matches, 0.3333333333 then 0.5000000000, the values computeProbability() formats with %0.10f 5. In the nftables cluster, one element for the Service's ClusterIP in service-ips and one dnat ip addr . port to numgen random mod 3 map rule. The waits matter: kube-proxy programs a Service only from ready endpoints, and in nftables mode a Service without one gets an element in no-endpoint-services instead of service-ips and no service chain at all 24. If a dump still comes back empty right after the wait, kube-proxy has not finished its next sync yet; run it again a few seconds later. Then run the scale step, which waits for the fourth pod to be ready, and repeat the dumps. In iptables mode the next sync rewrites KUBE-SERVICES in full; in nftables mode the Service's element in service-ips does not change, the service chain is flushed and refilled, and, because this single-node cluster makes every endpoint local, syncProxyRules() adds one hairpin-connections element for the new local endpoint 24.
Lab 2: measuring the cost of one update
The second lab isolates the claim this article rests on: the input of a one-Service update grows with cluster size in iptables mode and does not in nftables mode. It does not run kube-proxy. A short generator writes rulesets with the same shape as the two proxiers (a KUBE-SERVICES rule, a KUBE-SVC chain with a statistic cascade and two KUBE-SEP chains per Service for iptables; a service-ips element and a numgen DNAT chain per Service for nftables) and replays what each proxier sends when one Service's endpoints change. The fixed 0x4000 mark in the generator is arbitrary, and it omits NodePorts, the filter table and traffic-policy chains, so absolute numbers understate a real node.
Environment: Fedora 43, kernel 7.2.13-100.fc43.x86_64, iptables v1.8.11 (nf_tables), nftables v1.1.3, Python 3.14.8, Intel Core i9-13900H with 20 hardware threads. Everything ran as an unprivileged user inside a fresh user and network namespace (unshare -rn), so nothing touched the host's rules.
#!/usr/bin/env python3
# Emits kube-proxy-shaped NAT rules for N services with E endpoints each.
# kpgen.py ipt-batch N E LO HI iptables-restore input for services LO..HI-1
# kpgen.py ipt-sync N E K what a partial sync writes when service K changes
# kpgen.py nft-full N E nft transaction that builds the whole table
# kpgen.py nft-sync N E K nft transaction when service K changes
import sys, hashlib, base64
mode, n, e = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
args = [int(a) for a in sys.argv[4:]]
h = lambda s: base64.b32encode(hashlib.sha256(s.encode()).digest()).decode()[:16]
vip = lambda i: f"10.96.{i // 250}.{i % 250 + 1}"
def ep(i, j, g):
x = i * e + j + g * 7
return f"10.244.{x // 250 % 250}.{x % 250 + 1}"
out = []
if mode.startswith("ipt"):
lo, hi = args if mode == "ipt-batch" else (args[0], args[0] + 1)
gen = 0 if mode == "ipt-batch" else 1
out.append("*nat")
if mode == "ipt-sync" or lo == 0:
out += [":KUBE-SERVICES - [0:0]", ":KUBE-MARK-MASQ - [0:0]",
"-A KUBE-MARK-MASQ -j MARK --or-mark 0x4000"]
top = range(n) if mode == "ipt-sync" else range(lo, hi)
for i in top:
out.append(f'-A KUBE-SERVICES -m comment --comment "ns/s{i}:p80 cluster IP" '
f"-m tcp -p tcp -d {vip(i)} --dport 80 -j KUBE-SVC-{h(f'ns/s{i}:p80tcp')}")
for i in range(lo, hi):
svc = "KUBE-SVC-" + h(f"ns/s{i}:p80tcp")
out.insert(1, f":{svc} - [0:0]")
for j in range(e):
a = ep(i, j, gen)
sep = "KUBE-SEP-" + h(f"ns/s{i}:p80tcp{a}")
out.insert(1, f":{sep} - [0:0]")
prob = "" if j == e - 1 else f" -m statistic --mode random --probability {1 / (e - j):.10f}"
out += [f"-A {svc}{prob} -j {sep}", f"-A {sep} -s {a}/32 -j KUBE-MARK-MASQ",
f"-A {sep} -p tcp -m tcp -j DNAT --to-destination {a}:8080"]
out.append("COMMIT")
else:
full = mode == "nft-full"
if full:
out += ["add table ip kp",
"add map ip kp service-ips { type ipv4_addr . inet_proto . inet_service : verdict ; }",
"add chain ip kp nat-prerouting { type nat hook prerouting priority dstnat ; }",
"add chain ip kp services",
"add rule ip kp nat-prerouting jump services",
"add rule ip kp services ip daddr . meta l4proto . th dport vmap @service-ips"]
for i in (range(n) if full else args[:1]):
chain = f"service-{h(f'ns/s{i}/tcp/p80')[:8]}-ns/s{i}/tcp/p80"
gen = 0 if full else 1
m = ", ".join(f"{j} : {ep(i, j, gen)} . 8080" for j in range(e))
out += [f"add chain ip kp {chain}", f"flush chain ip kp {chain}",
f"add rule ip kp {chain} meta l4proto tcp dnat ip addr . port to numgen random mod {e} map {{ {m} }}"]
if full:
out.append(f"add element ip kp service-ips {{ {vip(i)} . tcp . 80 : goto {chain} }}")
print("\n".join(out))#!/bin/bash
# Run as: unshare -rn ./bench.sh N (unprivileged user and network namespace)
set -euo pipefail
N=$1; E=2; W=$(mktemp -d); trap 'rm -rf "$W"' EXIT
mean_ms() { # mean wall time of "$@ FILE" over files $W/$1.1..20
local p=$1 tot=0 s f; shift
for f in "$W/$p".{1..20}; do s=$(date +%s%N); "$@" "$f" >/dev/null; tot=$((tot + $(date +%s%N) - s)); done
echo "scale=1; $tot / 20 / 1000000" | bc
}
for ((lo = 0; lo < N; lo += 50)); do
./kpgen.py ipt-batch "$N" $E $lo $((lo + 50 < N ? lo + 50 : N)) | iptables-nft-restore --noflush
done
./kpgen.py nft-full "$N" $E | nft -f -
nft -f - <<< 'add table ip small; add map ip small m { type ipv4_addr . inet_proto . inet_service : verdict ; }'
for r in {1..20}; do
./kpgen.py ipt-sync "$N" $E $r > "$W/ipt.$r"
./kpgen.py nft-sync "$N" $E $r > "$W/nft.$r"
echo "add element ip kp service-ips { 10.97.0.$r . tcp . 80 : drop }" > "$W/el.$r"
echo "add element ip small m { 10.97.0.$r . tcp . 80 : drop }" > "$W/sm.$r"
done
echo "services=$N nat_rules=$(iptables-nft-save -t nat | grep -c '^-A')"
echo "ipt-sync bytes=$(wc -c < "$W/ipt.1") test_ms=$(mean_ms ipt iptables-nft-restore --noflush --test)"
echo "nft-sync bytes=$(wc -c < "$W/nft.1") commit_ms=$(mean_ms nft nft -f)"
echo "one element: kube table ms=$(mean_ms el nft -f) small table ms=$(mean_ms sm nft -f)"chmod +x kpgen.py bench.sh attrib.sh empty.sh events.sh
for pass in 1 2; do for n in 1000 5000 10000; do unshare -rn ./bench.sh $n; done; done# Run as: bash limit.sh (each batch size runs once, in its own fresh namespace)
for k in 60 65 66 67 68 69 70 75; do
printf 'K=%s ' $k
unshare -rn sh -c "./kpgen.py ipt-batch 1000 2 0 $k | iptables-nft-restore --noflush && echo ok" 2>&1 | tail -1
doneOne constraint of the unprivileged namespace shaped the method. With two endpoints per Service, iptables-nft-restore committed a batch of 69 Services and refused one of 70 with sendmsg() failed: Message too long, the same in three separate invocations of limit.sh above. The script therefore loads the iptables ruleset in 50-Service batches. A real partial sync carries every KUBE-SERVICES rule in one batch, so it hits the same limit: at 1,000 Services it failed with the same error. The script times it with --test instead, which per the man page parses and constructs the ruleset without committing it 13. The iptables timings are therefore a lower bound on the real restore. The nftables timings include the commit.
| Services | iptables NAT rules | iptables partial-sync input | iptables-nft-restore --test | nft transaction | nft -f commit | one element: kube table / other table |
|---|---|---|---|---|---|---|
| 1,000 | 7,001 | 132,135 bytes | 43.7 / 45.0 ms | 257 bytes | 26.4 / 53.0 ms | 15.2 / 17.5 and 36.8 / 41.7 ms |
| 5,000 | 35,001 | 664,907 bytes | 181.5 / 170.5 ms | 257 bytes | 74.9 / 60.4 ms | 61.3 / 60.5 and 49.2 / 47.5 ms |
| 10,000 | 70,001 | 1,332,747 bytes | 744.1 / 1,279.5 ms | 257 bytes | 134.3 / 139.4 ms | 104.9 / 102.6 and 102.2 / 98.4 ms |
The byte counts are deterministic and they are the cleanest result. The iptables partial sync grows by almost exactly 133 bytes per Service, which is one KUBE-SERVICES line, from 132,135 bytes at 1,000 Services to 1,332,747 at 10,000. The nftables transaction for the same change is 257 bytes at every size. The parse-and-construct time of the iptables update grew by a factor of 17 to 28 over a tenfold growth in Services, and that excludes the commit.
The nftables numbers hold a result I did not expect. The constant-size transaction did not take constant time: nft -f went from about 26 to 53 ms at 1,000 Services to about 135 ms at 10,000. The last column shows that the cost is not a function of the table being written: at 5,000 and 10,000 Services, adding one element to a separate two-object table cost about as much as adding one to the large table, and at 1,000 Services the small table cost more than twice as much (36.8 / 41.7 against 15.2 / 17.5 ms). I did not isolate the cause of that 1,000-Service inversion, so I read it only as evidence against a per-table cost, not as a measurement of the small-table case. The same one-element nft -f in a fresh, otherwise empty namespace took 6.1 to 6.2 ms over three runs of empty.sh below. The cost tracks the total nftables state in the network namespace, which here includes the 70,001 iptables-nft rules and their chains, since those live in nf_tables too.
The step 2 walk of nf_tables_commit() over every chain in the namespace is the obvious kernel-side candidate for that cost, so I tested it. perf and bpftrace were not installed on the host, so attrib.sh takes another route: it rebuilds the bench.sh state and compares nft -f with nft -c -f, which per the nft man page checks the commands without applying them, so the transaction is never committed 33. It also times an iptables-nft-restore --test whose input declares one unrelated empty chain, and it counts the chains in the namespace.
#!/bin/bash
# Run as: unshare -rn ./attrib.sh N (bench.sh state, then 20 runs each of three small updates)
set -euo pipefail
N=$1; E=2; W=$(mktemp -d); trap 'rm -rf "$W"' EXIT
for ((lo = 0; lo < N; lo += 50)); do
./kpgen.py ipt-batch "$N" $E $lo $((lo + 50 < N ? lo + 50 : N)) | iptables-nft-restore --noflush
done
./kpgen.py nft-full "$N" $E | nft -f -
for r in {1..20}; do echo "add element ip kp service-ips { 10.97.0.$r . tcp . 80 : drop }" > "$W/el.$r"; done
printf '*nat\n:KUBE-TINY - [0:0]\nCOMMIT\n' > "$W/tiny"
export W
echo "services=$N chains=$(nft list chains | grep -c 'chain ')"
/usr/bin/time -f "nft -c -f, x20: %es user=%Us sys=%Ss" bash -c 'for f in "$W"/el.{1..20}; do nft -c -f "$f"; done'
/usr/bin/time -f "nft -f, x20: %es user=%Us sys=%Ss" bash -c 'for f in "$W"/el.{1..20}; do nft -f "$f"; done'
/usr/bin/time -f "one empty chain, iptables-nft-restore --noflush --test, x20: %es user=%Us sys=%Ss" \
bash -c 'for r in {1..20}; do iptables-nft-restore --noflush --test < "$W/tiny"; done'#!/bin/bash
# Run as: unshare -rn ./empty.sh (fresh, otherwise empty network namespace)
set -euo pipefail
W=$(mktemp -d); trap 'rm -rf "$W"' EXIT
nft -f - <<< 'add table ip small; add map ip small m { type ipv4_addr . inet_proto . inet_service : verdict ; }'
for r in {1..20}; do echo "add element ip small m { 10.97.0.$r . tcp . 80 : drop }" > "$W/sm.$r"; done
tot=0; for f in "$W"/sm.{1..20}; do s=$(date +%s%N); nft -f "$f"; tot=$((tot + $(date +%s%N) - s)); done
echo "one element, empty namespace ms=$(echo "scale=1; $tot / 20 / 1000000" | bc)"| Services | nf_tables chains | nft -c -f, per run | nft -f, per run | nft -f, user / sys over 20 runs | iptables-nft-restore --test, one empty chain, per run |
|---|---|---|---|---|---|
| 1,000 | 4,004 | 23.5 / 25.0 ms | 13.0 / 13.0 ms | 0.07 / 0.19 s and 0.07 / 0.18 s | 12.0 / 11.0 ms |
| 5,000 | 20,004 | 59.5 / 64.5 ms | 54.0 / 52.5 ms | 0.26 / 0.81 s and 0.28 / 0.76 s | 12.5 / 12.5 ms |
| 10,000 | 40,004 | 100.5 / 105.5 ms | 99.0 / 88.5 ms | 0.50 / 1.46 s and 0.43 / 1.32 s | 12.0 / 12.0 ms |
The check cost as much as the commit at every size, and more at 1,000 Services, where the check loop ran first. So the step 2 walk, real as it is, is not where the size-dependent cost goes on this host: the cost is paid before any commit. About 70 to 75 percent of the nft -f time was system time, which means most of it is kernel work done on behalf of the nft process. My hypothesis is that this is nft reading the existing objects of the namespace from the kernel before it builds and sends its batch. The lab does not prove that, and it would take tracing on nft and on the netlink dump path to settle it. The iptables side behaves differently: an iptables-nft-restore --test that touched one unrelated chain cost about 12 ms at every size, so its size-dependent cost comes from what the input touches, which in a partial sync is the n-rule KUBE-SERVICES chain.
#!/bin/bash
# Run as: unshare -rn ./events.sh N (N must stay below the batch limit to commit)
set -euo pipefail
N=$1; E=2; W=$(mktemp -d); trap 'rm -rf "$W"' EXIT
for ((lo = 0; lo < N; lo += 50)); do
./kpgen.py ipt-batch "$N" $E $lo $((lo + 50 < N ? lo + 50 : N)) | iptables-nft-restore --noflush
done
nft monitor rules > "$W/ev" & M=$!; sleep 1
./kpgen.py ipt-sync "$N" $E 1 | iptables-nft-restore --noflush
sleep 1; kill $M
echo "services=$N deleted rules=$(grep -c '^delete rule' "$W/ev") added rules=$(grep -c '^add rule' "$W/ev")"events.sh shows the iptables-nft transaction from the kernel's side. A real partial sync can only be committed below the batch limit, so it runs at 60 Services. One Service changed, and nft monitor reported 63 deleted rules and 67 added rules: the 60 KUBE-SERVICES rules, the KUBE-MARK-MASQ rule and the changed Service's two KUBE-SVC rules were deleted, and the same 63 rules plus four rules in the two new endpoint chains were written back. Every Service in the cluster costs a rule deletion and a rule insertion in each partial sync, which is the n-rule rewrite described above.
The practical reading is that the nftables backend makes the payload of an update independent of cluster size, while each nft invocation still pays something for the size of everything else on the node, and that cost stays below the iptables restore's parse-and-construct time from 5,000 Services up: by a factor of about 2.4 to 2.8 at 5,000 and 5.5 to 9.2 at 10,000 in this lab, with the iptables figure still excluding its commit. At 1,000 Services the two were comparable.
The lab says nothing about packet latency. The data-plane comparison in the nftables announcement, taken from measurements presented at KubeCon North America 2024, found that in clusters of 5,000 and 10,000 Services the nftables p50 first-packet latency was about the same as the iptables p01, and that at 30,000 Services the nftables p99 beat the iptables p01 by a few microseconds. The same post states that nftables mode has the same performance as IPVS mode, and slightly better 7.
Choosing a mode
The decision is simpler than the mechanics. On nodes with kernel 5.13 or newer and every netfilter-touching component verified against it, use nftables. The data plane is at least as fast as either alternative, an update's payload is proportional to what changed, and the table is owned by kube-proxy alone 7 4. Keep iptables mode where an older kernel, or a CNI or policy engine that still edits kube-proxy's iptables chains, rules nftables out. Below a few thousand Services its update cost is tolerable, and partial sync already removed most of the waste 1. Move off IPVS on a schedule, not when 1.40 forces it 1.
Whatever you choose, write it down. The default is still iptables in v1.37, and the documentation warns that a future release will change it to nftables; it asks every cluster to set the mode explicitly so that an upgrade does not change the proxy backend underneath it 1. With GitOps that means the KubeProxyConfiguration lives in the repository with mode set, so the backend changes in a reviewed commit and not as a side effect of a version bump.
Then measure what you have. kubeproxy_sync_proxy_rules_duration_seconds and its full and partial variants kubeproxy_sync_full_proxy_rules_duration_seconds and kubeproxy_sync_partial_proxy_rules_duration_seconds are exported by both backends, and kubeproxy_network_programming_duration_seconds measures the time from an EndpointSlice change to rules in the kernel 34. If the partial-sync histogram climbs with your Service count, you are paying the linear KUBE-SERVICES rewrite this article describes, and the fix is a different backend, not a larger minSyncPeriod.
Izvori
- Virtual IPs and Service Proxies Kubernetes Documentation (v1.37)
- pkg/features/kube_features.go (NFTablesProxyMode, NFTablesNetlink, KubeProxyIPVS) Kubernetes v1.37.2 source
- KEP-5495: Deprecate ipvs mode in kube-proxy Kubernetes Enhancements, SIG Network
- NFTables kube-proxy (pkg/proxy/nftables/README.md) Kubernetes v1.37.2 source
- pkg/proxy/iptables/proxier.go Kubernetes v1.37.2 source
- net/netfilter/nf_nat_core.c (nf_nat_inet_fn) Linux v7.2 source
- NFTables mode for kube-proxy (Dan Winship, 2025-02-28) Kubernetes Blog
- net/netfilter/xt_statistic.c (statistic_mt) Linux v7.2 source
- net/ipv4/netfilter/ip_tables.c (ipt_do_table, translate_table, do_replace) Linux v7.2 source
- net/netfilter/x_tables.c (do_replace_table, xt_replace_table) Linux v7.2 source
- KEP-3866: Add an nftables-based kube-proxy backend Kubernetes Enhancements, SIG Network
- KEP-3453: Minimizing iptables-restore input size Kubernetes Enhancements, SIG Network
- iptables-restore(8) Linux man-pages project (man7.org)
- pkg/proxy/util/utils.go (FullSyncPeriod) Kubernetes v1.37.2 source
- pkg/proxy/runner/bounded_frequency_runner.go (NewBoundedFrequencyRunner) Kubernetes v1.37.2 source
- pkg/util/iptables/iptables.go (Monitor) Kubernetes v1.37.2 source
- net/netfilter/ipvs/ip_vs_ctl.c (ip_vs_svc_hashval) Linux v7.2 source
- net/netfilter/ipvs/ip_vs_conn.c (connection table, conn_tab_bits) Linux v7.2 source
- net/netfilter/ipvs/ip_vs_core.c (ip_vs_ops4 hook registration, ip_vs_rht_desired_size) Linux v7.2 source
- include/net/ip_vs.h (IP_VS_CONN_TAB_MIN_BITS) Linux v7.2 source
- Documentation/networking/ipvs-sysctl.rst (conn_lfactor) Linux v7.2 source
- pkg/proxy/ipvs/proxier.go Kubernetes v1.37.2 source
- pkg/proxy/ipvs/ipset.go Kubernetes v1.37.2 source
- pkg/proxy/nftables/proxier.go Kubernetes v1.37.2 source
- net/netfilter/nf_tables_api.c (nft_select_set_ops, nf_tables_commit) Linux v7.2 source
- net/netfilter/nft_set_hash.c (nft_rhash_estimate) Linux v7.2 source
- net/netfilter/nft_numgen.c (nft_ng_random_gen) Linux v7.2 source
- knftables v0.0.22 nftables.go (Run, UseNetlink) Kubernetes SIGs
- pkg/proxy/nftables/supported.go (getNFTablesInterface) Kubernetes v1.37.2 source
- include/net/netfilter/nf_tables.h (generation cursor) Linux v7.2 source
- kind v0.33.0 pkg/apis/config/defaults/image.go Kubernetes SIGs
- kind Configuration: kube-proxy mode kind documentation
- nft(8) netfilter.org
- pkg/proxy/metrics/metrics.go Kubernetes v1.37.2 source