Skip to content

Per-query overhead scales with the model's declared relation count — persists in v7 query compiler (same DB/table/query: 0.24ms at 30 relations → 1.46ms at 300) #29745

Closed

Description

@fairnakub

Bug description

Client-observed latency of a trivial findFirst({ select: { id: true } }) scales with how many relation fields the queried model declares in the schema — even though the generated SQL and the executed query are identical. This was measurable on the v6 Rust engine and persists unchanged on v7's TypeScript query compiler (7.9.0, query caching active).

Isolation: same database, same table, same query — only the schema's relation count on the model changes:

Client generated from hub.findFirst p50 (50 iters, warm)
schema where Hub has 30 back-relations 0.24ms
schema where Hub has 300 back-relations 1.46ms
Leaf control model (0 relations), either schema ~0.30ms

(Apple M-series; Postgres 16 in local Docker; Postgres executes the statement in <0.1ms per pg_stat_statements.) On a small cloud vCPU the same shape costs 20–90ms per query in our production app (735-model schema; the "user" hub model has ~390 back-relations), which made every request paying 2–3 such lookups ~200ms before we worked around it.

v7.4's query parameterization/caching does not absorb it: the numbers above are steady-state over 50 identical iterations (min ≈ p50).

Expected: after the first compilation of a given query shape, per-query cost should be independent of how many unrelated relation fields the model declares.

How to reproduce

// gen-schema.mjs — hub model with N back-relations + zero-relation control
import { writeFileSync } from 'node:fs';
const N = Number(process.env.N ?? 300);
let s = `generator client {\n  provider = "prisma-client"\n  output   = "./generated"\n}\n\ndatasource db {\n  provider = "postgresql"\n}\n\n`;
s += `model Hub {\n  id String @id @default(uuid())\n  name String\n`;
for (let i = 0; i < N; i++) s += `  spokes${i} Spoke${i}[]\n`;
s += `}\n\nmodel Leaf {\n  id String @id @default(uuid())\n  name String\n}\n\n`;
for (let i = 0; i < N; i++) {
  s += `model Spoke${i} {\n  id String @id @default(uuid())\n  hubId String\n  hub Hub @relation(fields: [hubId], references: [id])\n}\n\n`;
}
writeFileSync('schema.prisma', s);
// bench.mjs
import { PrismaClient } from './generated/client.js';
import { PrismaPg } from '@prisma/adapter-pg';
const p = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }) });
const t = async (label, fn) => {
  await fn();
  const xs = [];
  for (let i = 0; i < 50; i++) {
    const s = process.hrtime.bigint();
    await fn();
    xs.push(Number(process.hrtime.bigint() - s) / 1e6);
  }
  xs.sort((a, b) => a - b);
  console.log(label, 'p50=' + xs[25].toFixed(2) + 'ms');
};
await t('leaf.findFirst', () => p.leaf.findFirst({ select: { id: true } }));
await t('hub.findFirst ', () => p.hub.findFirst({ select: { id: true } }));
await p.$disconnect();
npm i prisma@7 @prisma/client@7 @prisma/adapter-pg dotenv tsx
N=300 node gen-schema.mjs
npx prisma db push && npx prisma generate
DATABASE_URL=... npx tsx bench.mjs   # hub ≈ 5-6× leaf
N=30 node gen-schema.mjs && npx prisma generate
DATABASE_URL=... npx tsx bench.mjs   # hub ≈ leaf (same DB/tables as before)

(prisma.config.ts with schema: 'schema.prisma' and a datasource url from env.)

Expected vs actual

  • Expected: hub.findFirst ≈ leaf.findFirst once warm.
  • Actual: linear-looking growth with declared relation count; ~5–6× at 300 relations, worse on slower CPUs.

Environment & setup

  • OS: macOS (Apple Silicon), also reproduced on Alpine Linux x86_64 (2 vCPU) with larger absolute numbers
  • Database: PostgreSQL 16
  • Node.js: 24.x

Prisma Version

Reproduced on 7.9.0 (query compiler) and 6.19.3 (Rust engine — same scaling, slightly lower constants).

Activity

  1. aqrln commented on Jul 21, 2026

    @aqrln
    Member

    Interesting, thanks for the report! We'll have a look.

  2. Hprogram commented on Jul 22, 2026

    @Hprogram
    Contributor

    I profiled this and can confirm the overhead — it lives entirely in the client-side proxy layer, before the query-plan cache, which is why caching doesn't absorb it.

    Root cause. applyFluent builds a field-name→field map for the model on every invocation:

    // packages/client/src/runtime/core/model/applyFluent.ts
    const dmmfModelFieldMap = dmmfModel.fields.reduce(
      (acc, field) => ({ ...acc, [field.name]: field }),
      {} as { [dmmfModelFieldName: string]: DMMF.Field },
    )

    Two things compound here:

    1. The { ...acc } spread inside reduce makes construction O(fields²) — each iteration copies every previously accumulated entry.
    2. It runs eagerly on every property access of the fluent-API actions (findUnique/findFirst/create/update/upsert/delete — applyModel invokes applyFluent in its property getter), even though the map is only read inside the fluent Proxy's get trap, i.e. only when you actually chain .relation() off the returned promise. For a plain findFirst({ select: { id: true } }) it's built and thrown away.

    Evidence. Reproduced with [email protected] (@prisma/adapter-better-sqlite3, warm, 500 iters), schemas differing only in declared back-relation count:

    relations findFirst({select:{id:true}}) p50 findMany({take:1}) p50 (control — not a fluent action)
    0 0.032 ms 0.030 ms
    30 0.044 ms 0.032 ms
    300 1.5–1.7 ms 0.031 ms

    findMany isn't in the fluent-props list, so it skips applyFluent — and stays flat at any relation count, which cleanly isolates the overhead to this path. A --cpu-prof run at 300 relations attributes ~77% of sampled self-time to this reduce.

    The fix is small — building the map in a single pass and lazily (only when the fluent get trap first needs it), so non-chained calls pay nothing: #29751 covers the sibling stack-overflow issue, and I've opened a PR for this one with before/after measurements. (A further step would be memoizing the map per model on the client instance so chained calls never rebuild it either — happy to include that if preferred.)

  3. added a commit that references this issue on Jul 22, 2026
    ebcfa35
  4. added a commit that references this issue on Jul 22, 2026
    e720bd6
  5. added a commit that references this issue on Aug 9, 2026
    440cc78
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions