32.10. Kernel Load Balancing with LVS and IPVS

LVS - Linux Virtual Server - is the kernel's own load balancer. The IPVS code in the kernel keeps a table of virtual services and real servers and forwards packets at network speed; userspace tools only manage the table. Keepalived is the usual manager, pairing the IPVS table with the VRRP address ownership of the previous section.

32.10.1. Virtual Services, Real Servers, and the IPVS Packet Path

An IPVS virtual server is one address and port that clients connect to; its real servers are the backends that actually answer. The director - the host whose kernel holds the table - examines each inbound packet for a registered virtual service and forwards it to a chosen real server according to a scheduling algorithm. The client speaks only to the virtual address, and every reply arrives as if it came from that address. In all three forwarding modes the backend sees the client's own source address: NAT rewrites the packet's destination on the way in and the reply's source on the way back, and never touches the client's address. What the modes differ in is how the packet reaches the backend and how the reply returns.

IPVS forwarding modes

Figure 32.6. The three forwarding modes. NAT rewrites the destination on the way in and the reply's source on the way back, funnelling every reply through the director; direct routing changes only the frame's MAC address, and backends reply to clients directly; tunneling encapsulates the whole original packet in an IPIP packet, and backends reply directly after decapsulating.

The three modes trade transparency against network requirements. NAT works with any backends that can route back through the director, at the cost of concentrating every reply on the director's interface. Direct routing and tunneling let replies bypass the director entirely - the scalability argument - but require backends configured to accept traffic for an address they do not own, and tunneling additionally requires IPIP support and attention to the MTU.

32.10.2. Installing ipvsadm and Inspecting Kernel Capabilities

The table manager is one small package. On ha1, as john:

$ sudo apt install ipvsadm

Debian's kernel builds IPVS as a module, loaded on first use. Confirm the tool and the kernel implementation:

$ sudo ipvsadm --version 2>&1 | head -1
ipvsadm v1.31 2019/12/24 (compiled with popt and IPVS v1.2.1)

The command needs root because it talks to the kernel's IPVS netlink interface; an ordinary user's ipvsadm fails rather than printing an empty table. There is no configuration file of its own - the table lives in the kernel, and something must own the job of filling it. That something is Keepalived here, so ipvsadm is used purely for inspection.

32.10.3. Scheduling Algorithms, Weights, Persistence, and Timeouts

The scheduler picks a real server for each new connection. The commonly used ones:

Scheduler Chooses Notes
rr round robin exactly the alternation captured below
wrr weighted round robin servers with higher weights get proportionally more connections
lc least connections the server with the fewest active connections
wlc weighted least connections the default choice for uneven hardware
sh source hashing the client address hashes to a server - persistence by construction
dh destination hashing the virtual address hashes to a server
sed shortest expected delay wlc refined for connection cost

Persistence is a modifier, not a scheduler: with persistence_timeout, IPVS remembers which real server served a client and keeps sending that client there for the timeout period, independent of the scheduler. It is the kernel's stickiness, and the NAT exercise below uses it deliberately - its captured request sequence would look like a broken round robin without it. Connection timeouts for established TCP sessions are kernel sysctls (net.ipv4.vs.*), tunable per service or globally; the defaults suit most pools.

32.10.4. Configuring Keepalived virtual_server and real_server Definitions

Keepalived extends its VRRP configuration with a description of the IPVS table. The shape of every entry is the same in all three modes:

virtual_server VIP PORT {
    delay_loop 3
    lb_algo rr
    lb_kind NAT
    protocol TCP
    persistence_timeout 30

    real_server RIP PORT {
        weight 1
        TCP_CHECK {
            connect_timeout 2
            retry 2
            delay_before_retry 1
        }
    }
}

A virtual_server names the address and port clients use, the scheduler (lb_algo), the forwarding mode (lb_kind: NAT, DR, or TUN), and how often the health checker runs (delay_loop). Each real_server names a backend and its check. The TCP_CHECK shown opens a TCP connection to the backend's port - the simplest check that proves something is listening. Keepalived removes a real server from the IPVS table when its check fails and restores it when the check passes, which section 32.10.8 captures in action.

32.10.5. NAT Mode, Forwarding, and Real-Server Return Routes

NAT mode makes the director a router: it rewrites the destination address of inbound packets from the virtual address to the chosen real server, and rewrites the reply's source back to the virtual address. The kernel must therefore forward packets, and it must not short-circuit the redirection with ICMP advice. On ha1, as john:

