Redis is one of the most interesting of the NOSQL solutions. It goes beyond a simple key-value store in that keys’ values can be simple strings, but can also be data structures. Redis currently supports lists, sets and sorted sets. This post provides an example of using Redis’ Set data type in a recent feature I implemented for Weplay, our social youth sports site.
The End Result
Weplay members were told us they wanted to be able to see which of their friends were online, so we decided to add the feature. Let’s look at how Redis was instrumental in this functionality.
Properties of a Set
First a quick overview of Redis’s “set” data structure. A set in Redis has the same properties as the abstract data structure of the same name:
* 0 to N elements
* No repeated members
In practice, this is nice because adding a value to a set does not require you to check if the value exists in the set first.
Redis Set Operations
You can see a full list of the set operations Redis supports. here are the ones were going to use:
The idea is to have one active set per minute. During each request that comes in from a logged-in user, we’ll add a user ID to the active set. When we want to know which user IDs are online, we can union the last 5 sets to get a collection of user IDs who have made a request in the last 5 minutes.
Now, if we have a set of the user’s friend’s IDs, we can intersect that with the online users and we’ve got our online friend IDs.
I love that the code is almost as succinct as the diagrams.
With this approach, you need to empty or delete the older sets before the next hour comes around. We use a cron job for that purpose. I’m not going to show that here, but feel free to get in touch if you have any questions about it.
Hope this gives you some ideas of the Redis’ elegant simplicity and power. This code simpler than it would be if we had used an RDBMS or memcached, or both.
If you’re new to Redis, I’d recommend following it’s creator and maintainer, Salvatore Sanfilippo (@antirez). He’s a very thoughtful and transparent open source leader and is rapidly and continually improving Redis.