Faster Webapps with Memcached

This is an article on Faster Webapps with Memcached in Engineering Concepts.

Memcached is a free & open-source, robust, fast & distributed memory object caching system. Memcached was originally developed by Brad Fitzpatrick for LiveJournal in 2003. Since then it has gone a long way and today top websites like Youtube, Facebook & Twitter use memcached.

Memcached works on a client-server model, where the memcached daemon runs on it's default port 11211. Memcached if generally used to speed up dynamic websites by caching their content in RAM for fast retrival for the subsequent requests, thereby avoiding database or API calls. Each memcached object is identified by a key for easy fetching. An expiry time needs to be provided with each object cached, after which the object is discarded. Memcached discard object using the LRU (Least Recently Used) logic when no more space is left to accommodate new objects. Developers should always remember that Memcached should only be used for caching and not persistent storage, and code should be written to handle inavailabity of a key in memcached.

Many more projects have evolved out the memcached project, like MemcacheDB which stores data persistently, also MemcacheQ is a MemcacheDB variant that provides a simple message queue service.

Installing

Dynamic Web Objects Caching

Say you want to display the name & email of the user after they login, but for displaying that in every page you'll need to query the database, here memcached helps you by caching the info and you may check memcached for the key, if not found fetch the data from database use it & add to memcached.

If can be argued that the same can be done using storing use CGI or PHP session, but session stores in files & IO latency will be higher than memcached, also memcached enables you to store data distributed in multiple servers or remote server, whereas session data in generally stored locally. Read the next section for using memcached for storing session data.

Other Uses

Apart from the above mentioned, most popular usage, memcached can also be used by stand-alone applications to speed up their flow. Another interesting use for CGI session data storage, if you have multiple application servers then session using conventional file storage method will not work as the requests are balanced between the multiple application servers. One such example is the Perl module CGI::Session:river::memcached - CGI::Session driver.