Configuration Cache and Rails Session Store with Redis

The main purpose of caching is making the application work faster. But also this mechanism can help to more flexibly manage data, a good example is session management.

Redis cache store

Rails 5.2 introduced built-in Redis cache store, which allows you to store cache entries in Redis.

To use Redis as a Rails cache store, use a dedicated cache instance that’s set up as an LRU (Last Recently Used) cache instead of pointing the store at your existing Redis server, to make sure entries are dropped from the store when it reaches its maximum size.

The Redis store works with the Redis gem and hiredis, as well as providing support for a number of configuration options, like setting one or multiple remote servers.

Usage

To get started, add the redis gem to your Gemfile:

gem 'redis'

You can enable support for the faster hiredis connection library by additionally adding its ruby wrapper to your Gemfile:

gem 'hiredis'

Redis cache store will automatically require & use hiredis if available. No further configuration is needed.

Finally, add the configuration in the relevant config/environments/*.rb file:

config.cache_store = :redis_cache_store, { url: ENV['REDIS_URL'] }

REDIS_URL should be in the following format: redis://someserver.com:6379/1

Also caching should be performed for your environment:

config.action_controller.perform_caching = true

Session store

By default Rails is just using encrypted cookies on the client. This eliminates the single point of failure completely. This approach is the best in most cases.

The biggest advantage of Redis-backed session storage is that you have complete control over session data and never have to deal with stale cookies.

Using a backend for sessions will allow:

  • Share sessions between some applications.
  • Manage data before user comes next time to the site.

To store session data in the Redis usually use Hash or String data types.

If you already use Redis for cache just configure session store as a cache store.

config.session_store :cache_store, key: ENV['APP_SESSION_KEY']

Solution For Rails < 5.2

redis-rails provides a full set of stores (Cache, Session, HTTP Cache) for Rails.

Add the redis-rails to your Gemfile:

gem 'redis-rails'

Then set cache store config as :redis_store

config.cache_store = :redis_store, ENV['REDIS_URL']

And in the similar way we can configure session store:

config.session_store :redis_store, {
servers: [
{ host: ENV['REDIS_HOST'], port: 6379, db: 0 },
],
key: '_some_session_key'
}

Now when you add some data to session, for user will be added cookies with key for access data from Redis.

Inside storage it will key with type string and encrypted value:

Like what you read? Give Kirill Shevchenko a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.