PHP sessions in a load balancing cluster - how? PHP sessions in a load balancing cluster - how? php php

PHP sessions in a load balancing cluster - how?


You could set PHP to handle the sessions in the database, so all your servers share same session information as all servers use the same database for that.

A good tutorial for that can be found here.


The way we handle this is through memcached. All it takes is changing the php.ini similar to the following:

session.save_handler = memcachesession.save_path = "tcp://path.to.memcached.server:11211"

We use AWS ElastiCache, so the server path is a domain, but I'm sure it'd be similar for local memcached as well.

This method doesn't require any application code changes.


You don't mentioned what technology you are using for load balancing (software, hardware etc.); but in any case, the solution to your problem is to employ "sticky sessions" on the load balancer.

In summary, this means that when the first request from a "new" visitor comes in, they are assigned a specific server from the cluster: all future requests for the lifetime of their session are then directed to that server. In practice this means that applications written to work on a single server can be up-scaled to a balanced environment with zero/few code changes.

If you are using a hardware balancer, such as a Radware device, then the sticky sessions is configured as part of the cluster setup. Hardware devices usually give you more fine-grained control: such as which server a new user is assigned to (they can check for health status etc. and pick the most healthy / least utilised server), and more control of what happens when a server fails and drops out of the cluster. The drawback of hardware balancers is the cost - but they are worth it imho.

As for software balancers, it comes down to what you are using. For Apache there is the stickysession property on mod_proxy - and plenty of articles via google to get this working with the php session ( for example )


Edit:From other comments posted after the original question, it sounds like your "balancing" is done via Round Robin DNS, so the above probably won't apply. I'll refrain from commenting further and starting a flame against round robin dns.