I have just started using caching in a production application to speed things up. I've read the primary Rails guide, various blogs, the source itself, etc. But my head is still not clear on one simple thing when it comes to fragment caching:
When you destroy the cache after updating the object, are you only updating the single object, or the class? I think just the single object.
Here's an example:
<% #jobs.each do |job| %>
<% cache("jobs_index_table_environment_#{session[:merchant_id]}_job_#{job}") do %>
stuff
<% end %>
<% end %>
I use the code above in my jobs index page. Each row is rendered with some information the user wants, some CSS, clickable to view the individual job, etc.
I wrote this in my Job class (model)
after_save do
Rails.cache.delete("jobs_index_table_environment_#{merchant_id}_job_#{self}")
end
after_destroy do
Rails.cache.delete("jobs_index_table_environment_#{merchant_id}_job_#{self}")
end
I want the individual job objects destroyed from the cache if they are updated or destroyed, and of course newly created jobs get their own cache key the first time they pop on the page.
I don't do the Russian doll thing with #jobs because this is my "god" object and is changing all the time. The cache would almost never be helpful as the collection probably morphs by the minute.
Is my understanding correct that in the above view, if I rendered, say, 25 jobs to the first page, I would get 25 objects in my cache with the cache key, and then if I only change the first, it's cached value would be destroyed and the next time the jobs page loads, it would be re-cached while the other 24 would just be pulled from the cache?
I'm a novice to fragment caching as well, and I just encountered a very similar use-case so I feel my (limited) knowledge is fresh enough to be of help.
Trosborn is correct, your terminal will highlight when you READ and when you WRITE, which shows you how many "hits" you got on your cache. It should only WRITE when you've changed an object. And based on what I see above, your delete is only deleting individual records.
However, I think there is a potentially simpler way to accomplish this, which is passing the ActiveRecord object to the cache, such as:
<% #jobs.each do |job| %>
<% cache(job) do %>
stuff
<% end %>
<% end %>
Read this post from DHH on how this works. In short, when an AR object is passed to cache, the key is generated not just on the model name, but also on the id and the updated_at fields.
Obsolete fragments eventually get pushed out of the cache when memory runs out, so you don't need to worry about deleting old cache objects.
Related
I have a model "Wrapper", which has_many of another model "Category", which in turn has_many of another model, "Thing".
"Thing" has the integer attributes :count and :number. It also has an instance method defined as such in models/thing.rb:
def ratio
(self.count + self.number).to_f / Thing.all.count.to_f
end
"Category", then, has this instance method, defined in models/category.rb:
def thing_ratios
self.things.sum(&:ratio.to_f)
end
Finally, my wrapper.html.erb view shows Categories, listed in order of thing_ratios:
<%= #wrapper.categories.all.order(&:thing_ratios).each do |category| %>
...
My question is this: every time someone reloads the page wrapper.html.erb, would every single relavant calculation have to be recalculated, all the way down to self.count for every Thing associated with every Category on the page?
In addition to the resources that #Kelseydh provided, you can also consider memoization for when you hit the same function multiple times as part of the same request. However, it will not retain its value after the request is processed.
Yes it will be recalculated every time. If this is an expensive operation you should add a counter_cache (guide: http://railscasts.com/episodes/23-counter-cache-column) for the count and look into caching the query result using a service like memcache.
Many caching strategies exist, but for the database/Rails app itself Russian doll caching is considered the most flexible approach. If your data doesn't update often (meaning you don't need to worry about cache expiration often) you may be able to get way with page caching -- if so, count yourself lucky.
Some resources to get you started:
DHH on Russian Doll Caching: https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works).
Railscast on cache keys: http://railscasts.com/episodes/387-cache-digests
Advanced caching guide: http://hawkins.io/2012/07/advanced_caching_revised/
Not free, but I found this series was what really let me understand various forms of caching correctly:
http://www.pluralsight.com/courses/rails-4-1-performance-fundamentals
I have a rails 4.1 app, that on a particular page retrieves a list of orders and lists them out in a table. It's important to note that the list is different depending on the logged in user.
To improve performance of this, I am looking to cache the partials for each order row. I am considering to do it like this:
_order_list.html.erb
<% cache(#orders) do %>
<%= render #orders %>
<% end %>
_order.html.erb
<% cache(order) do %>
...view code for order here
<% end %>
However, I'm unsure about the caching of the collection (#orders). Will all users then be served the same set of cached #orders (which is not desired)?
In other words, how can I ensure to cache the entire collection of #orders for each user individually?
Will all users then be served the same set of cached #orders (which is
not desired)?
Actually cache_digests does not cache #orders themselves. It caches html part of the page for a particular given object or set of objects (e.g. #orders). Each time a user asks for a webpage, #orders variable is going to be set in controller action and its digest is compared to the cached digest.
So, assuming we retrieve #orders like this:
def index
#orders = Order.where(:id => [1,20,34]).all
end
What we gonna get is cached view with a stamp like that:
views/orders/1-20131202075718784548000/orders/20-20131220073309890261000/orders/34-20131223112753448151000/6da080fdcd3e2af29fab811488a953d0
Note that ids of retrieved orders are mentioned in that stamp, so each user with his/her own unique set of orders should obtain his/her own individual cached view.
But here comes some great downsides of your approach:
Page caches are always stored on disk. That means that you can't have page stamp with any desired length. As soon as you retrieve a solid bunch of orders in a time, you exceed your OS's limit for filenames (e.g. it's 255 bytes for linux) and end up with runtime error.
Orders are dynamic content. As soon as at least one of them updates, your cache becomes invalid. Cache generation and saving it to disk is a pretty consuming operation, so it would be better to cache each order individually. In this case you will have to re-generate cache for a single order instead of re-generating the whole massive collection's cache.
Just doing some research on the best way to cache a paginated collection of items. Currently using jbuilder to output JSON and have been playing with various cache_key options.
The best example I've seen is by using the latest record's updated_at plus the amount of items in the collection.
def cache_key
pluck("COUNT(*)", "MAX(updated_at)").flatten.map(&:to_i).join("-")
end
defined here: https://gist.github.com/aaronjensen/6062912
However this won't work for paginated items, where I always have 10 items in my collection.
Are there any workarounds for this?
With a paginated collection, you're just getting an array. Any attempt to monkey patch Array to include a cache key would be a bit convoluted. Your best bet it just to use the cache method to generate a key on a collection-to-collection basis.
You can pass plenty of things to the cache method to generate a key. If you always have 10 items per page, I don't think the count is very valuable. However, the page number, and the last updated item would be.
cache ["v1/items_list/page-#{params[:page]}", #items.maximum('updated_at')] do
would generate a cache key like
v1/items_list/page-3/20140124164356774568000
With russian doll caching you should also cache each item in the list
# index.html.erb
<%= cache ["v1/items_list/page-#{params[:page]}", #items.maximum('updated_at')] do %>
<!-- v1/items_list/page-3/20140124164356774568000 -->
<%= render #items %>
<% end %>
# _item.html.erb
<%= cache ['v1', item] do %>
<!-- v1/items/15-20140124164356774568000 -->
<!-- render item -->
<% end %>
Caching pagination collections is tricky. The usual trick of using the collection count and max updated_at does mostly not apply!
As you said, the collection count is a given so kind of useless, unless you allow dynamic per_page values.
The latest updated_at is totally dependent on the sorting of your collection.
Imagine than a new record is added and ends up in page one. This means that one record, previously page 1, now enters page 2. One previous page 2 record now becomes page 3. If the new page 2 record is not updated more recently than the previous max, the cache key stays the same but the collection is not! The same happens when a record is deleted.
Only if you can guarantee that new records always end up on the last page and no records will ever be deleted, using the max updated_at is a solid way to go.
As a solution, you could include the total record count and the total max updated_at in the cache key, in addition to page number and the per page value. This will require extra queries, but can be worth it, depending on your database configuration and record count.
Another solution is using a key that takes into account some reduced form of the actual collection content. For example, also taking into account all record id's.
If you are using postgres as a database, this gem might help you, though I've never used it myself.
https://github.com/cmer/scope_cache_key
And the rails 4 fork:
https://github.com/joshblour/scope_cache_key
I have an E-Commerce Rails Application where we need to output Orders placed by Customers on a page within last one year for reporting reasons. Now, the data set is quite large and displaying these Orders on a single page takes quite a bit of SQL processing. This task initially was very slow and hence I moved all the required order details to a Redis Server and fetching of data has become really fast now but we are still not quite there.
Here's what we have:
Rendered **path**/sales_orders.html.haml within layouts/admin (39421.1ms)
Completed 200 OK in 44925ms (Views: 39406.8ms | ActiveRecord: 417.2ms)
The application is hosted on Heroku and if a request takes more than 30s it is killed. As you can see we are well above that limit. Most of the time is lost in rendering the view.
The page contains a date filter where the user gets to choose what Date Range to select the Orders from. So, caching is not the ideal solution since Date Ranges might change every time.
Any ideas how this can be done?
The Redis keys are of the format (The following is a Redis Hash):
orders:2012-01-01:123
orders:yyyy-mm-dd:$order-id
User simply provides a Date range and I get all the keys within that date range under the orders namespace.
Here's how I would get the Customer Name for instance from the Redis order key:
= REDIS.hget(order_key, "customer_name")
Consider building the report with a periodic task using the Heroku Scheduler addon.
As long as last-minute orders are not required to be included in the report, you can build your reports nightly and have them available for immediate download to read with your morning coffee, or even have them mailed to you (or whoever needs to read them.)
If you need interactive selection of periods for reports, you will need to queue the requests up and build the reports using background jobs.
Almost all your time is spent in rendering views. That probably means you have a lot of partials or other complex view logic. Some of your options are:
Paginate your output, but offer a PDF or CSV for unpaginated output.
Simplify your view logic...a lot.
Try a helper like cycle instead of rendering complex tables or nested partials.
Move your rendering into the client with JSON and JavaScript.
That's about it, really. If one or more of those don't get you where you need to go, it may be time to revisit your requirements.
I suggest you use fragment caching. Reading a fragment is very fast (~0.5 ms) and in my experience you'll see a huge speedup gain by not re-rendering your partials again and again. It's also a fairly cheap solution as Rails takes care of invalidating the fragments (if you use the model as part of the cache key) and it requires minimal changes in your template. I.e. the solution could be as simple as:
<% #orders.each do |order| %>
<% cache ["v1", order] do %>
<%= render order %>
<% end %>
<% end %>
I've taken the quote below, which I can see some sense in:
"Cached pages and fragments usually depend on model states. The cache doesn't care about which actions create, change or destroy the relevant model(s). So using a normal observer seems to be the best choice to me for expiring caches."
For example. I've got a resque worker that updates a model. I need a fragment cache to expire when a model is updated / created. This can't be done with a sweeper.
However, using an observer will mean I would need something like, either in the model or in the Resque job:
ActionController::Base.new.expire_fragment('foobar')
The model itself should not know about caching. Which will also break MVC principles that will lead to ugly ugly results down the road.
Use an ActiveRecord::Observer to watch for model changes. It can expire the cache.
You can auto-expire the cache by passing the model as an argument in your view template:
<% cache #model do %>
# your code here
<% end %>
What's happening behind the scenes is a cache named [model]/[id]-[updated_at] is created. Models have a method cache_key, which returns a string containing the model id and updated_at timestamp. When a model changes, the fragment's updated_at timestamp won't match and the cache will re-generate.
This is a much nicer approach and you don't have to worry about background workers or expiring the cache in your controllers/observers.
Ryan Bates also has a paid Railscast on the topic: Fragment Caching
A good and simple solution would be not to expire but to cache it with a key that will be different if the content is different. Here is an example
<% cache "post-#{#post.id}", #post.updated_at.to_i do %>
When that post gets updated or deleted and you fetch it again, it will miss the cache since the hash is different, so it will kind of expire and cache the new value. I think you can have some problems by doing this, for example if you are using the Rails default cache wich creates html files as cache, so you would end up with a lot of files in your public dir after some time, so you better set your application to use something like memcached, wich manages memory deleting old cached records/pages/parcials if needed to cache others or something like that.
I'd recommend reviewing this section on sweepers in the Rails Guide - Caching with Rails: An overview
http://guides.rubyonrails.org/caching_with_rails.html#sweepers
It looks like this can be done without specifically creating lots of cache expiration observers.