Skip to content

findUnique() batching exceeding parameter binding limits #23957

Open

Description

@chris-basis

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

  1. With over 33000 rows in the table you're querying
  2. Perform 33000 individual entity.findUnique() queries in a Promise.all, simulating a large GQL N+1
  3. 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

Activity

  1. changed the title [-]FindUnique batching exceeding parameter binding limits[/-] [+]`findUnique()` batching exceeding parameter binding limits[/+] on Apr 25, 2024
  2. added
    bug/1-unconfirmed
    on Apr 25, 2024
  3. janpio commented on Jun 4, 2024

    @janpio
    Contributor

    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...)

  4. self-assigned this
    on Jun 6, 2024
  5. flaviaan commented on Jun 6, 2024

    @flaviaan
    Contributor

    Hey, I'm unable to reproduce your issue. Here's what I've been trying:

    model User {
      id Int @id
    }
    // seed.ts
    import { PrismaClient, Prisma } from "@prisma/client";
    
    const N_USERS = 200_000;
    
    async function seed() {
      const prisma = new PrismaClient();
    
      console.log("Seeding users...");
      await seedUsers(prisma);
    
      await prisma.$disconnect();
    }
    
    async function seedUsers(prisma: PrismaClient) {
      let users: Prisma.UserUncheckedCreateInput[] = [];
    
      for (let i = 1; i <= N_USERS; i++) {
        users.push({
          id: i,
        });
      }
    
      await prisma.user.createMany({
        data: users,
      });
    }
    
    seed()
      .then(() => console.log("Done!"))
      .catch((err) => console.error(err));
    // actual reproduction
    import { PrismaClient } from "@prisma/client";
    
    async function main() {
      const prisma = new PrismaClient({
        log: ["query"]
      });
      const users = await prisma.user.findMany({ take: 100000 });
    
      const res = await Promise.all(
        users.map((id) =>
          prisma.user.findUnique({
            where: {
              id: id.id,
            },
          })
        )
      );
    
      console.log(res)
    }
    
    main()
      .then(() => console.log("Done!"))
      .catch((err) => console.error(err));

    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!

  6. added
    bug/0-unknown
    and removed
    bug/1-unconfirmed
    on Jun 6, 2024
  7. jkomyno commented on Jul 15, 2024

    @jkomyno
    Contributor

    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

      generator client {
        provider        = "prisma-client-js"
        output          = "../node_modules/.prisma/client"
        previewFeatures = ["relationJoins"] // extrapolated from the "Preview Features" section of this issue's description
      }
      
      datasource db {
        provider = "postgres"
        url      = env("TEST_POSTGRES_URI")
      }
      
      model Tag {
        id Int  @id
      }
      
      model Company {
        id Int  @id
        name String
        accounts Account[]
      }
      
      model Account {
        id Int  @id
        name String
        companyId Int
        company Company @relation(fields: [companyId], references: [id])
      }
    • @prisma/client snippet

      import { PrismaClient } from '.prisma/client'
      
      async function main() {
        const prisma = new PrismaClient()
      
        await prisma.account.deleteMany()
        await prisma.company.deleteMany()
      
        const n = 33_001
        const ids = Array.from({ length: n }, (_, i) => i + 1)
      
        const { id: companyId } = await prisma.company.create({
          data: {
            id: 1,
            name: 'company',
          }
        })
      
        await prisma.account.createMany({
          data: ids.map((id) => ({
            id: id + 1,
            companyId,
            name: `account-${id + 1}`
          }))
        })
      
        const accountsFromCreate = await prisma.account.findMany({
          select: {
            id: true,
          },
          where: {
            companyId,
          },
        })
      
        const accountIds = accountsFromCreate.map((account) => account.id)
      
        const accountsFromQuery = await Promise.all(
          accountIds.map((id) =>
            prisma.account.findUnique({
              where: {
                id,
              },
            })
          )
        )
      
        console.log('accountsFromQuery.length', accountsFromQuery.length)
        console.log('accountsFromQuery')
        console.dir(accountsFromQuery[0], { depth: null })
        console.dir(accountsFromQuery[1], { depth: null })
      
        process.exit(0)
      }
      
      void main().catch((e) => {
        console.log(e.message)
        process.exit(1)
      })
    • Console output

      Invalid `prisma.account.findUnique()` invocation in
      /.../index.ts:40:22
      
        37 
        38 const accountsFromQuery = await Promise.all(
        39   accountIds.map((id) =>
      → 40     prisma.account.findUnique(
      Query parameter limit exceeded error: Joined queries cannot be split into multiple queries..
      

    If I repeat the snippet without the relationJoins preview feature, here's what I get:

    accountsFromQuery.length 33001
    accountsFromQuery
    { id: 2, name: 'account-2', companyId: 1 }
    { id: 3, name: 'account-3', companyId: 1 }
    

    I'm not, however, able to get the error you reported:

    prisma.account.findUnique(
      Assertion violation on the database: `too many bind variables in prepared statement, expected maximum of 32767, 
      received 150656`
    
  8. jkomyno commented on Jul 15, 2024

    @jkomyno
    Contributor

    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

      generator client {
        provider = "prisma-client-js"
      }
      
      datasource db {
        provider = "postgres"
        url      = env("TEST_POSTGRES_URI")
      }
      
      model User {
        id        Int    @id @default(autoincrement())
        name      String
        
        createdAt DateTime  @default(now())
        updatedAt DateTime  @updatedAt
        deletedAt DateTime?
      }
    • @prisma/client snippet

      import { PrismaClient } from '.prisma/client'
      
      async function main() {
        const prisma = new PrismaClient({
          // log: ['query'],
        })
      
        await prisma.user.deleteMany()
      
        // decrease `n` by 1 to make the snippet succeed
        const n = 32767
        const usersToSeed = Array.from({ length: n }).map((_, i) => {
          const id = i + 1
      
          return { id, name: `name-${id}` }
        })
      
        await prisma.user.createMany({ data: usersToSeed })
      
        const usersFromQuery = await Promise.all(
          usersToSeed.map(({ id }) =>
            prisma.user.findUnique({
              where: {
                id,
      
                // comment `deleteAt` to make the snippet succeed
                deletedAt: null,
              },
            })
          )
        )
      
        console.log('usersFromQuery.length', usersFromQuery.length)
        console.log('usersFromQuery[0]')
        console.dir(usersFromQuery[0], { depth: null })
      
        process.exit(0)
      }
      
      void main().catch((e) => {
        console.log(e.message)
        process.exit(1)
      })
    • Output

      Invalid `prisma.user.findUnique()` invocation in
      /Users/jkomyno/work/prisma/prisma/sandbox/basic-postgres/index.ts:22:19
      
        19 
        20 const usersFromQuery = await Promise.all(
        21   usersToSeed.map(({ id }) =>
      → 22     prisma.user.findUnique(
      Assertion violation on the database: `too many bind variables in prepared statement, expected maximum of 32767, received 40001`
      
  9. jkomyno commented on Jul 15, 2024

    @jkomyno
    Contributor

    Causes of this issue

    Here is a techincal analysis of why this issue is happening in the first place.

    • Multiple findUnique queries are started concurrently within the same Node.js tick, via something like:

      const results = await Promise.all([
        prisma.user.findUnique(...),
        prisma.user.findUnique(...),
      ])
    • When this happens, Prisma's Dataloader kicks in, an rather than emitting as many SELECT ... FROM "User" WHERE ... statements as there are concurrent findUnique queries, it emits a single SELECT ... 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 findUnique query:

      prisma.user.findUnique({
        select: {
          id: true,
        },
        where: {
          id: id, // `id` is a numeric variable
          deletedAt: null,
        },
      })
      1. Here is the SQL query emitted when running 1 findUnique query:
      SELECT
        "public"."User"."id"
      FROM "public"."User"
      WHERE
        ("public"."User"."id" = $1 AND "public"."User"."deletedAt" IS NULL)
      LIMIT $2 OFFSET $3
      • $1 is the query parameter for the 1st id, 1
      1. Here is the SQL query emitted when running 2 concurrent findUnique queries:
      SELECT
        "public"."User"."id", "public"."User"."deletedAt"
      FROM "public"."User"
      WHERE (
        ("public"."User"."id" = $1 AND "public"."User"."deletedAt" IS NULL) OR
        ("public"."User"."id" = $2 AND "public"."User"."deletedAt" IS NULL)
      )
      OFFSET $3
      • $1 is the query parameter for the 1st id, 1
      • $2 is the query parameter for the 2nd id, 2
      1. Here is (part of) the SQL query emitted when running 32766 concurrent findUnique queries:
      SELECT
        "public"."User"."id", "public"."User"."deletedAt"
      FROM "public"."User"
      WHERE (
        ("public"."User"."id" = $1 AND "public"."User"."deletedAt" IS NULL) OR
        ("public"."User"."id" = $2 AND "public"."User"."deletedAt" IS NULL) OR
        -- ... OR
        ("public"."User"."id" = $32766 AND "public"."User"."deletedAt" IS NULL)
      )
      OFFSET $32767
      • $1 is the query parameter for the 1st id, 1
      • $2 is the query parameter for the 2nd id, 2
      • $32766 is the query parameter for the 32766th id, 32766
    • The 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) with const n = 32767 is just enough to trigger the error

      Invalid `prisma.user.findUnique()` invocation in
      /.../index.ts:22:19
      
        19 
        20 const usersFromQuery = await Promise.all(
        21   usersToSeed.map(({ id }) =>
      → 22     prisma.user.findUnique(
      Assertion violation on the database: `too many bind variables in prepared statement, expected maximum of 32767, received 32768`
      
    • Can Prisma currently handle 32767+ concurrent findUnique queries at all? Yes, but only if the where filter is simplified to e.g.,

      prisma.user.findUnique({
        select: { ... },
        where: {
          id,
      -   deletedAt: null,
        },
      })

      This where filter only uses a PRIMARY KEY column, which allows for simpler SQL queries.
      The Prisma Datasource still kicks in, so the 32767 concurrent findUnique queries, rather than generating 32767 corresponding SQL queries, are theoretically compacted into a single, large SQL query of the following shape, different than before:

      SELECT
        "public"."User"."id"
      FROM
        "public"."User"
      WHERE
        "public"."User"."id" IN ($1,$2,$3, ... $32767)
      OFFSET $32768

      In reality, since Prisma also has a chunking mechanism built-in, and since 32768 is greater than 32767, 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:

      1. First query chunk
      SELECT
        "public"."User"."id"
      FROM
        "public"."User"
      WHERE
        "public"."User"."id" IN ($1,$2,$3, ... $32766)
      OFFSET $32767
      1. Second query chunk
      SELECT
        "public"."User"."id"
      FROM
        "public"."User"
      WHERE
        "public"."User"."id" IN ($1)
      OFFSET $2

    Related issues

    ...and possibly others in this list.

    How to fix this issue

    Prisma needs to change how compacted queries for multiple findUnique queries are generated.

    When Prisma detects that multiple findUnique queries are triggered within the same Node.js (or whatever JS runtime) tick, e.g. via await Promise.all(... /* prisma findUnique queries */), and these queries have where filters conditional on both unique keys (e.g., the id column) and non-unique fields (e.g., the deletedAt column), it should generate compact queries with the following shape:

    SELECT
      <FIELDS>
    FROM
      <TABLE>
    WHERE (
      <UNIQUE_KEY> IN (<PARAMETERS_LIST>)
    ) AND (
      <NON_UNIQUE_KEY> = <SHARED_NON_UNIQUE_VALUE>
    )

    W.r.t. the snippet in #23957 (comment), this would look like:

    SELECT
      "public"."User"."id"
    FROM
      "public"."User"
    WHERE (
      "public"."User"."id" IN ($1, $2, ..., $32767)
    ) AND (
      "public"."User"."deletedAt" IS NULL
    )
    OFFSET $32768

    which - due to query chunking - would be split into

    1. First query
    SELECT
      "public"."User"."id"
    FROM
      "public"."User"
    WHERE (
      "public"."User"."id" IN ($1, $2, ..., $32766)
    ) AND (
      "public"."User"."deletedAt" IS NULL
    )
    OFFSET $32767
    1. Second query
    SELECT
      "public"."User"."id"
    FROM
      "public"."User"
    WHERE (
      "public"."User"."id" IN ($1)
    ) AND (
      "public"."User"."deletedAt" IS NULL
    )
    OFFSET $2

    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).

  10. added
    bug/2-confirmed
    and removed
    bug/0-unknown
    on Jul 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions