Load balancing

From nftables wiki
Revision as of 20:01, 19 June 2017 by Pablo (talk | contribs) (fix broken example)
Jump to navigation Jump to search

Since nftables v0.7, there is support in place to perform NAT load balancing.

Don't forget the special NAT chain semantics: Only the first packet evaluates the rule, follow up packets rely on conntrack to apply the NAT information.

Round Robin

This method uses the nftables number generator.

The example below is distributing new connections in a round-robin fashion between and

% nft add rule nat prerouting dnat to numgen inc mod 2 map { \
               0 :, \
               1 : }

You can also emulate flow distribution with different backend weights using intervals:

% nft add rule nat prerouting dnat to numgen inc mod 10 map { \
               0-5 :, \
               6-9 : }

The distribution can be based on ports as well:

% nft add rule nat prerouting ip protocol tcp dnat to : numgen inc mod 2 map {\
               0 : 4040 ,\
               1 : 4050 }

Consistent Hash-based Distribution

Using the nftables internal hashing mechanisms.

% nft add rule x y dnat to jhash ip saddr . tcp dport mod 2 map { \
                0 :, \
                1 : }

This relies on the Jenkins hash.

Using stateless NAT

You can perform load balancing through stateless NAT approach as well. You can combine this either with the round robin and consistent hash-based distribution approaches.

The example below uses Round Robin flow distribution:

% nft add rule t c tcp dport 80 ip daddr set numgen inc mod 2 map { 0 :, 1 : }

This is more lightweight that stateful NAT given there is no flow tracking in place.

Using Direct Server Return (DSR)