Multi-tier load-balancing with Linux

Vincent Bernat

A com­mon so­lu­tion to pro­vide a highly-avail­able and scal­able ser­vice is to in­sert a load-bal­anc­ing layer to spread re­quests from users to back­end servers.1 We usu­ally have sev­eral ex­pec­ta­tions for such a layer:

Scal­a­bil­ity
It al­lows a ser­vice to scale by push­ing traf­fic to newly pro­vi­sioned back­end servers. It should also be able to scale it­self when it be­comes the bot­tleneck.
Avail­abil­ity
It pro­vides high avail­abil­ity to the ser­vice. If one server be­comes un­avail­able, the traf­fic should be quickly steered to an­other server. The load-bal­anc­ing layer it­self should also be highly available.
Flex­i­bil­ity
It han­dles both short and long con­nec­tions. It is flex­i­ble enough to of­fer all the fea­tures back­ends gen­er­ally ex­pect from a load-bal­ancer like TLS or HTTP routing.
Op­er­abil­ity
With some co­op­er­a­tion, any ex­pected change should be seam­less: rolling out a new soft­ware on the back­ends, adding or re­mov­ing back­ends, or scal­ing up or down the load-bal­anc­ing layer itself.

The prob­lem and its so­lu­tions are well known. From re­cently pub­lished ar­ti­cles on the topic, “In­tro­duc­tion to mod­ern net­work load-bal­anc­ing and prox­y­ing” pro­vides an over­view of the state of the art. Google re­leased “Ma­glev: A Fast and Re­li­able Soft­ware Net­work Load Bal­ancer” de­scrib­ing their in-house so­lu­tion in de­tail.2 How­ever, the as­so­ci­ated soft­ware is not avail­able. Build­ing a load-bal­anc­ing so­lu­tion with com­mod­ity servers con­sists of as­sem­bling three com­ponents:

  • ECMP routing
  • state­less L4 load-balancing
  • state­ful L7 load-balancing

In this ar­ti­cle, I de­scribe and sup­port a multi-tier so­lu­tion us­ing Linux and only open-source com­po­nents. It should of­fer you the ba­sis to build a pro­duc­tion-ready load-bal­anc­ing layer.

Up­date (2018-05)

Face­book just re­leased Ka­tran, an L4 load-bal­ancer im­ple­mented with XDP and eBPF and us­ing con­sis­tent hash­ing. It could be in­serted in the con­fig­u­ra­tion de­scribed below.

Up­date (2018-08)

GitHub just re­leased GLB Di­rec­tor, an L4 load-bal­ancer us­ing a ren­dez-vous hash­ing to se­lect a pair of L7 load-bal­ancers. Us­ing a cus­tom Net­fil­ter mod­ule, the first mem­ber redi­rects the flow to the sec­ond if it is un­able to find a match in its con­nec­tion table.

Up­date (2021-12)

Cil­ium 1.10+ uses a sim­i­lar ap­proach to the one de­scribed in this ar­ti­cle to man­age ser­vices in a Ku­ber­netes clus­ter. Check out the doc­u­men­ta­tion about Ku­ber­netes with­out kube-proxy as well as the doc­u­men­ta­tion on how to set up BGP.

Last tier: L7 load-balancing#

Let’s start with the last tier. Its role is to pro­vide high avail­abil­ity, by for­ward­ing re­quests to only healthy back­ends, and scal­a­bil­ity, by spread­ing re­quests fairly be­tween them. Work­ing in the high­est lay­ers of the OSI model, it can also of­fer ad­di­tional ser­vices, like TLS-ter­mi­na­tion, HTTP rout­ing, header rewrit­ing, rate-lim­it­ing of unau­then­ti­cated users, and so on. Be­ing state­ful, it can lever­age com­plex load-bal­anc­ing al­go­rithms. Be­ing the first point of con­tact with back­end servers, it should ease main­te­nances and min­i­mize im­pact dur­ing daily changes.

L7 load-balancers
The last tier of the load-balancing solution is a set of L7 load-balancers receiving user connections and forwarding them to the backends.