$ sudo sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
$ sudo sysctl -w net.ipv4.conf.all.send_redirects=0
net.ipv4.conf.all.send_redirects = 0

The second command matters when backends share the client subnet, as the practice network does: without it, the kernel would send ICMP redirects telling the backends to reach the client directly, which would bypass the director and break the reply rewriting.

A backend's replies must return through the director. In a classic NAT deployment the backends sit on a private subnet whose default route is the director, and nothing extra is needed. The practice network is flat - backends and client share one /24 - so the return route must be pinned explicitly, telling each backend to reach the client lbcli (192.168.232.15) via the director. On haclient, as john:

$ sudo ip route replace 192.168.232.15/32 via 192.168.232.11

On lbclient, as john, the same command. Each normally prints nothing.

For a clean single-owner demonstration, stop the second director's Keepalived during the NAT phase. On ha2, as john:

$ sudo systemctl stop keepalived

Now replace /etc/keepalived/keepalived.conf on ha1 with the NAT service - the VRRP instance from section 32.9.2, with a new router ID, new virtual address, and the IPVS service added:

global_defs {
    router_id ha1
    enable_script_security
    script_user root
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth1
    virtual_router_id 52
    priority 100
    advert_int 1
    preempt_delay 5
    unicast_src_ip 192.168.232.11
    unicast_peer {
        192.168.232.12
    }
    virtual_ipaddress {
        192.168.232.160/24 dev eth1
    }
}

virtual_server 192.168.232.160 80 {
    delay_loop 3
    lb_algo rr
    lb_kind NAT
    protocol TCP
    persistence_timeout 30
    real_server 192.168.232.13 8081 {
        weight 1
        TCP_CHECK {
            connect_timeout 2
            retry 2
            delay_before_retry 1
        }
    }
    real_server 192.168.232.14 8081 {
        weight 1
        TCP_CHECK {
            connect_timeout 2
            retry 2
            delay_before_retry 1
        }
    }
}

Start it. On ha1, as john:

$ sudo systemctl restart keepalived

The command normally prints nothing. Keepalived takes the .160 address, creates the virtual service, and checks both backends. Inspect the kernel table it built. On ha1, as john:

$ sudo ipvsadm -L -n
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.232.160:80 rr persistent 30
  -> 192.168.232.13:8081          Masq    1      0          0         
  -> 192.168.232.14:8081          Masq    1      0          0         
Option Description
-L List the IPVS table
-n Numeric addresses and ports, no name resolution
--stats Add per-service and per-server byte and packet counters
-C Clear the whole table (inspection tool only here)

The Masq column marks NAT forwarding, rr the scheduler, and persistent 30 the persistence flag from the configuration. Send traffic through the virtual address. On lbcli, as john:

$ for i in 1 2 3 4; do curl -s --max-time 5 http://192.168.232.160/ | head -1; done
backend=lbclient
backend=lbclient
backend=lbclient
backend=lbclient

All four requests landed on one backend - and that is persistence, not a failure: with persistence_timeout 30, the client lbcli was mapped to one real server for thirty seconds after its first connection, and every request inside that window followed the map. The round-robin scheduler never got to alternate. Compare the alternation in sections 32.10.6 and 32.10.7, which run without persistence - same scheduler, same pool, no map. Persistence exists for exactly the session-affinity reason of section 32.2.3; when using it, remember that it also pins clients to a backend for the timeout after failover behavior is considered - section 32.11.5 returns to that.

The counters confirm what the requests did. On ha1, as john:

$ sudo ipvsadm -L -n --stats
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port               Conns   InPkts  OutPkts  InBytes OutBytes
  -> RemoteAddress:Port
TCP  192.168.232.160:80                  4       20       20     1388     1864
  -> 192.168.232.13:8081                 0        0        0        0        0
  -> 192.168.232.14:8081                 4       20       20     1388     1864

Four connections, all accounted on the .14 real server, both packet directions counted at the virtual service - the second OutPkts column is the director rewriting and forwarding the replies. Stop the backend that is serving, in the terminal on lbclient running backend.py, with Ctrl-C. After the TCP_CHECK failures, the table updates. On ha1, as john:

$ sudo ipvsadm -L -n
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.232.160:80 rr persistent 30
  -> 192.168.232.14:8081          Masq    1      0          4         

The failed real server is gone from the table - Keepalived removed it - and the client's answer was continuity. On lbcli, as john:

