What fix should you pick for your “latest-comment” n+1 queries problem?
One example of this problem is trying to get the latest comment on a list of posts, but there are others, like the last review in a list of products, or the cheapest price, or the latest payment for each costumer, etc…
I have already shared some fixes to help you solve the problem. and some benchmarks for this fixes….
This is the code that I use to run those benchmarks. You can use it to play with the code and seed values, to make it more specific to your current problem.
The benchmark will include the memory and the “iterations per second” benchmarks.
With this “reports"…
sorted_comments
- Default order for the "has many” associationlatest_comment
- A “has one” association for the latest commentfeed looping
- Looping through the latest comment for each postcached feed
- A version of the looping where we cache feed in memoryrussian_doll
- Russian doll-caching (with a simpler cache mechanism)cached_comment
- Caching the latest comment in a columnYou can see the code on github at bhserna/latest_comment_n-1_fixes_benchmark
Making things work isn't enough for you any more? Now you need to consider performance and scalability?
... But you normally have troubles fixing n+1 queries and trying to find why active record is ignoring your "includes"?
Are you are worried because you feel unqualified to tackle tasks with complex data models?
Sign up to learn how to fix n+1 queries on Rails