Sunday, January 31, 2016

PHP Sessions in AWS

Php sessions helps creating persistence for the php based applications.

The Elastic load balancer follows the Round robin algorithm to deliver the traffic to the backend servers. If a request asking for the authentication is served from a server it generates a token which is used to check the authenticated users. The problem comes when the request has been authenticated by a server reaches to other server due to ELB sending next request to another backend server but since it does not have that session id so it won't be able to authenticate in that case.

To Overcome this problem in AWS, you can use the Session Stickiness on the ELB. The ELB would generate a token and send it to client in the form of cookie. In this case ELB would be able to determine which server authenticated and would create a persistence between the server and the client request so that everytime the request comes from that client is delivered from the same server as defined in the timeout value. For e.g if you set up time out to 1800 seconds or 30minutes , ELB would continuously route the authenticated traffic of a client to that server only instead of the round robin request.

But this can create a problem in the high traffic environment because chances are server would eventually be loaded and can cause increase in latency due to high number of request and in a way fails the objective of the elastic load balancer since request are served from that instance only.

To overcome this problem you should use the server sessions instead of the ELB and store it in the database at backend with a memcache(elasticache) in front of the database. So that everytime the request comes it gets authenticated from the elasticache in case its not able to find the session in the elasticache it will search in the database and gets authenticated. Since the session is now isolated from the server so you can send request to any webserver behind your load balancer.

To configure php to use memcache, do the following:
Install and setup pecl memcache (pecl install pecl/memcache)
Setup a memcached instance for
Edit php.ini to use memcache (extension = memcache.so)
session.save_handler = memcache
session.save_path = "tcp://"


Post a Comment