Jun 112011

If you have multiple load balanced webservers all serving the same site, sessions should be shared among thosememcache logo servers, and not reside on each server individually. Because we don’t know where user gets load-balanced to which backend server. A common way solving this problems are by using custom class that overrides default behavior and stores sessions in a MySQL database. All webservers in clusters connect to the same database. However, the main problem that must be taken into consideration when using a database is the bottleneck.

Example loadbalancing backend using nginx

http {
  upstream backend {
    server weight=3;

  server {
    listen 80;
    server_name www.example.com;
    location / {
      proxy_pass http://backend;

Another alternative solution is using Memcached. Memcached can be used for caching almost everything, function results, html blocks, database query results. But now we’re going to use it to store sessions for our website clusters. In the php configuration, session handler can be overridden using the following way.

session.save_handler = memcache
session.save_path = 'tcp://'

And don’t forget to restart apache backends. how do we make memcache listen on a specific ip address?
In /etc/sysconfig/memcached


PHP will now know not use the default files handler to save session files in /var/lib/php/session/ php will use memcache running at instead. But other people can access our memcached servers? alter or damage the contents. you might ask.

That is easy. we can use iptables to restrict source ip address which is allowed to access our memcached servers.
In Memcached server:

iptables -N MEMC
iptables -A INPUT -p tcp -m tcp --dport 11211 -j MEMC

iptables -A MEMC -s -j RETURN
iptables -A MEMC -s -j RETURN
iptables -A MEMC -s -j RETURN
iptables -A MEMC -s -j RETURN
iptables -A MEMC -s -j RETURN
iptables -A MEMC -j REJECT --reject-with icmp-host-prohibited

Now we have a session storage that can be used from any backend servers.


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>




This site uses Akismet to reduce spam. Learn how your comment data is processed.