If you know me you know that I’m a huge proponent of Redis. I started using it in mid-2011 as the storage engine for a chat system I was building for SceneKids. Over the last year and a half or so I’ve utilized Redis more and more for many other sub-systems on the site. My initial draw to it were the various data types and the optional persistence. I’m going to discuss the different ways I’ve been able to successfully leverage Redis.
Probably the easiest way to implement Redis into your [PHP] stack is by using the Redis session handler. Unlike Memcached, you can enable persistence in Redis and provide a better experience for your users (reads: no more logging everything out of the site if you have to restart your box or the service itself).
The unfortunate side of things is that you will need to compile the PHP extension for Redis to enable the session handler. The advantage is having a native extension for Redis instead of using a [slower] PHP client like Rediska or Predis.
The PHP extension is available here and installation is pretty simple. Once downloaded and extracted, enter the directory and run:
Once installed, you will need to edit your
php.ini and add the line:
Then you can enable the session save handler in your
php.ini by changing the session save handler and path:
You can specify multiple servers if you’re running a cluster, just comma separate them. There are also some other options that can be specified with each host, just check the README. If I had to guess, there is probably a Ruby Gem out there to allow Rails sessions to be stored in Redis as well.
All subsequent code examples will be using the
I’ve made the mistake of putting a counter field on a database table in the past. It’s a fairly innocuous thing to do when the field isn’t being updated that often (like once a day or so). If it’s something that is being updated every few minutes or sooner you’re going to run into a lot of database writes and possibly more reads if you’re invalidating a caching layer on every write.
Redis (like Memcached) has a command to increment and decrement a value. The obvious benefit when using Redis is the persistence and the speed to read and write (especially in high volume write scenarios) over an RDBMS. The commands are as follows:
There is also a command
incrByFloat in case you want to increment by values with a decimal (e.g. 2.5). There is not a decrementing equivalent but you can increment by a negative value.
One of my favorite scenarios for using Redis is when creating a leaderboard / top scores list. The Redis sorted set data type is perfect for this scenario as it does all of the heavy lifting of sorting the data automatically. You can realistically get away with only four Redis commands to score the stores and recalling scores and ranks:
There’s not much to it and of course it’s fast and can be persistent. If you’re keeping track of something like the number of times a user’s profile has been viewed (in relation to other user’s profiles), you could use
zIncrBy to increment the score during each view of the profile.
Because of the awesome data types that Redis has, building queues is a very common use case. You could use the sorted set like we did above and set the score to the timestamp of the event or you could use the list type, which is ordered based on when and where you added the data. I generally use lists for the queues I’ve built.
When I originally built the dashboard on SceneKids I went with a basic scatter gather method to get the data to display for the user. As with most things, it was fine at the beginning but started to become problematic as the volume of the data increased and more touch points were added.
The original logic would grab the ID’s of all of a user’s friends when they would view the dashboard, then go out to each of the tables I wanted data from (status updates, images, journal entries and their respective comments). So upwards of 6 tables were being hit and subsequentially cached for 2 minutes. Far from a real time solution, and wasn’t going to scale much further as users on the site were starting to have upwards of 5,000 friends or more.
When rebuilding the dashboard I dropped the gathering and moved to a push queue where every update was pushed to a queue for each of your friends. Let’s say you have 10,000 friends and you posted a new status update. Every status update has a unique ID and I push a string
# is the unique ID) to the dashboard queue for each of your friends. Yes, there are instances where I’m writing to Redis 10,000 times but the time it takes is negligible.
Now instead of trying to find the data I want for the dashboard, I can use the queue to extract the unique ID’s for the data and perform my database calls to collect the data (assuming it’s not already in the cache). This allowed me to drop sorting from the database (after I merge the data into an array I sort it in PHP) and pull the data while using the primary key for the tables. We could still have the same number of queries as before but the queries being run are more efficient.
These are some examples of how I use Redis. There are still scenarios where I favor either MySQL or Memcached depending on what the data is and how I will need to interact with it. Redis’ speed and persistence make it a very viable RDBMS replacement in my eyes, assuming you have enough RAM to store your entire dataset.