Blog

Search This Blog

Loading...

Friday, September 7, 2012

Guest Post: Using IronCache as a Persistent Key Value Store for Real-time Chat

While IronCache is a great option for caching, it can also be used to persist data more permanently. There are dozens of great uses for a persistent key/value store, however, we’ll be building a simple chat app with Sinatra using IronCache as our datastore.

This is a guest post by JP Silvashy, CTO of Motionloft. You can find him on Twitter or his blog.

First let’s talk about a traditional cache. Take Memcached for example, it’s an in memory, non-durable, key/value store. It’s great! It’s probably the most popular object caching system there is. Until now, Memcached has always been my go-to solution.

Initially I built my mini-chat app Chattyloo using Postgres. Postgres is a big hammer,
for quite a simple problem. I know I needed persistence and durability, but I didn’t need such a serious Object Relationship Mapper. Moreover I didn’t want to manage a database, and that was the biggest factor to move over to IronCache.

Now there is one relationship here, but it’s actually an advantage in the case of a chat app. I needed to have one relationship, as chat rooms have chats. The way around this is to store all your chats as a single value for that room. I’ve created an ORM-like finder:

Now this is a sinatra app so settings is a hash, and ironcache is just an instance of IronCache::Client, see here: https://github.com/jpsilvashy/chattyloo/blob/master/app.rb#L22
When a new chat is POST’ed, we insert it like so:

The last(), trims off the messages so we don’t grow the size of the object too large, as they are all loaded at once.

Lastly, chats are retrieved like so:

This finder will return the channel with the messages. Now in your views you can iterate over the @messages for a given instance of Channel.

If you want to check out the final product, head over to chattyloo.com. The project is entirely open source on Github as well, check out Chattyloo on Github.