It also ter­mi­nates client TCP con­nec­tions. This in­tro­duces some loose cou­pling be­tween the load-bal­anc­ing com­po­nents and the back­end servers with the fol­low­ing benefits:

  • con­nec­tions to servers can be kept open for lower re­source use and latency;
  • re­quests can be re­tried trans­par­ently in case of failure;
  • clients can use a dif­fer­ent IP pro­to­col than servers; and
  • servers do not have to care about path MTU dis­cov­ery, TCP con­ges­tion con­trol al­go­rithms, avoid­ance of the TIME-WAIT state, and var­i­ous other low-level details.

Many pieces of soft­ware would fit in this layer and an am­ple lit­er­a­ture ex­ists on how to con­fig­ure them. You could look at HAProxy, En­voy or Trae­fik. Here is a con­fig­u­ra­tion ex­am­ple for HAProxy:

# L7 load-balancer endpoint
frontend l7lb
  # Listen on both IPv4 and IPv6
  bind :80 v4v6
  # Redirect everything to a default backend
  default_backend servers
  # Healthchecking
  acl dead nbsrv(servers) lt 1
  acl disabled nbsrv(enabler) lt 1
  monitor-uri /healthcheck
  monitor fail if dead || disabled

# IPv6-only servers with HTTP healthchecking and remote agent checks
backend servers
  balance roundrobin
  option httpchk
  server web1 [2001:db8:1:0:2::1]:80 send-proxy check agent-check agent-port 5555
  server web2 [2001:db8:1:0:2::2]:80 send-proxy check agent-check agent-port 5555
  server web3 [2001:db8:1:0:2::3]:80 send-proxy check agent-check agent-port 5555
  server web4 [2001:db8:1:0:2::4]:80 send-proxy check agent-check agent-port 5555

# Fake backend: if the local agent check fails, we assume we are dead
backend enabler
  server enabler [::1]:0 agent-check agent-port 5555

This con­fig­u­ra­tion is the most in­com­plete piece of this guide. How­ever, it il­lus­trates two key con­cepts for op­er­ability:

  1. Healthcheck­ing of the web servers is done both at HTTP-level (with check and option httpchk) and us­ing an aux­il­iary agent check (with agent-check). The lat­ter makes it easy to put a server to main­te­nance or to or­ches­trate a pro­gres­sive roll­out. On each back­end, you need a process lis­ten­ing on port 5555 and re­port­ing the sta­tus of the ser­vice (UP, DOWN, MAINT). A sim­ple socat process can do the trick:3

    socat -ly \
      TCP6-LISTEN:5555,ipv6only=0,reuseaddr,fork \
      OPEN:/etc/lb/agent-check,rdonly
    

    Put UP in /etc/​lb/​agent-check when the ser­vice is in nom­i­nal mode. If the reg­u­lar healthcheck is also pos­i­tive, HAProxy will send re­quests to this node. When you need to put it in main­te­nance, write MAINT and wait for the ex­ist­ing con­nec­tions to ter­mi­nate. Use READY to can­cel this mode.

  2. The load-bal­ancer it­self should pro­vide a healthcheck end­point (/healthcheck) for the up­per tier. It will re­turn a 503 er­ror if ei­ther there are no back­end servers avail­able or if the enabler back­end is put down through the agent check. The same mech­a­nism as for reg­u­lar back­ends can be used to sig­nal the un­avail­abil­ity of this load-balancer.

Ad­di­tion­ally, the send-proxy di­rec­tive en­ables the proxy pro­to­col to trans­mit the real clients’ IP ad­dresses. This pro­to­col also works for non-HTTP con­nec­tions and is sup­ported by a va­ri­ety of servers, in­clud­ing nginx:

http {
  server {
    listen [::]:80 default ipv6only=off proxy_protocol;
    root /var/www;
    set_real_ip_from ::/0;
    real_ip_header proxy_protocol;
  }
}

As is, this so­lu­tion is not com­plete. We have just moved the avail­abil­ity and scal­a­bil­ity prob­lem some­where else. How do we load-bal­ance the re­quests be­tween the load-balancers?