$ for i in 1 2 3 4; do curl -s --max-time 5 http://192.168.232.160/ | head -1; done
backend=lbclient
backend=lbclient
backend=lbclient
backend=lbclient

Restart the backend on lbclient afterward (as john, the same python3 ~/debian-handbook/ha/backend.py 8081), and Keepalived will re-add it after its checks pass.

32.10.6. Direct Routing, Real-Server VIPs, and ARP Handling

Direct routing forwards by changing the Ethernet frame only: the packet still carries the virtual address as its destination, and the real server that receives it must therefore accept traffic for the virtual address without ever advertising it. That is the ARP problem, and it has a standard two-part solution.

First, remove the NAT return routes: in direct routing, backends reply to clients directly, and a route pinning replies through the director would defeat the mode. On haclient, as john:

$ sudo ip route del 192.168.232.15/32 via 192.168.232.11

On lbclient, as john, the same. Each normally prints nothing.

Second, configure each backend's ARP behavior and give it the virtual address on loopback. Run these on both backends - the commands and values are identical on the two hosts:

$ sudo sysctl -w net.ipv4.conf.all.arp_ignore=1
net.ipv4.conf.all.arp_ignore = 1
$ sudo sysctl -w net.ipv4.conf.all.arp_announce=2
net.ipv4.conf.all.arp_announce = 2
$ sudo sysctl -w net.ipv4.conf.eth1.arp_ignore=1
net.ipv4.conf.eth1.arp_ignore = 1
$ sudo sysctl -w net.ipv4.conf.eth1.arp_announce=2
net.ipv4.conf.eth1.arp_announce = 2
$ sudo sysctl -w net.ipv4.conf.all.rp_filter=0
net.ipv4.conf.all.rp_filter = 0

arp_ignore=1 makes the kernel answer ARP requests only for addresses configured on the interface that received the request; arp_announce=2 makes it always use the best local source address in replies. Together they keep the loopback VIP invisible to ARP. rp_filter=0 stops the kernel from discarding the forwarded packets, whose destination address (the VIP) is configured on loopback rather than on the receiving interface. Then the address itself:

$ sudo ip addr add 192.168.232.161/32 dev lo

The command normally prints nothing, on both backends.

The director's configuration changes only in the vrrp_instance (the new address .161) and the virtual_server block (lb_kind DR, port 8081, no persistence). Replace /etc/keepalived/keepalived.conf on ha1:

global_defs {
    router_id ha1
    enable_script_security
    script_user root
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth1
    virtual_router_id 53
    priority 100
    advert_int 1
    preempt_delay 5
    unicast_src_ip 192.168.232.11
    unicast_peer {
        192.168.232.12
    }
    virtual_ipaddress {
        192.168.232.161/24 dev eth1
    }
}

virtual_server 192.168.232.161 8081 {
    delay_loop 3
    lb_algo rr
    lb_kind DR
    protocol TCP
    real_server 192.168.232.13 8081 {
        weight 1
        TCP_CHECK {
            connect_timeout 2
            retry 2
            delay_before_retry 1
        }
    }
    real_server 192.168.232.14 8081 {
        weight 1
        TCP_CHECK {
            connect_timeout 2
            retry 2
            delay_before_retry 1
        }
    }
}

Start it. On ha1, as john:

$ sudo systemctl restart keepalived
$ sudo ipvsadm -L -n
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.232.161:8081 rr
  -> 192.168.232.13:8081          Route   1      0          0         
  -> 192.168.232.14:8081          Route   1      0          0         

Route is direct routing's marker. Through the client, on lbcli, as john:

$ for i in 1 2 3 4; do curl -s --max-time 5 http://192.168.232.161:8081/ | head -1; done
backend=lbclient
backend=haclient
backend=lbclient
backend=haclient

Alternating hosts, no persistence: the reply to each request came straight from the backend to the client, never touching the director. Direct routing scales the return path - a backend's reply bandwidth is its own - and it is the standard mode when backends and clients share a segment. When they do not, each backend needs a route for the client network out its own gateway, which is the same requirement stated from the other side.

32.10.7. Tunneling Mode, Encapsulation, MTU, and Return Paths

Tunneling keeps direct routing's "replies bypass the director" property while decoupling the director and backends from a shared segment: the director encapsulates the client's whole packet - virtual destination address intact - inside an IPIP packet addressed to the real server. Each backend must load the IPIP module, hold the virtual address on its tunnel device, and relax reverse-path filtering on that device. Run these on both backends:

