rss

Super Charge your Rails App with Rack Cache and Memcache

Slow is sweeping the nation: slow food, slow living, and slow reading. Unfortunately your app called, it said it wants to be fast. Web apps that respond quickly are more enjoyable to work with and Google even gives them a small SEO bump. Recently basecamp next got quite a bit of customer love based on how quickly it responds. The fact of the matter is if it’s on the web, fast matters.

This is based on an article I wrote for the Heroku Dev Center Using Rack::Cache with Memcached for Static Asset Caching in Rails 3.1+. If you have any questions ping me @schneems.

One of the quickest ways we can speed up your whole application is to add on HTTP caching. Not only does this mean we return static files quickly, we also reduce the overall load of your application. The easy answer to this hard problem is to configure your application to use Rack::Cache with Memcache.

Performance Testing

I did some load testing of the example app with the trial version of the BlitzIO addon. BlitzIO will hit whatever url you specify with as many simulated users as you want and graph the result for you. This is a run from 1 to 250 concurrent users over the course of 60 seconds with four dynos. Compare the default production settings to using Memcache with Rack::Cache.

Rails Default Settings

Rails Default Settings

(Left is response time [peaks around 500ms] right is number of concurrent users represented by straight line, bottom is time of test )

Memcache & Rack Cache

Memcache Rack::Cache

(Left is response time [peaks around 100ms] right is number of concurrent users represented by straight line, bottom is time of test )

Here the Memcache & Rack::Cache combo smokes the default rails settings. If you want to run your own tests, you should know that each time you run BlitzIO, your performance graph will be different. I recommend running a few tests to make sure you’re not seeing a fluke. I also highly recommend doing any type of load testing on a staging server instead of production, or it could take down your site and your users wouldn’t be too happy.

Settings

So how can you, the speedfreak you are, get these types of results in your app? Long story short, you want to add this to your config/production.rb file:

config.action_dispatch.rack_cache = {
                        :metastore    => Dalli::Client.new,
                        :entitystore  => 'file:tmp/cache/rack/body',
                        :allow_reload => false }
config.static_cache_control = "public, max-age=2592000"

For more details on how to implement add this to your Rails app and why we chose these settings, please read the devcenter article or browse source on my demo app. Good luck, and enjoy the speed!