1. What is the N+1 query problem?
  2. How to avoid your code from incorporating such performance anti-patterns?
  3. Process of Solving N+1 Issue
  4. What caused the N+1 query problem?
  5. Conclusion

What is the N+1 query problem?

How to avoid your code from incorporating such performance anti-patterns?

Process of Solving N+1 Issue

  • ID
  • name
  • email
  • password
  • ID
  • plan
  • user_id
  • ID
  • amount
  • date
  • user_id
  • ID
  • parameter 1
  • parameter 2
  • user_id
  • etc.
  • calculated parameter 1
  • calculated parameter 2
  • We created a Result model.
  • Then we created a table to store the data for the aforementioned model.
  • We fetched all the data via eager loading.
  • We looped through the users’ data, but instead of storing the results in RAM, we saved them to the results table in the database.
  • Finally, we retrieved all the calculated data from the database in just one request.
  • We created a Result model.
  • Then created a table to store the data for the Result model.
  • We set up stored procedures and triggers to handle changes in the users, payments, subscriptions, or taxes table and recalculate the data stored in the Result table accordingly.
  • When the admin wants to retrieve Result data, there is no need for on-the-fly calculation since we already have the result. All that’s needed is to fetch the data from the results table and render it.

What caused the N+1 query problem?

Conclusion

Roman Bondarenko is the CEO of EVNE Developers. He is an expert in software development and technological entrepreneurship and has 10+years of experience in digital transformation consulting in Healthcare, FinTech, Supply Chain and Logistics.