$ sudo modprobe ipip
$ sudo ip addr add 192.168.232.162/32 dev tunl0
$ sudo ip link set tunl0 up
$ sudo sysctl -w net.ipv4.conf.tunl0.rp_filter=0
net.ipv4.conf.tunl0.rp_filter = 0

The first three commands normally print nothing; the last echoes the value. The director's configuration swaps the mode and the address (.162) once more. Replace /etc/keepalived/keepalived.conf on ha1:

global_defs {
    router_id ha1
    enable_script_security
    script_user root
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth1
    virtual_router_id 54
    priority 100
    advert_int 1
    preempt_delay 5
    unicast_src_ip 192.168.232.11
    unicast_peer {
        192.168.232.12
    }
    virtual_ipaddress {
        192.168.232.162/24 dev eth1
    }
}

virtual_server 192.168.232.162 8081 {
    delay_loop 3
    lb_algo rr
    lb_kind TUN
    protocol TCP
    real_server 192.168.232.13 8081 {
        weight 1
        TCP_CHECK {
            connect_timeout 2
            retry 2
            delay_before_retry 1
        }
    }
    real_server 192.168.232.14 8081 {
        weight 1
        TCP_CHECK {
            connect_timeout 2
            retry 2
            delay_before_retry 1
        }
    }
}

On ha1, as john:

$ sudo systemctl restart keepalived
$ sudo ipvsadm -L -n
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.232.162:8081 rr
  -> 192.168.232.13:8081          Tunnel  1      0          0         
  -> 192.168.232.14:8081          Tunnel  1      0          0         

And through the client, on lbcli, as john:

$ for i in 1 2 3 4; do curl -s --max-time 5 http://192.168.232.162:8081/ | head -1; done
backend=lbclient
backend=haclient
backend=lbclient
backend=haclient

The MTU is tunneling's standing obligation. Every packet gains 20 bytes of outer IP header, so a client sending full-size 1500-byte packets produces a 1520-byte frame on the wire toward the backend; the backend will not accept it on a 1500-MTU tunnel device, and the failure mode is silent for small requests (which is why the captured curls worked) and fatal for large ones. The standard fixes: configure a reduced MTU on tunl0 on the backends (1480 is the conventional number) so path-MTU discovery informs clients, or ensure ICMP "fragmentation needed" messages flow end to end so PMTUD works. The walkthroughs did not exercise large-packet behavior, so treat the MTU configuration as a documented requirement to apply, not a captured result.

32.10.8. Health Checks, Backend Draining, and Configuration Ownership

Health checking in the Keepalived configurations above is the TCP_CHECK: connect to the real server's port, fail after the configured retries, succeed after a pass. The NAT phase captured the whole cycle - a backend stopped, its entry vanished from the table, the client saw only healthy answers, and the entry returned when the backend did. What the simple check proves is narrow: something accepts TCP connections. Keepalived offers richer checkers (HTTP status checks, negotiated protocol exchanges) when "listening" is not enough, and the choice belongs to the service: a database pool wants a check that actually queries, not one that connects.

Draining is the planned version of a health failure: set a real server's weight to zero - in Keepalived, weight 0 in the real_server block, or ipvsadm -e -t ... -r ... -w 0 interactively - and IPVS stops sending new connections to it while established ones drain. It is the correct way to take a backend out for maintenance, and the captured table behavior in section 32.10.5 shows the unplanned equivalent.

Configuration ownership is the rule that keeps the table sane: Keepalived owns the IPVS table it configures. It creates the services on start, corrects the table as checks run, and rebuilds exactly its configured state on restart - each phase of this section, after replacing the configuration file and restarting, produced a table containing precisely that file's services. Hand-edits with ipvsadm alongside a running Keepalived are therefore transient at best and contradicted at worst: put the change in the configuration file, reload, and let the tool reconcile.

The same ownership question covers the kernel settings this section made directly. Everything sysctl -w set - forwarding and redirect suppression on the director, the backends' ARP behavior and reverse-path filtering - together with the ip route and ip addr add commands on the backends and the modprobe of ipip, is a runtime change that vanishes at reboot; only the director's virtual address and IPVS table are rebuilt automatically, from /etc/keepalived. A deployment persists the rest - the sysctls as /etc/sysctl.d/ entries, and the loopback or tunnel address, the return routes, and the IPIP module in the boot-time network configuration (Chapter 17 covers the mechanisms) - so a rebooted backend rejoins its pool instead of failing every health check.