Skip to content

Instantly share code, notes, and snippets.

@psahni
Last active October 3, 2016 23:11
Show Gist options
  • Save psahni/4fec15d812857a3c949e to your computer and use it in GitHub Desktop.
Save psahni/4fec15d812857a3c949e to your computer and use it in GitHub Desktop.
Comparison of memcache and redis [ Ruby on Rails ]

##Memcache

Memcache can be used for caching data in main memory using key value pair. So it reduces database load significantly. It is actually a storage engine used by Rack::Cache which is a middleware in Rails that provides HTTP caching. For example we can store a complex query result into a key

Rails.cache.fetch(key) do
  #......Processing
end

If the key is present, then the value is retrieved otherwise processing code is executed.

###Setup memcache

In Gemfile

gem 'rack-cache'
gem 'dalli'

in config/production.rb

config.cache_store = :dalli_store  # memcached

  client = Dalli::Client.new(<memcache_server_ip>)
  config.action_dispatch.rack_cache = {
      :metastore    => client,
      :entitystore  => client,
      :allow_reload => false
  }

Redis

Redis is a key value pair persistant system. It is much more than the simple caching mechanism of memcache. We can configure redis to behave like memcache. In general the performance and memory usage of Redis compared to memcached should be relatively similar. Redis has verity of data structures to use. It supports replication, sharding etc.

'redis-rails' gem provides a full set of stores (Cache, Session, HTTP Cache) for Ruby on Rails [https://github.com/redis-store/redis-rails]

###Setup

config/initializers/redis.rb

$redis = Redis.new(:host => 'localhost', :port => 6379)

config/environments/production.rb

config.cache_store = :redis_store

Gemfile

gem 'redis-rails'

What to use Memcache or Redis

If we have simple requirement of reading and writing to the cache, then memcache is a choice, otherwise we can use redis. We can also use both - memcache for caching and redis along with resque for background jobs/workers.

Resources:-

http://schneems.com/post/20472425017/super-charge-your-rails-app-with-rack-cache-and http://www.quora.com/Redis-vs-Memcached-which-one-should-I-use-for-a-web-based-application

Discussions from stackoverflow:-

http://stackoverflow.com/questions/4188620/redis-and-memcache-or-just-redis?rq=1 http://stackoverflow.com/questions/10558465/memcache-vs-redis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment