IP Address Lookup Caching Using ElastiCache Memcached

In this tutorial, we will demonstrate how to cache an IP2Location query with the help of Amazon Web Service ElastiCache. ElastiCache has 2 engines available for caching. The one we will be using is the memcached engine. For this demonstration, we will be running our PHP code on an AWS EC2 instance as ElastiCache is meant to work with EC2.

Important Note

We will not cover the installation of PHP or MySQL. We will assume there exists a MySQL database that is loaded with IP2Location data and that our EC2 test machine has PHP installed with memcached support.

Creating the example code

Save the following code into a PHP file.

<?php
$config['dbHost'] = 'mydatabaseserver';
$config['dbUser'] = 'myuser';
$config['dbPass'] = 'mypassword';
$config['dbName'] = 'ip2location_database';
$config['cacheHost'] = 'mycacheserver';
$config['cachePort'] = 11211;

$m = new Memcached();
$m->addServer($config['cacheHost'], $config['cachePort']);

$IP = '8.8.8.8'; // test IP

if ($data = $m->get($IP)) {
	echo "Reading from cache.\n";
	var_dump($data);
}
else {
	if ($data = readDB($IP)) {
		echo "Reading from database.\n";
		var_dump($data);
		echo "Caching result.\n";
		$m->set($IP, $data);
	}
	else {
		echo "Error.\n";
	}
}

function readDB($myIP) {
	global $config;
	try {
		$pdo = new PDO('mysql:host=' . $config['dbHost'] . ';dbname=' . $config['dbName'] . ';charset=utf8', $config['dbUser'], $config['dbPass']);
		$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		
		$sql = 'select * from `ip2location_table` where inet_aton(:myIP) <= ip_to limit 1';
		$st = $pdo->prepare($sql);
		$st->bindParam(':myIP', $myIP, PDO::PARAM_STR);
		$st->execute();
		return $st->fetchAll();
	}
	catch(PDOException $e) {
		return false;
	}
}
?>

Testing the caching

Run the PHP code above to query IP2Location data for the 8.8.8.8 IP address.

Firstly, the code will query the cache and since this is the first time we are querying this IP address, it will not exists in the cache. We will get FALSE when we query the cache.

Then we proceed to query the MySQL database and we get our IP2Location result. We will store this result into our cache for future queries.

Now, run the PHP code again to query the same IP address. You'll notice that this time the cache is returning the IP2Location result that was previously stored.

The caching codes are relatively simple to implement and anyone who has a website with heavy traffic will benefit from using ElastiCache.

Since memcached is an in-memory cache, there is no disk I/O to slow things down. When you are dealing with thousands of queries per second, this will speed up your queries especially when you keep querying the same sets of IP addresses.

Bear in mind that memcached can store even complex objects like arrays and objects, which makes it a very versatile way to improve the responsiveness of your website as you no longer have to query a slow disk-based database for information.


Do you like this article? Share it with others by clicking the social media buttons below. We will write more articles related to this topic.