Sticky session load balancing with Apache and mod_balancer on Ubuntu Linux

Apache 2.2 can do load balancing with sticky sessions. However, there is a catch. You need to use mod_headers module to set a cookie based on the chosen balancer member for the first request and then route the subsequent requests to this client.

Use cases

The method described here works in every situation and does not rely on client IP address, etc. The only downside is that if one balancer member goes down all subsequent requests for it will die. So this method can be only used for load balancing, not for high availability (I am not sure if BALANCER_ROUTE_CHANGED environment variable is set when a balancer member is lost and would redirect the clients to a new balancer member).

This requests were tested on Ubuntu Linux, but may as well work in other environments.

1. Setting route configution in virtual host

Create a balancer

<Proxy balancer://yourlb>
 BalancerMember http://127.0.0.1:13001/ route=1
 BalancerMember http://127.0.0.1:13002/ route=2
 BalancerMember http://127.0.0.1:13003/ route=3
 BalancerMember http://127.0.0.1:13004/ route=4
</Proxy>

Set the cookie using mod_headers. Note that the cookie must be in format [session name].[route id] (the dot is required). It seems to be possible to leave session name empty.

Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED

Make ProxyPass  follow the cookie (Zope virtual host monster style with HTTPS)

ProxyPass / balancer://lbsits/http://localhost/VirtualHostBase/https/yoursite.org:443/yourplonesiteid/VirtualHostRoot/ stickysession=ROUTEID

Note: Hard restart is required. apache2ctl graceful is not enough to make new balancer rules effective.

2. Testing

Use wget

wget -S https://yoursite.org/

See that Set-Cookie: ROUTE_ID is present and it contains a valid value (is not empty)

HTTP/1.1 200 OK
 Date: Wed, 13 Apr 2011 15:21:52 GMT
 Server: Zope/(Zope 2.10.9-final, python 2.4.5, linux2) ZServer/1.1 Plone/3.3.3
 Content-Length: 23197
 Expires: Sat, 01 Jan 2000 00:00:00 GMT
 Content-Type: text/html;charset=utf-8
 Content-Language: en
 Set-Cookie: I18N_LANGUAGE="en"; Path=/
 Set-Cookie: ROUTEID=.1; path=/

3. More info

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

One thought on “Sticky session load balancing with Apache and mod_balancer on Ubuntu Linux

  1. I am constantly getting an error “service temporary unavailable” when working in Apache tomcat. could that be caused by sticky session? thx

Leave a Reply

Your email address will not be published. Required fields are marked *