I’ve been playing around with deploying REST web services via Jersey with embedded Jetty servers and decided to use HAProxy as a software load balancer in my development environment as there aren’t any spare F5 appliances lying around.

After downloading the tar, issue the following commands to quickly install HAProxy in your current directory:

$ tar xvfz haproxy-1.4.22.tar.gz
$ cd haproxy-1.4.22
$ sudo make install

Before we start on the configuration file, let’s assume that we have the following endpoints:

# load balanced url

Our simple configuration file will then look like this

        log   local0
        log   local1 notice
        #log loghost    local0 info
        maxconn 4096
        chroot /usr/share/haproxy
        uid 99
        gid 99

        log     global
        mode    http
        option  httplog
        option  dontlognull
        retries 3
        maxconn 2000
        contimeout      5000
        clitimeout      50000
        srvtimeout      50000

listen  servicefarm
        mode http
        cookie SERVERID insert
        balance roundrobin
        option httpclose
        option forwardfor
        stats enable
        stats auth myuser:mypassword 
        server server1 cookie SERVER1 check inter 2000 rise 2 fall 5
        server server2 cookie SERVER2 check inter 2000 rise 2 fall 5

“server1” and “server2” are the server names that will appear in the log files, while “SERVER1” and “SERVER2” will be the cookie strings returned by HAProxy.

Here is what actually happens with the simple HTTP load-balancing with cookie insertion specified above:

  • HAProxy will receive clients requests.
  • If a request does not contain a cookie, it will be forwarded to a valid server.
  • In return, a cookie “SERVERID” will be inserted in the response holding the server name (eg: “SERVER1”).
  • When the client comes again with the cookie “SERVERID=SERVER1”, HAProxy will know that it must be forwarded to server1. The cookie will be removed so that the server does not see it.
  • If “server1” dies, the requests will be sent to another valid server (“server2”)and a cookie will be reassigned.

Next, HAProxy can be started with:

$ ./haproxy -f haproxy.cfg

Now, any calls you make to will be load balanced to either “server1” or “server2”. Fiddler is a nice and simple tool that you can use to inspect your HTTP traffic.

HAProxy also provides a nice stats page that can be accessed at

With the configuration above, the username will be “myuser” and the password “mypassword”.

Lastly, if you ever need to do a hot redeploy of HAProxy, such as picking up an updated configuration file, you can run:

$ ./haproxy -f haproxy.cfg -p haproxy.pid -sf $(cat haproxy.pid)