Are you eager to elevate your security skills and safeguard your applications
against cyber threats? I created a Rails Security course is designed
specifically for developers like you who aim to build robust, secure Rails
applications!
Buy my course: Security for Rails Developers.
I've built a Kanban board as a side project and I want to share how much performance boost I was able to give it by implementing a Russian Doll Caching.Buy my course: Security for Rails Developers.
The app itself is a typical kanban board where you can setup different stages for the tasks and they are in the column of the appropriate stage. I have a project where I have 4 stages: To-do, In progress, Waiting for review, Done. On this board I have 138 tasks in the moment. According to Rack Metrics this page takes between 1485 and 1678 ms to get ready on the server side. This is way too slow in my opinion so I will dig in a bit more. I randomly picked one of the request to this route and I saw there the following:
Duration: 1598.14ms
View runtime: 1485.152174ms
DB runtime: 78.776503ms
Render calls: 140
First, I need to make sure caching is enabled and set to `mem_cache_store` by putting this line into config/production.rb:
config.action_controller.perform_caching = true
config.cache_store = :mem_cache_store
<% status.tasks.each do |task| %>
<%= render task %>
<% end %>
<% status.tasks.each do |task| %>
<% cache(task) do %>
<%= render task %>
<% end %>
<% end %>
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true, touch: true
end
I already made my app perform better but there is one more thing I can do to make it even faster. I could cache the whole view in a fragment and bust the cache when any of the tasks has changed. To make this work I created a helper method to generate a cache_key based on the number of tasks and the updated task:
module ProjectsHelper
def cache_key_for_tasks
count = Task.count
max_updated_at = Task.maximum(:updated_at).try(:utc).try(:to_s, :number)
"tasks/all-#{count}-#{max_updated_at}"
end
end
<% cache(cache_key_for_tasks) do %>
...
# rest of the file
<% end %>
As you see with clever caching your Rails app can be a lot faster and use less resources.
I hope you enjoyed the article. UPDATE: A second part of this acrticle available at: https://greg.molnar.io/blog/rails-caching-again
Or follow me on Twitter
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.
It is free to use at the moment, and I am grateful for any feedback about it.If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!