Apache Load Balancer Persistence

Apache 2.2’s load balancer is pretty neat. However, to get persistence to work properly, you have to be careful. Here we are setting the balancer manager to watch a client cookie called BALANCEID, and each member has a particular route string tied to it that is set in the cookie. It’s important to note that the cookie format must be: something.routestring, ie, nat.server1. If it is just server1, it will not work.

ProxyPass / balancer://mycluster/ stickysession=BALANCEID 
ProxyPassReverse / http://localhost:71/ 
ProxyPassReverse / http://localhost:72/ 
<Proxy balancer://mycluster> 
 BalancerMember http://localhost:71 route=server1 
 BalancerMember http://localhost:72 route=server2 
</Proxy> 

Now there’s the issue of the client cookie being set. What if you are load balancing a third party app or webserver and can’t easily get the cookie set on the client? No problem! While it didn’t work in 2.2.3 (in particular, the BALANCER_ROUTE_CHANGED var being set), when I tried in 2.2.11, I was able to set the cookie myself based on which balancer member was selected:

# Set session cookie if BALANCER_ROUTE_CHANGED, containing BALANCER_WORKER_ROUTE env variable, which is set to the route above 
# Note that cookie value should be a session id, followed by a period, followed by the route. 
# Since session id cookie usually not advised to be mutable, best create own cookie with anything you want 
# for the session part, just make sure to have a period and route part last 
### Used for setting cookie LoadModule headers_module modules/mod_headers.so 
Header add Set-Cookie "BALANCEID=balancer.%{BALANCER_WORKER_ROUTE}e; path=/;" env=BALANCER_ROUTE_CHANGED 
# Just give some debug info in the header, don't use once you have it working 
Header add X-Var "BALANCER_ROUTE_CHANGED=%{BALANCER_ROUTE_CHANGED}e" env=BALANCER_ROUTE_CHANGED 
Header add X-Var "BALANCER_WORKER_ROUTE=%{BALANCER_WORKER_ROUTE}e" env=BALANCER_WORKER_ROUTE 
Header add X-Var "BALANCER_SESSION_ROUTE=%{BALANCER_SESSION_ROUTE}e" env=BALANCER_SESSION_ROUTE 

Presto! Session persistence, all handled at the reverse proxy load balancer level.