This is largely a solved problem. New generations of programmers are simply rediscovering it.
The solution:
- be aware of it
- add DB query monitoring via your favorite APM tool
- review the APM tool regularly
- when you see an N+1 issue apply one of the normal solutions.
Follow this and N+1 query issues will disappear soon enough.
If you can’t do this it means you chose an immature framework or tech stack and my advice is to consider starting from scratch. Otherwise you will need to re-live the mistakes many people have already solved before you which feels adventurous but is painful and dumb.
I used to work somewhere that was really good at testing. We had `assert_no_n_plus_ones` in our rspec controller tests where we'd load a page of things with one thing on it and again with many things on it and assert that the number of DB queries was the same between both.
The thing is, as a developer I want every dumb mistake I could make appear as a squiggle in my editor. The hierarchy for programming error reporting is something like: lawsuit, social media post, ticket filed by support, bug found by QA, failing browser driver regression test, failing controller test, failing UI unit test, failing linter bug (elm-review is incredible for lint with auto fixes), failing compile which is caught by my editor. Only the last two might not require me to write any code, and only the last one might not require me to even write any configuration. If the error is caught anywhere past QA, that's good and cool, no disagreement there. But if it's found before I could ever have to assert it's not there, I feel so much more secure that I haven't introduced it.