CARP & HAProxy: High-Availability for Beginners

The field of high-availability in the web area is often complicated, large, and hard to grasp. But it doesn’t have to be, thanks to CARP and HAProxy. The combination of these two techniques makes it possible to distribute requests to multiple servers and thereby avoid the single-point-of-failure problem. For this, we only need at least 2 computers with FreeBSD (or another BSD system with CARP support) that are in the same subnet and some time to set up the following software:

HAProxy

HAProxy is a reverse TCP proxy with load-balancing functionality. It distributes the load to multiple (backend) servers and detects when one of them is no longer reachable. HAProxy can be used for balancing both MySQL requests and HTTP requests. I will focus exclusively on the latter here.

Installation

The easiest way to install it is through the ports tree:

cd /usr/ports/net/haproxy
make install clean

This compiles and installs HAProxy on the system.

Configuration

The configuration file for HAProxy is located at /usr/local/etc/haproxy.conf. A starting point for a working configuration could be the following:

global
        daemon
        maxconn 256

defaults
        mode http
        timeout connect 5000ms
        timeout client 5000ms
        timeout server 5000ms
        stats enable

frontend http-in
        option httplog
        log global
        default_backend servers

backend servers
        server server1 server1.example.com:8080 check
        server server2 server2.example.com:8080 check

CARP

CARP stands for “Common Address Redundancy Protocol”. It allows an IP address to be automatically taken over by another host if it is no longer reachable. The prerequisite for this is that all computers are in the same network segment, as CARP works via broadcast.

Installation

Starting with FreeBSD 9.0, CARP is enabled by default. For older versions, support must either be compiled into the kernel or the kernel module must be activated with the entry:

if_carp_load="YES"

in the file /boot/loader.conf.

Configuration Files

The configuration of CARP is relatively simple. First, a master server is configured. This server holds the IP by default.

To do this, we need to create and configure a CARP interface. During operation, we use:

ifconfig carp0 create
ifconfig vhid 1 pass <password> 10.10.0.1/16

The password and the vhid number must be the same on all backup systems. To ensure this configuration works after a restart, we add the following lines to /etc/rc.conf:

cloned_interfaces="carp0"
ifconfig_carp0="vhid 1 pass <password> 10.10.0.1/16"

On the backup systems, the CARP interface is created in a similar way, but the “advskew” argument is inserted:

cloned_interfaces="carp0"
ifconfig_carp0="vhid 1 advskew 100 pass <password> 10.10.0.1/16"

The higher the value after “advskew”, the lower the priority if the main system fails.