{"id":246,"date":"2009-09-08T16:22:13","date_gmt":"2009-09-08T19:22:13","guid":{"rendered":"http:\/\/blog.plataformatec.com.br\/?p=246"},"modified":"2009-09-18T13:26:20","modified_gmt":"2009-09-18T16:26:20","slug":"how-to-avoid-dog-pile-effect-rails-app","status":"publish","type":"post","link":"https:\/\/blog.plataformatec.com.br\/2009\/09\/how-to-avoid-dog-pile-effect-rails-app\/","title":{"rendered":"How to avoid the dog-pile effect on your Rails app"},"content":{"rendered":"

Everyone already heard about scalability at least once. Everyone already heard about memcached<\/a> as well. What not everyone might heard is the dog-pile effect and how to avoid it. But before we start, let’s take a look on how to use Rails with memcached.<\/p>\n

Rails + Memcached = <3<\/h3>\n

First, if you never used memcached with rails or never read\/heard a lot about scalability, I recommend checking out Scaling Rails<\/a> episodes done by Gregg Pollack<\/a>, in special the episode<\/a> about memcached.<\/p>\n

Assuming that you have your memcached installed and want to use it on your application, you just need to add the following to your configuration files (for example production.rb):<\/p>\n

\r\nconfig.cache_store = :mem_cache_store\r\n<\/pre>\n

By default, Rails will search for a memcached process running on localhost:11211.<\/p>\n

But wait, why would I want to use memcached? Well, imagine that your application has a page where a slow query is executed against the database to generate a ranking of blog posts based on the author’s influence and this query takes on average 5 seconds. In this case, everytime an user access this page, the query will be executed and your application will end up having a very high response time.<\/p>\n

Since you don’t want the user to wait 5 seconds everytime he wants to see the ranking, what do you do? You store the query results inside memcached. Once your query result is cached, your app users do not have to wait for those damn 5 seconds anymore!<\/p>\n

What is the dog-pile effect?<\/h3>\n

Nice, we start to cache our query results, our application is responsive and we can finally sleep at night, right?<\/p>\n

That depends. Let’s suppose we are expiring the cache based on a time interval, for example 5 minutes. Let’s see how it will work in two scenarios:<\/p>\n

1 user accessing the page after the cache was expired:<\/b><\/p>\n

In this first case, when the user access the page after the cache was expired, the query will be executed again. After 5 seconds the user will be able to see the ranking, your server worked a little and your application is still working.<\/p>\n

N users accessing the page after the cache was expired:<\/b><\/p>\n

Imagine that in a certain hour, this page on your application receives 4 requests per second on average. In this case, between the first request and the query results being returned, 5 seconds will pass and something around 20 requests will hit your server. The problem is, all those 20 requests will miss the cache and your application will try to execute the query in all of them, consuming a lot of CPU and memory resources. This is the dog-pile effect.<\/p>\n

Depending on how many requests hit your server and the amount of resources needed to process the query, the dog-pile effect can bring your application down. Holy cow!<\/p>\n

Luckily, there are a few solutions to handle this effect. Let’s take a look at one of them.<\/p>\n

\"Dog

Dog pile effect working on your application!<\/p><\/div>\n

How to avoid the dog-pile effect?<\/h3>\n

The dog-pile effect is triggered because we allowed more than one request to execute the expensive query. So, what if we isolate this operation to just the first request and let the next requests use the old cache until the new one is available? Looks like a good idea, so let’s code it!<\/p>\n

Since Rails 2.1, we have an API to access the cache, which is defined by an abstract class called ActiveSupport::Cache::Store<\/a>. You can read more about it in this post<\/a> or in this excellent railscast episode<\/a>.<\/p>\n

The code below simply implements a new and smarter memcached store on top of the already existing MemCacheStore<\/a>:<\/p>\n

\r\nmodule ActiveSupport\r\n  module Cache\r\n    class SmartMemCacheStore < MemCacheStore\r\n\r\n      alias_method :orig_read, :read\r\n      alias_method :orig_write, :write\r\n\r\n      def read(key, options = nil)\r\n        lock_expires_in = options.delete(:lock_expires_in) if !options.nil?\r\n        lock_expires_in ||= 10\r\n\r\n        response = orig_read(key, options)\r\n        return nil if response.nil?\r\n\r\n        data, expires_at = response\r\n        if Time.now > expires_at && !exist?(\"lock_#{key}\")\r\n          orig_write(\"lock_#{key}\", true, :expires_in => lock_expires_in)\r\n          return nil\r\n        else\r\n          data\r\n        end\r\n      end\r\n\r\n      def write(key, value, options = nil)\r\n        expires_delta = options.delete[:expires_delta] if !options.nil?\r\n        expires_delta ||= 300\r\n\r\n        expires_at = Time.now + expires_delta\r\n        package = [value, expires_at]\r\n        orig_write(key, package, options)\r\n        delete(\"lock_#{key}\")\r\n      end\r\n    end\r\n  end\r\nend\r\n<\/pre>\n

The code above is mainly doing:<\/p>\n

    \n
  1. Suppose that your query is already cached;<\/li>\n
  2. In the first five minutes, all requests will hit the cache;<\/li>\n
  3. In the next minutes, the first request will notice that the cache is stale (line 17) and will create a lock so only it will calculate the new cache;<\/li>\n
  4. In the next 5 seconds, the new query is calculated and all requests, instead of missing the cache, will access the old cache and return it to the client (lines 17 and 21)k;<\/li>\n
  5. When the query result is returned, it will overwrite the old cache with the new value and remove the lock (lines 31 and 32);<\/li>\n
  6. From now on, all new requests in the next five minutes will access the fresh cache and return it (lines 17 and 21).<\/li>\n<\/ol>\n

    Fallbacks and a few things to keep in mind<\/h3>\n

    First, is not recommend to set the :expires_in value in your cache:<\/p>\n

    \r\nRails.cache.write('my_key', 'my_value', :expires_in => 300)\r\n<\/pre>\n

    With the solution proposed above, you just need to set :expires_delta. This is due to the fact that our application will now be responsible to expire the cache and not memcached.<\/p>\n

    \r\nRails.cache.write('my_key', 'my_value', :expires_delta => 300)\r\n<\/pre>\n

    However, there are a few cases where memcached can eventually expire the cache. When you initialize memcached, it allocates by default 64MB in memory. If eventually those 64MB are filled, what will memcached do when you try to save a new object? It uses the LRU algorithm<\/a> and deletes the less accessed object in memory.<\/p>\n

    In such cases, where memcached removes a cache on its own, the dog pile effect can appear again. Suppose that the ranking is not accessed for quite some time and the cached ranking is discarded due to LRU. If suddenly a lot of people access the page in the five initial seconds where the query is being calculated, requests will accumulate and once again the dog-pile effect can bring your application down.<\/p>\n

    It’s important to have this scenario in mind when you are sizing your memcached, mainly on how many memory will be allocated.<\/p>\n

    Now I can handle the dog-pile effect and sleep again!<\/h3>\n

    Summarizing, when your are using a cache strategy, you will probably need to expire your cache. In this process, the dog-pile effect can appear and haunt you down. Now you have one (more) tool to solve it.<\/p>\n

    You just need to add the SmartMemCacheStore code above to your application (for example in lib\/), set your production.rb (or any appropriated environment) to use the :smart_mem_cache_store. If you use Rails default API to access the cache (Rails.cache.read, Rails.cache.write) and designed well your memcached structure, you will be protected from the dog-pile effect.<\/p>\n

    \"A

    A real dog-pile! =p<\/p><\/div>\n","protected":false},"excerpt":{"rendered":"

    Everyone already heard about scalability at least once. Everyone already heard about memcached as well. What not everyone might heard is the dog-pile effect and how to avoid it. But before we start, let’s take a look on how to use Rails with memcached. Rails + Memcached = expires_at && !exist?(“lock_#{key}”) orig_write(“lock_#{key}”, true, :expires_in => … \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ngg_post_thumbnail":0,"footnotes":""},"categories":[1],"tags":[28,25,7,27],"aioseo_notices":[],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/246"}],"collection":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/comments?post=246"}],"version-history":[{"count":22,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/246\/revisions"}],"predecessor-version":[{"id":285,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/246\/revisions\/285"}],"wp:attachment":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/media?parent=246"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/categories?post=246"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/tags?post=246"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}