First tier: ECMP routing#

On most mod­ern routed IP net­works, re­dun­dant paths ex­ist be­tween clients and servers. For each packet, routers have to choose a path. When the cost as­so­ci­ated to each path is equal, in­com­ing flows4 are load-bal­anced among the avail­able des­ti­na­tions. This char­ac­ter­is­tic can be used to bal­ance con­nec­tions among avail­able load-balancers:

ECMP routing
ECMP routing is used as a first tier. Flows are spread among available L7 load-balancers. Routing is stateless and asymmetric. Backend servers are not represented.

There is lit­tle con­trol over the load-bal­anc­ing but ECMP rout­ing brings the abil­ity to scale hor­i­zon­tally both tiers. A com­mon way to im­ple­ment such a so­lu­tion is to use BGP, a rout­ing pro­to­col to ex­change routes be­tween net­work de­vices. Each load-bal­ancer an­nounces to its con­nected routers the IP ad­dresses it is serving.

If we as­sume you al­ready have BGP-en­abled routers avail­able, ExaBGP is a flex­i­ble so­lu­tion to let the load-bal­ancers ad­ver­tise their avail­abil­ity. Here is a con­fig­u­ra­tion for one of the load-balancers:

# Healthcheck for IPv6
process service-v6 {
  run python -m exabgp healthcheck -s --interval 10 --increase 0 --cmd "test -f /etc/lb/v6-ready -a ! -f /etc/lb/disable";
  encoder text;
}

template {
  # Template for IPv6 neighbors
  neighbor v6 {
    router-id 192.0.2.132;
    local-address 2001:db8::192.0.2.132;
    local-as 65000;
    peer-as 65000;
    hold-time 6;
    family {
      ipv6 unicast;
    }
    api services-v6 {
      processes [ service-v6 ];
    }
  }
}

# First router
neighbor 2001:db8::192.0.2.254 {
  inherit v6;
}

# Second router
neighbor 2001:db8::192.0.2.253 {
  inherit v6;
}

If /etc/​lb/​v6-ready is present and /etc/​lb/​disable is ab­sent, all the IP ad­dresses con­fig­ured on the lo in­ter­face will be an­nounced to both routers. If the other load-bal­ancers use a sim­i­lar con­fig­u­ra­tion, the routers will dis­trib­ute in­com­ing flows be­tween them. Some ex­ter­nal process should man­age the ex­is­tence of the /etc/​lb/​v6-ready file by check­ing for the health­i­ness of the load-bal­ancer (us­ing the /healthcheck end­point for ex­am­ple). An op­er­a­tor can re­move a load-bal­ancer from the ro­ta­tion by cre­at­ing the /etc/​lb/​disable file.

To get more de­tails on this part, have a look at “High avail­abil­ity with ExaBGP.” If you are in the cloud, this tier is usu­ally im­ple­mented by your cloud provider, ei­ther us­ing an any­cast IP ad­dress or a ba­sic L4 load-balancer.

Un­for­tu­nately, this so­lu­tion is not re­silient when an ex­pected or un­ex­pected change hap­pens. No­tably, when adding or re­mov­ing a load-bal­ancer, the num­ber of avail­able routes for a des­ti­na­tion changes. The hash­ing al­go­rithm used by routers is not con­sis­tent and flows are reshuf­fled among the avail­able load-bal­ancers, break­ing ex­ist­ing con­nections:

Stability of ECMP routing 1/2
ECMP routing is unstable when a change happens. An additional load-balancer is added to the pool and the flows are routed to different load-balancers, which do not have the appropriate entries in their connection tables.

More­over, each router may choose its own routes. When a router be­comes un­avail­able, the sec­ond one may route the same flows dif­ferently:

Stability of ECMP routing 2/2
A router becomes unavailable and the remaining router load-balances its flows differently. One of them is routed to a different load-balancer, which does not have the appropriate entry in its connection table.

If you think this is not an ac­cept­able out­come, no­tably if you need to han­dle long con­nec­tions like file down­loads, video stream­ing or web­socket con­nec­tions, you need an ad­di­tional tier. Keep reading!

Up­date (2021-03)

Some hard­ware ven­dors sup­port re­silient hash­ing to help cir­cum­vent this lim­i­ta­tion. See for ex­am­ple the doc­u­men­ta­tion from Ju­niper and Cu­mu­lus. Thanks to Jessy Vet­ter for the tip! This fea­ture has also been added in Linux 5.12.

Second tier: L4 load-balancing#

The sec­ond tier is the glue be­tween the state­less world of IP routers and the state­ful land of L7 load-bal­anc­ing. It is im­ple­mented with L4 load-bal­anc­ing. The ter­mi­nol­ogy can be a bit con­fus­ing here: this tier routes IP data­grams (no TCP ter­mi­na­tion) but the sched­uler uses both des­ti­na­tion IP and port to choose an avail­able L7 load-bal­ancer. The pur­pose of this tier is to en­sure all mem­bers take the same sched­ul­ing de­ci­sion for an in­com­ing packet.

There are two options:

  • state­ful L4 load-bal­anc­ing with state syn­chro­niza­tion across the members; or
  • state­less L4 load-bal­anc­ing with con­sis­tent hashing.

The first op­tion in­creases com­plex­ity and lim­its scal­a­bil­ity. We won’t use it.5 The sec­ond op­tion is less re­silient dur­ing some changes but can be en­hanced with a hy­brid ap­proach us­ing a lo­cal state.

We use IPVS, a per­for­mant L4 load-bal­ancer run­ning in­side the Linux ker­nel, with Keepalived, a fron­tend to IPVS with a set of healthcheck­ers to kick out an un­healthy com­po­nent. IPVS is con­fig­ured to use the Ma­glev sched­uler, a con­sis­tent hash­ing al­go­rithm from Google. Among its fam­ily, this is a great al­go­rithm be­cause it spreads con­nec­tions fairly, min­i­mizes dis­rup­tions dur­ing changes and is quite fast at build­ing its lookup ta­ble. Fi­nally, to im­prove per­for­mance, we let the last tier—the L7 load-bal­ancers—send back an­swers di­rectly to the clients with­out in­volv­ing the sec­ond tier—the L4 load-bal­ancers. This is re­ferred to as di­rect server re­turn (DSR) or di­rect rout­ing (DR).

Second tier: L4 load-balancing
L4 load-balancing with IPVS and consistent hashing as a glue between the first tier and the third tier. Backend servers have been omitted. Dotted lines represent the path for the return packets.

With such a setup, we ex­pect pack­ets from a flow to be able to move freely be­tween the com­po­nents of the first two tiers while stick­ing to the same L7 load-balancer.

Configuration#

As­sum­ing ExaBGP has al­ready been con­fig­ured like de­scribed in the pre­vi­ous sec­tion, let’s start with the con­fig­u­ra­tion of Keepalived:

virtual_server_group VS_GROUP_MH_IPv6 {
  2001:db8::198.51.100.1 80
}
virtual_server group VS_GROUP_MH_IPv6 {
  lvs_method TUN  # Tunnel mode for DSR
  lvs_sched mh    # Scheduler: Maglev
  mh-port         # Use port information for scheduling
  protocol TCP
  delay_loop 5
  alpha           # All servers are down on start
  omega           # Execute quorum_down on shutdown
  quorum_up   "/bin/touch /etc/lb/v6-ready"
  quorum_down "/bin/rm -f /etc/lb/v6-ready"

  # First L7 load-balancer
  real_server 2001:db8::192.0.2.132 80 {
    weight 1
    HTTP_GET {
      url {
        path /healthcheck
        status_code 200
      }
      connect_timeout 2
    }
  }

  # Many others...
}

The quorum_up and quorum_​down state­ments de­fine the com­mands to be ex­e­cuted when the ser­vice be­comes avail­able and un­avail­able re­spec­tively. The /etc/​lb/​v6-ready file is used as a sig­nal to ExaBGP to ad­ver­tise the ser­vice IP ad­dress to the neigh­bor routers.

