You can use memcache on your Heroku dyno through addons such as Memcachier. If you're working in development mode, Memcachier provides up to 25mb for free. Here's how to get started.

This article assumes that you've already prepared your Rails app for Heroku deployment. If not, read this article first.


Step 1 - Configure Heroku

Change directory into your Heroku app.

cd ~/path/to/rails_app

Add Memcachier through the Heroku command line.

heroku addons:add memcachier

Open up the documentation.

heroku addons:docs memcachier

That's it! The following steps are pretty much straight from the instructions found in Getting started with Memcachier and Rails 4.


Step 2 - Configure Gemfile

Add this to your Gemfile.

gem 'dalli'

Run bundle install

bundle install

Step 3 - Configure Your Environment

When you add Memcachier to Heroku, it auto created a few Environmental Variables. To complete the setup, all you need to do is paste this into config/environments/production.rb

  # Memcachier / dalli configuration
  config.cache_store = :dalli_store,
    (ENV["MEMCACHIER_SERVERS"] || "").split(","),
    {:username => ENV["MEMCACHIER_USERNAME"],
      :password => ENV["MEMCACHIER_PASSWORD"],
      :failover => true,
      :socket_timeout => 1.5,
      :socket_failure_delay => 0.2,
      :down_retry_delay => 60
    }

Step 4 - Fragment Caching

There are three types of caching; Whole Site caching, per-view caching and fragment caching. Source

I use fragment caching the most on specific parts of my view such as tables,

- cache "keywords_index_table", skip_digest: true do

If you want your fragment to have an expiration, here's how.

- cache "keywords_show_id_#{@keyword.id}_page_#{params[:page]}", skip_digest: true, expires_in: 5.minutes do

If the cache within your view is making a request to a specific model, you'll need to add the cache to the Model too.

# Memcachier that clears a fragment
ActionController::Base.new.expire_fragment('keywords_index_table')