Memcached-Based PHP Sessions


30 May 2013

If you have a website that gets millions of page requests per day each starting a session and you wish to get the last ounce of performance from your server and you’re still using file-based sessions then by all means give this a try. The more volume of dynamic content you’re serving, the more you’ll benefit in terms of load average and site-speed.

One of my website gets about 8 million page views per day almost all needing a session to be started. Using memcached-based sessions helped reduce the load at least 6-folds and sped-up the site considerably.

Since I came to know about it rather late in my career I say it’s one of least known but much simple and effective way to solve performance problems when you have lots of traffic. Remember high-traffic is a must to see any considerable effect.

Use the following code in the bootstrap script of your website:

ini_set('session.save_handler', 'memcache');
ini_set('session.save_path', "MEMCACHE_SOCKET_PATH");

You can also set the above variables in the php.ini file for activating it globally. You must have memcache and memcache PHP extension installed for this to work.

You’ll have to estimate the amount of memory sessions will require and set memcache with a higher value than that. You can check the /tmp directory for the session files and see how much memory is being taken by sess_ files. If you give less memory session data might clear automatically (FIFO by memcached) and users may get logged out etc. depending on what you’re using sessions for.

You can also use redis in place of memcached if you absolutely don’t want the session data to get cleared in any way (other than by the GC).

How does this work? Memory is SO MUCH faster than HDD.

75 people like this post.

Comment Form

About Me

Personal blog of a 24-year-old entrepreneur from Jamshedpur, India. He loves to discover new things and how stuff works.




img_0771 img_0803 img_2670 img_2924