Fix n+1 queries on Rails

Learn different ways to solve n+1 queries beyond "includes", to be confident that you can handle tasks on complex data models and fix n+1 queries if they appear.

By Benito Serna

Making things work isn't enough for you any more?

Do you feel or maybe your boss have told you directly that now you need to consider performance and scalability?

Do you feel unqualified to tackle complex tasks?

Do you still have troubles fixing some n+1 queries?

Do you have problems trying to find why active record is ignoring your "includes"?

Maybe you know the basics...

Maybe you know how to fix some n+1 queries and use "preload" or "includes" here and there, but...

Do you worry when they ask you for more?

"Can you preload just an scope?"

"Can you change the implementation to preload via has many through?"

"Shoud we use a counter cache or just preload the counts?"

"Can you persist the calculation?... just please be aware of race conditions!"

"That fix to the n+1 queries, will hurt the performance... we need to try something else"

But, what if you could...

Ship code that fix user problems taking performance in consideration.

Be confident that you can handle tasks on complex data models.

Fix n+1 queries in the best way possible taking into account different angles.

Be one of those who help the team... next week

Learn how to fix n+1 queries on rails

Start your road to fix n+1 queries like a pro, with my ebook Fix n+1 queries on rails that will help you:

Table of contents

Here is the full table of contents of the book.

No more… “Why active record is ignoring my includes?”

  1. Explain what is an n+1 queries problem
  2. Identify when ActiveRecord will execute a query
  3. Solve the latest comment example
  4. Detect n+1 queries by watching the logs
  5. Tools to detect n+1 queries

Use preloading to avoid n+1 queries

  1. Joins does not preload
  2. Preload direct associations
  3. Preload nested associations
  4. Difference between preload, eager load or includes
  5. I prefer to use preload by default
  6. Preload scopes with scoped associations
  7. Simplify preloading with has many through associations
  8. Use a “preload object” for complex preloading
  9. Sometimes preloading can hurt the performance

Count without n+1 queries

  1. What is the difference between count, size and length
  2. Common mistakes with counts
  3. How to preload counts in a list

Save counts with counter caches

  1. Add counter cache to a new association
  2. Custom counter cache columns names
  3. Reset the counters for and existent association with just a few records
  4. Reset the counters with SQL, for associations with many records
  5. Using counter caches in your views

Caching custom counts and other computed values

  1. Fix n+1 queries by caching computed values
  2. Be aware that you can save incorrect values due to race conditions
  3. Tips to avoid race conditions saving computed values