Faster Queries Using Memcached

Typically, MySQL can scale to very large workloads. It’s even used at companies such as Facebook for the majority of their data storage. However, although they’ve scaled their MySQL environment well and optimized the queries, they started hitting issues with scalability. Due to this issue in scaling well, they successfully utilized Memcached to speed up data access.

Memcached in an in-memory distributed key-value store. What this means is that you can store small pieces of data in memory (which makes it incredibly fast to get this data), and it automatically distributes across as many servers as you have in your cluster.

You don’t need a large workload like Facebook has to use Memcached though. Even small workloads can benefit from its use. For example, PHP sessions aren’t very durable, so it would be useful to store active login sessions on the server, and a session key in a browser cookie. This also provides flexibility in logins, which we will cover in another post. Memcached would work better than a MySQL table in this case, because on every page load you would want to verify the active session, but you wouldn’t want to overload your database with constant queries.

MySQL is then used as backup on-disk storage, and you maintain the incredible speed of accessing data that is held in memory.

Let’s get started.

Memcached stores data in a key-value store. This means each thing you’re storing has a key, and a value. The key, for example, could be “login-j49fjs0lwms” and the value could be a userID like “7”. Now every time you load a page, you take the visitor’s login cookie (login- j49fjs0lwms), and retrieve their userID, so you know which user to load content for.

In PHP, this could look something like this:

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

function login(){
  $randomKey = generateKey();
  $userID = getUserID();
  $m->set('login-'.$randomKey, $userID);
  setCookie("loginCookie", $randomKey);
}

function generateKey(){
  // some code to generate a random key
}

function getUserID(){
  // some code to check the login and get a user ID
}

function setCookie($cookieName){
  // some code for setting cookies
}

function checkLogin(){
  $userID = $m->get("login-".$_COOKIE['loginCookie']);
}

?>

Learn more about Memcached at Memcached.org