Join the discussion
Write your take first — we'll ask for email only when you're ready to publish.
- Hacker News
- Non-identity principle.
A=A
by hmnxr1e - Wasn't this 'solved' by Hibernate ages ago?by jbverschoor
- Heavy Hibernate user here, Hibernate does not make it impossible to write N+1 queries afaik - unless there are some tips we're missing in our team?
We just regularly check our slow queries dashboard, fix it (or well let an LLM work on it) and then move on.
by _1tan - 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.
by koliber - 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.
by 1-more - Compare with the prior art of N+1 queries of 2014:
https://github.com/facebook/Haxl/blob/main/example/sql/readm...
by mrkeen - Of course mainstream ORMs leave a lot of perf on the table. For example, I once patched the ORM in a struggling php web app that i had to help. I started as a logger profiler thingy but then had the crazy idea of being a trace optimiser. By recognising the call sites from previous visits I could spot the 1+N and select * etc and actually transcode that into better sql in the next run etc. Shockingly it made a massive difference and I was surprised that normal ORMs aren’t doing that kind of thing.by wood_spirit
- > trace optimizer/better sql in the next run
Ah wow! I admittedly already linked this PR in another reply, but I'm trying similar things here:
https://github.com/joist-orm/joist-orm/pull/1967
Neat to hear you had success with it before; did you have to handle "the optimization was inaccurate [a novel codepath asked for a column we didn't return], so fallback to `select *`"? And do that without failing the overall request?
This "fallback and implicit retry" is what I'm doing atm, and just assuming is the only way of handling the "novel codepath was hit this time" problem, but lmk if I'm missing something.
by stephen - I really believe that every engineer writing queries (even SQL) should read the FoundationDB data modeling guide [0]. It really gives an appreciation of what smart choice of primary key can do to query efficiency. With some de-normalization, joins aren’t even needed for performance.
Postgres has supported query pipelining for a long time. In my opinion, most queries should be written in such a way that sequential queries don’t have any data dependencies on the previous query at all. This speeds up applications by huge amounts.
by WilcoKruijer - lol I remember a senior dev absolutely shitting on me for suggesting de-normalization to improve a JOIN query that was absolutely way too slow (on a table that was reseeded on deploys at that). I left it at that but to this day I maintain that it was the right move.
- > [Datalog] is a subset of Prolog that lacks recursion
Datalog does allow for recursion — a common example is graph reachability:
reachable(a, b) :- edge(a, b). reachable(a, c) :- edge(a, b), reachable(b, c).
(Evan mentioned implementing kCFA, which would require recursion like this...)
'Base datalog' guarantees termination by requiring all input relations to be finite. Notably this means that it doesn't have numerical operations like addition or multiplication, since `plus(a, b)` or `times(a, b)` would be infinite relations.
More practical Datalog engines like Souffle (https://souffle-lang.github.io/) have numerical operations but don't guarantee termination.
Recursive queries are not needed by most applications, but maybe Acadia could allow them (compiling to recursive CTEs) by proving that recursion only goes through finite relations.
by vilterp - If you can do Peano numbers...
Guaranteed termination isn't really if you give me enough rope to implement the Ackermann function.
by cryptonector - Side note: I strongly prefer referring to this as the "1+N problem" as the author did here. I didn't understand what people were grousing about when they talked about "N+1".
N+1: You're already doing N queries. Is adding 1 more that big of a deal?
1+N: This should have been 1 query, but somehow you blew it up into that one plus N more.
I'd seen that query antipattern plenty of times and knew what it was bad, but didn't realize that's what people meant by "N+1", which I thought must mean something different.
by kstrauser - But addition is commutative! :)by mwigdahl
- Thank you. I turn grumpy when my colleagues keep calling it N+1. What even.by hnarayanan
- N+1 is at best two queries, right? I always interpreted it as:
optimized to:query 0 = list query 1_0 = getItem(0) ... guest 1_n = getItem(n)query 0 = list query 1 = getItems(0..n)by dfee - Algebraically, it is the number of queries: n+1. That's traditionally how you write such a number, not 1+n.
It's the number of queries not a sentence of "we did 1 query, then we had to do n queries."
by LanceH - You're not the only one. I never stopped to delve into what this N+1 problem was b/c I assumed it was never an issue for me. All these years and this is the 1st time I've finally understood what they were saying.
However, after going back and forth with LLM on it just now, I feel like "1+N" is just a coding mistake, not a perplexing multi-faceted, engineering problem to be solved. Experience or a slow application would teach you to find a better way to get that info and then you move on.
by libria - Nice, and I understand why using `getAuthorNames` solves the N+1 here.
But... isn't this solving the problem by removing most of what makes it an issue in the first place? I imagine most people use ORMs for the SQL <-> native class data sync capability. And this assumes one would run the Acadia query instead.
FWIW I'm not trying to be negative, it's just my general impression is that these N+1 usually occur because people _want_ direct object access and _want_ to write loops, and _want_ to access fields and have the underlying SQL be sorted by the ORM.
by quibono - Yes, this does essentially nothing to solve the 1+N query problem. If your solution was to to stuff everything into one query, this was already possible with SQL!by hobofan
- This is my experience too. The solution is to train people to stop wanting to solve data query problems in the application layer.by cnity
- As far as I understand Acadia gives you Acadia <-> Native class data sync, only just Haskell and Elm at the moment unfortunately.
I'd be willing to rewrite queries in some other language that transpiles to SQL if it allows me to do all the queries I want and gives me full compile time type support for db access in return.
The policies look interesting too by the way, but they don't solve a major IMO.
by lobofta - Afaict their solution is "here's a prolog-ish query DSL that safely translates FP-ish code to joins".
That seems fine, but imo 1+Ns usually happen when you interleave business logic with database loads--like you have business logic that "really wants to be in a loop" b/c it's "not easily expressed in SQL" logic.
So, the author's ~3 lines of "a loop with zero business logic" is not that convincing, and seems like a premature claim to "solving 1+Ns"?
Like maybe if you can express truly generic business logic, and somehow that is translated into "evaled on the database-side" SQL?
(Disclaimer, I work on an ORM that does let you interleave business logic & database loads, and still avoids 1+Ns: https://joist-orm.io/goals/avoiding-n-plus-1s/)
by stephen - This is what you get when you let your ORM loose on the database without understanding JOINs. Especially, the bit where something like 'book.author.name' that looks like a simple field dereference actually is a method call on an ORM proxy object (book), via python's __getattr__ or similar, that fires off a new query if the data you want is not loaded yet.
Some ORMs let you specify the extent of the data that you want, like Hibernate has its own Hibernate Query Language.
At some point you are better off just writing SQL yourself, though. Even without join problems, if you ask an ORM to get the person with user id 123 and all you want is their name, the ORM cannot know that unless to tell it, and so you end up with a 'SELECT *' type query.
by red_admiral - > all you want is their name
I have a WIP PR that addresses exactly this:
by stephen - You should write a raw SQL query to grab just a user's name only when there's a need for that.by seki285
- Or set lazy loadin to "raise" in the relationships and get exceptions if you dont explicitly join.by ddorian43
- This is true but not super true in case of linq and related providers like efcore. Even nhibernate linq would do this.by tehlike
- ORMs are great. They make the easy queries remain easy and the harder queries impossible.by cnity
- People always say this and my experience in C# has been the opposite. I've never wanted to reach for raw SQL and hardly ever do, only if its because there's no extension to do SKIP..LOCKED or something
var name = dbContext.Users .Where(u => u.Id == 123) .Select(u => u.Name) .First();
by plaguuuuuu