Today we are going to learn how to use the Memcache plugin on Heroku in a Sinatra app. We will be using a gem called ‘Dalli’. Memcache means ‘a general-purpose distributed memory caching system’ or in other words, something cool, fast and easy to use for speeding up your website. The way to do this is to cache certain parts of your application for a specific time period (ttl) so that users on your site would share the same data output and not need to trigger the data collection mechanism for each request.
The 5MB version is free and should be adequate enough for your average blog, brochure website. In a commercial website, don’t be surprised if the number is closer to 20GB.
Adding the Memcache plugin would add the necessary environment variables that ‘Dalli’ needs to use. So, lets go ahead and add ‘Dalli’ to our Gemfile….
and install it…
Next we need to set up ‘Dalli’ in our rack_app.rb
require 'sinatra' require 'erb' require 'dalli' set :cache, Dalli::Client.new set :enable_cache, true set :short_ttl, 400 set :long_ttl, 4600 get '/' do erb :index end
You can play around with the :short_ttl and :long_ttl times to find the best setting for your content, but it wouldn’t be frowned upon to cache certain things for hours or even days (ie. ‘Post of the week’ promotion on your homepage).
Next we simply need to store our data in ‘Dalli’ whenever we want to cache it, and remember to look for it before using our time consuming fetching mechanism. We will do this with a CacheKey.
get '/' do @todays_posts = get(:todays_posts) erb :index end def get(key, time_to_live=settings.long_ttl) if(!settings.enable_cache) return some_really_complicated_dataretrieval(key); end if(settings.cache.get(key) == nil) settings.cache.set(key, some_really_complicated_dataretrieval(key), ttl=time_to_live+rand(100)) end return settings.cache.get(key) end
Note that I added a rand(100) to the TTL. This is so that when the cache refreshes, it doesn’t refresh all the items with the same TTL at once. This would cause a small hiccup in performance at that time. Thats it! That should be all you need to use Memcache on Heroku using Sinatra.