Ad­di­tion­ally, IPVS needs to be con­fig­ured to con­tinue rout­ing pack­ets from a flow moved from an­other L4 load-bal­ancer. It should also con­tinue rout­ing pack­ets from un­avail­able des­ti­na­tions to en­sure we can drain prop­erly an L7 load-balancer.

# Schedule non-SYN packets
sysctl -qw net.ipv4.vs.sloppy_tcp=1
# Do NOT reschedule a connection when destination
# doesn't exist anymore
sysctl -qw net.ipv4.vs.expire_nodest_conn=0
sysctl -qw net.ipv4.vs.expire_quiescent_template=0

The Ma­glev sched­ul­ing al­go­rithm will be avail­able with Linux 4.18, thanks to Inju Song. For older ker­nels, I have pre­pared a back­port.6 Use of source hash­ing as a sched­ul­ing al­go­rithm will hurt the re­silience of the setup.

DSR is im­ple­mented us­ing the tun­nel mode. This method is com­pat­i­ble with routed dat­a­cen­ters and cloud en­vi­ron­ments. Re­quests are tun­neled to the sched­uled peer us­ing IPIP en­cap­su­la­tion. It adds a small over­head and may lead to MTU is­sues. If pos­si­ble, en­sure you are us­ing a larger MTU for com­mu­ni­ca­tion be­tween the sec­ond and the third tier.7 Oth­er­wise, it is bet­ter to ex­plic­itly al­low frag­men­ta­tion of IP packets:

sysctl -qw net.ipv4.vs.pmtu_disc=0

You also need to con­fig­ure the L7 load-bal­ancers to han­dle en­cap­su­lated traffic:8

# Setup IPIP tunnel to accept packets from any source
ip tunnel add tunlv6 mode ip6ip6 local 2001:db8::192.0.2.132
ip link set up dev tunlv6
ip addr add 2001:db8::198.51.100.1/128 dev tunlv6

Evaluation of the resilience#

As con­fig­ured, the sec­ond tier in­creases the re­silience of this setup for two reasons:

  1. The sched­ul­ing al­go­rithm is us­ing a con­sis­tent hash to choose its des­ti­na­tion. Such an al­go­rithm re­duces the neg­a­tive im­pact of ex­pected or un­ex­pected changes by min­i­miz­ing the num­ber of flows mov­ing to a new des­ti­na­tion. “Con­sis­tent Hash­ing: Al­go­rith­mic Trade­offs” of­fers more de­tails on this subject.

  2. IPVS keeps a lo­cal con­nec­tion ta­ble for known flows. When a change im­pacts only the third tier, ex­ist­ing flows will be cor­rectly di­rected ac­cord­ing to the con­nec­tion table.

If we add or re­move an L4 load-bal­ancer, ex­ist­ing flows are not im­pacted be­cause each load-bal­ancer takes the same de­ci­sion, as long as they see the same set of L7 load-balancers:

L4 load-balancing instability 1/3
Losing an L4 load-balancer has no impact on existing flows. Each arrow is an example of flow. The dots are flow endpoints bound to the associated load-balancer. If they had moved to another load-balancer, connection would have been lost.

If we add an L7 load-bal­ancer, ex­ist­ing flows are not im­pacted ei­ther be­cause only new con­nec­tions will be sched­uled to it. For ex­ist­ing con­nec­tions, IPVS will look at its lo­cal con­nec­tion ta­ble and con­tinue to for­ward pack­ets to the orig­i­nal des­ti­na­tion. Sim­i­larly, if we re­move an L7 load-bal­ancer, only ex­ist­ing flows ter­mi­nat­ing at this load-bal­ancer are im­pacted. Other ex­ist­ing con­nec­tions will be for­warded correctly:

L4 load-balancing instability 2/3
Losing an L7 load-balancer only impacts the flows bound to it.

We need to have si­mul­ta­ne­ous changes on both lev­els to get a no­tice­able im­pact. For ex­am­ple, when adding both an L4 load-bal­ancer and an L7 load-bal­ancer, only con­nec­tions moved to an L4 load-bal­ancer with­out state and sched­uled to the new load-bal­ancer will be bro­ken. Thanks to the con­sis­tent hash­ing al­go­rithm, other con­nec­tions will stay bound to the right L7 load-bal­ancer. Dur­ing a planned change, this dis­rup­tion can be min­i­mized by adding the new L4 load-bal­ancers first, wait­ing a few min­utes, then adding the new L7 load-balancers.

L4 load-balancing instability 3/3
Both an L4 load-balancer and an L7 load-balancer come back to life. The consistent hash algorithm ensures that only one fifth of the existing connections would be moved to the incoming L7 load-balancer. Some of them continue to be routed through their original L4 load-balancer, which mitigates the impact.

Ad­di­tion­ally, IPVS cor­rectly routes ICMP mes­sages to the same L7 load-bal­ancers as the as­so­ci­ated con­nec­tions.9 This en­sures path MTU dis­cov­ery works and there is no need for smart work­arounds.

Tier 0: DNS load-balancing#

Op­tion­ally, you can add DNS load-bal­anc­ing to the mix. This is use­ful ei­ther if your setup is spanned across mul­ti­ple dat­a­cen­ters, or mul­ti­ple cloud re­gions, or if you want to break a large load-bal­anc­ing clus­ter into smaller ones. It is not in­tended to re­place the first tier as it doesn’t share the same char­ac­ter­is­tics: load-bal­anc­ing is un­fair (it is not flow-based) and re­cov­ery from a fail­ure is slow.

Complete load-balancing solution
A complete load-balancing solution spanning across two datacenters.

gdnsd is an au­thor­i­ta­tive-only DNS server with in­te­grated healthcheck­ing. It can serve zones from mas­ter files us­ing the RFC 1035 zone format:

@ SOA ns1 ns1.example.org. 1 7200 1800 259200 900
@ NS ns1.example.com.
@ NS ns1.example.net.
@ MX 10 smtp

@     60 DYNA multifo!web
www   60 DYNA multifo!web
smtp     A    198.51.100.99

The spe­cial RR type DYNA will re­turn A and AAAA records af­ter query­ing the spec­i­fied plugin. Here, the multifo plugin im­ple­ments an all-ac­tive failover of mon­i­tored ad­dresses:

service_types => {
  web => {
    plugin => http_status
    url_path => /healthcheck
    down_thresh => 5
    interval => 5
  }
  ext => {
    plugin => extfile
    file => /etc/lb/ext
    def_down => false
  }
}

plugins => {
  multifo => {
    web => {
      service_types => [ ext, web ]
      addrs_v4 => [ 198.51.100.1, 198.51.100.2 ]
      addrs_v6 => [ 2001:db8::198.51.100.1, 2001:db8::198.51.100.2 ]
    }
  }
}

In nom­i­nal state, an A re­quest will be an­swered with both 198.51.100.1 and 198.51.100.2. A healthcheck fail­ure will up­date the re­turned set ac­cord­ingly. It is also pos­si­ble to ad­min­is­tra­tively re­move an en­try by mod­i­fy­ing the /etc/​lb/​ext file. For ex­am­ple, with the fol­low­ing con­tent, 198.51.100.2 will not be ad­ver­tised anymore:

198.51.100.1 => UP
198.51.100.2 => DOWN
2001:db8::c633:6401 => UP
2001:db8::c633:6402 => UP

You can find all the con­fig­u­ra­tion files and the setup of each tier in the Git repos­i­tory. If you want to repli­cate this setup at a smaller scale, it is pos­si­ble to col­lapse the sec­ond and the third tiers by us­ing ei­ther lo­caln­ode or net­work names­paces. Even if you don’t need its fancy load-bal­anc­ing ser­vices, you should keep the last tier: while back­end servers come and go, the L7 load-bal­ancers bring sta­bil­ity, which trans­lates to re­siliency.