Sebastian Borrazas

I'm a full stack engineer from Montevideo. Love functional programming, the web and Erlang.

Ruby on Redis

Ever since I found out about the no-sql databases and since they became very popular lately, I wanted to write a blog post about my favourite one: Redis.

What I love so much about it is its simple API. In my honest opinion, one of the very best API's that I've found so far.

Also, since it's a lightweight and fast key-value store, it's specially useful for speeding up slow processes on your system. If things go slow, you should always consider using Redis, if it applies, it will speed things up.

The Ruby gem redis is as easy to use as redis API. Here's a quick look of it's usage on Rails. Where there's an AR Ranking model, which stores in a sorted set a list of albums to easily get the top [n] albums.

  # Setup the connection to the redis server
  $redis = 'localhost', port: 6379)
  class AlbumRanking < ActiveRecord::Base

    def top_albums(n)
      $redis.zrevrange(albums_key, 0, n - 1)

    def albums=(albums)
      $redis.multi do
        albums.each {|a| add_album(a) }

    def add_album(album)
      $redis.zadd(albums_key, album.downloads_number,

    def remove_album(album)

    def remove_all_albums

    def albums_key

Besides keeping track of sorted elements in a fast way, there are also many other useful ways in which redis could be used. Here's a list of them with a few interesting related resources:

  • Caching resources (in XML or JSON), LRU caching.
  • Having data which automatically expires. Another excellent feature needed for LRU caching.
  • Queues. Highly used by the resque gem
  • Keeping highly variable counters (page views, thumbs up, etc). Here's a Flask snippet.
  • Working with large sets of data (where you don't want repeated elements).