Repository navigation
Open
Labels
bug/2-confirmedBug has been reproduced and confirmed.kind/bugA reported bug.topic: Promise.alltopic: batchingtopic: chunkingtopic: findUnique()topic: postgresql
Description
Bug description
While querying large datasets leveraging findUnique to prevent GraphQL N+1s, we're experiencing parameter binding errors due to the amount of bound parameters created in the batched query.
This causes the graphql query hitting these resolvers to fail.
Error:
prisma.account.findUnique(
Assertion violation on the database: `too many bind variables in prepared statement, expected maximum of 32767,
received 150656`
How to reproduce
- With over 33000 rows in the table you're querying
- Perform 33000 individual entity.findUnique() queries in a
Promise.all, simulating a large GQL N+1 - Expect parameter binding error after surpassing your Postgres variable binding limit.
Expected behavior
Potentially split queries that would exceed the bound param limit into multiple batches.
Prisma information
Schema: Unrelated
Code:
const accountIds = await prisma.account
.findMany({
select: { id: true },
where: {
companyId: redacted,
},
})
.then((result) => result.map(({ id }) => id));
await Promise.all(
accountIds.map((id) =>
prisma.account.findUnique({
where: {
id,
},
})
)
);
Environment & setup
- OS: macOS, Windows, Debian, CentOS
- Database: PostgreSQL
- Node.js version:
v20.11.1
Prisma Version
prisma : 5.7.1
@prisma/client : 5.7.1
Computed binaryTarget : darwin
Operating System : darwin
Architecture : x64
Node.js : v20.11.1
Query Engine (Node-API) : libquery-engine 0ca5ccbcfa6bdc81c003cf549abe4269f59c41e5 (at node_modules/@prisma/engines/libquery_engine-darwin.dylib.node)
Schema Engine : schema-engine-cli 0ca5ccbcfa6bdc81c003cf549abe4269f59c41e5 (at node_modules/@prisma/engines/schema-engine-darwin)
Schema Wasm : @prisma/prisma-schema-wasm 5.7.1-1.0ca5ccbcfa6bdc81c003cf549abe4269f59c41e5
Default Engines Hash : 0ca5ccbcfa6bdc81c003cf549abe4269f59c41e5
Studio : 0.495.0
Preview Features : metrics, relationJoins
Reacted by Will Neville and Aleksandr
Metadata
Metadata
Assignees
Labels
bug/2-confirmedBug has been reproduced and confirmed.kind/bugA reported bug.topic: Promise.alltopic: batchingtopic: chunkingtopic: findUnique()topic: postgresql
Activity
[-]FindUnique batching exceeding parameter binding limits[/-][+]`findUnique()` batching exceeding parameter binding limits[/+]janpio commentedon Jun 4, 2024
From the description, it seems that our chunking logic does not trigger for the batched/packed SQL query. We need to confirm and understand.
@chris-basis Are you running the query as it is and documented above, or are you maybe using a Client extension that modifies the query in some form?
Can you please enable query logging for your Prisma Client, lower the number to one that still works (so <30.000) and then share part of the SQL query being logged? (Unfortunately we do not log the actual query that fails it seems...)
flaviaan commentedon Jun 6, 2024
Hey, I'm unable to reproduce your issue. Here's what I've been trying:
Logs show that the query is properly chunked into many and no error is thrown.
Could you help us by providing more info? Thank you!
jkomyno commentedon Jul 15, 2024
Hi @chris-basis, have you seen @Weakky's comment above?
By the way, I've given this a shot. This is what I get on Prisma 5.7.1 with the following schema:
Prisma schema
@prisma/clientsnippetConsole output
If I repeat the snippet without the
relationJoinspreview feature, here's what I get:I'm not, however, able to get the error you reported:
jkomyno commentedon Jul 15, 2024
Actually, thanks to a comment in a related issue (#24443), I was able to obtain the same error message (though while using a different schema and snippet).
Prisma schema
@prisma/clientsnippetOutput
jkomyno commentedon Jul 15, 2024
Causes of this issue
Here is a techincal analysis of why this issue is happening in the first place.
Multiple
findUniquequeries are started concurrently within the same Node.js tick, via something like:When this happens, Prisma's Dataloader kicks in, an rather than emitting as many
SELECT ... FROM "User" WHERE ...statements as there are concurrentfindUniquequeries, it emits a singleSELECT ... FROM "User" WHERE ...compact query that tries to return the same data the user would expect, but in a single roundtrip to the database.More precisely, consider the following
findUniquequery:findUniquequery:$1is the query parameter for the 1stid,1findUniquequeries:$1is the query parameter for the 1stid,1$2is the query parameter for the 2ndid,2findUniquequeries:$1is the query parameter for the 1stid,1$2is the query parameter for the 2ndid,2$32766is the query parameter for the 32766thid,32766The Postgres driver that Prisma uses under the hood supports a maximum of 32767 query parameters. This means that running the snippet of
findUnique()batching exceeding parameter binding limits #23957 (comment) withconst n = 32767is just enough to trigger the errorCan Prisma currently handle 32767+ concurrent
findUniquequeries at all? Yes, but only if thewherefilter is simplified to e.g.,prisma.user.findUnique({ select: { ... }, where: { id, - deletedAt: null, }, })This
wherefilter only uses aPRIMARY KEYcolumn, which allows for simpler SQL queries.The Prisma Datasource still kicks in, so the 32767 concurrent
findUniquequeries, rather than generating 32767 corresponding SQL queries, are theoretically compacted into a single, large SQL query of the following shape, different than before:In reality, since Prisma also has a chunking mechanism built-in, and since
32768is greater than32767, the maximum number of query parameters supported by Postgres, Prisma splits the query above into two queries, whose result sets are then merged maintaining the order of the inner results:Related issues
findMany()with two largeinfilters with arrays of32767items each fails withAssertion violation,too many bind variables in prepared statement#21802findMany()with two largeinfilters with arrays of65536items each results in no query chunking when using Driver Adapters #21803Promise.allin interactive$transactionunexpectedly merges operations #23951findUnique()is not chunked and exceeds parameter binding limits #24443...and possibly others in this list.
How to fix this issue
Prisma needs to change how compacted queries for multiple
findUniquequeries are generated.When Prisma detects that multiple
findUniquequeries are triggered within the same Node.js (or whatever JS runtime) tick, e.g. viaawait Promise.all(... /* prisma findUnique queries */), and these queries havewherefilters conditional on both unique keys (e.g., theidcolumn) and non-unique fields (e.g., thedeletedAtcolumn), it should generate compact queries with the following shape:W.r.t. the snippet in #23957 (comment), this would look like:
which - due to query chunking - would be split into
We don't have plans of removing the Dataloader batching feature, though there is a feature request for disabling it (which would only hide the problem, without actually solving it).