What is Redis?

Redis is a kind of in-memory database that has different kinds of data structures you can use.

Like:

  • Key / value storage
  • Lists
  • Sets

It has nothing to do with your typical SQL database, like Postgres.

Uses for Redis include:

  • Caching
  • Leaderboards
  • Counting visitors
  • Fast autocomplete suggestions
  • Keeping track of active user sessions
  • Work & message queues

Let’s have a look at how you can use Redis in your Ruby applications!

Installing Redis Locally

First:

You need to install the Redis server.

Just like you would install any other database.

If you’re running Ubuntu, you can use apt install redis-server, on Mac you can use brew install redis & on Windows 10 you’ll need the “Windows Subsystem for Linux” (click for instructions).

Once the server is up & running you’ll be able to use redis-cli to connect to the server.

Note: You may have to run redis-server on another terminal to start the server before you can connect to it.

Now you’re ready to start using Redis!

Using Redis Gems

You can interact with Redis directly using redis-cli, but if you want to work with Redis from Ruby you should use a gem.

There are a few gems available:

  • oxblood
  • redic
  • redis-rb

But only one is officially recommended by the Redis developers, redis-rb.

Install it:

gem install redis

With the gem installed, you can connect to your Redis server & start working with it.

Let’s start by adding one key, a, with a value of 1.

Here’s the code:

require 'redis'

redis = Redis.new(host: "localhost")

redis.set("a", 1)
# "OK"

redis.get("a")
# "1"

This gem does a good job at mapping Ruby methods to Redis commands, so if you want to know what commands are available you can check the Redis documentation, or you can check the gem documentation.

Working With The Documentation

You can type the name of a specific command, or search by data structure.

Click on “Filter by group” & choose “Strings”, then pick one of the commands to test it out.

For example, you can use the incr command:

redis.incr("a")
# "2"

Or you can set an auto-expiring key with setex:

redis.setex("bacon", 10, 100)

Where the 2nd argument is seconds before this key will expire, and the last argument is the value for this key.

Example:

redis.get("bacon")
# "100"

After 10 seconds…

redis.get("bacon")
# nil

Have fun exploring & trying out other commands!

How to Use Sorted Sets in Redis

Redis is not limited to simple key/value storage.

It offers some powerful data structures.

Like the sorted set.

This allows you to create a list of unique items that are sorted by a given value. The value is called a “score” in the Redis documentation.

You can query to get the top N items in this set.

So this is perfect for a leaderboard!

Example:

redis.zadd("popular_fruit", 10, "apple")
# true
redis.zadd("popular_fruit", 20, "banana")
# true
redis.zadd("popular_fruit", 30, "orange")
# true

Now that we have our set, we can query for the top item:

r.zrevrange("popular_fruit", 0, 0)
# ["orange"]

This command is saying:

“Starting from the highest rank (0), give me the top item.”

If you want everything, in order:

r.zrevrange("popular_fruit", 0, -1)
# ["orange", "banana", "apple"]

Notice the “rev” part in “zrevrange”, that means reverse & it will give you the items in descending order.

If you use “zrange” you’ll get the items in ascending order.

Sorted sets go beyond leaderboards!

Another thing you can do is build a fast autocomplete engine with the ZRANGEBYLEX command.

Please read the documentation for more set operations.

Understanding Keys, Values & Namespacing

There are no columns, there are no tables, everything is one plain namespace.

How can you organize your data then?

You can use the key name itself.

One common convention is to use a colon (:) to separate the generic name & the specific part of that name.

Here’s an example:

redis.set("fruit:1", "apple")
# OK
redis.set("fruit:2", "banana")
# OK

Nothing special about this convention, for Redis (the software) a key with a colon is no different than a key without it, but for you (a friendly Ruby developer) it helps you organize your data.

Data Persistence in Redis

By default Redis doesn’t save every single operation you make like a regular database.

It only saves data to disk when you stop the server.

Or under these conditions:

  • after 15 min, if 1 or more keys changed
  • after 5 min, if 10 or more keys changed
  • after 1 min, if 10,000 or more keys changed

This creates a dump.rdb file on the current directory.

If you’d like Redis persistence to behave more like a SQL database, you can enable the “Append Only Mode”, which will save changes after every second.

Enable this mode by adding (or uncommenting) this line on the redis configuration:

appendonly yes

Using Redis as a Rails Cache

Since Rails 5.2 you can use Redis as your cache store.

You only need the redis gem & server.

To enable this:

# config/environments/production.rb

Rails.application.configure do
  config.cache_store = :redis_cache_store, { url: "redis://localhost:6379/0" }
end

Then Rails will use Redis for all its caching needs.

You can also store something in the cache:

Rails.cache.write("a", 1)
# "OK"

Rails.cache.read("a")
# 1

Rails stores values that look like this:

"\u0004\bo: ActiveSupport::Cache::Entry\t:\v@valuei\u0006:\r@version0:\u0010@created_atf\u00171555005228.7954454:\u0010@expires_in0"

This means that you can store any serializable Ruby object, like results of an ActiveRecord query.

Redis F.A.Q

“Can I list all the keys in my Redis server?”

Yes, using the keys or scan commands, but it’s not recommended because it’s very slow, specially as your database grows.

“When should I use Redis?”

Only when it makes sense for your use case. That means that you can take advantage of Redis data structures to make your code easier to reason about.

You don’t want to use Redis just because it’s cool or popular.

Use it when it solves a problem better than other solutions.

“How can I make Redis faster?”

Install the hiredis gem on top of redis-rb for maximum performance.

Summary

You have learned about Redis, a fast in-memory database that can be very helpful in the right situations, like caching, counting & queues.

If you found this article interesting please share it so more people can enjoy it.

Thanks for reading!