Repository navigation
Description
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.findFirstonce 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
aqrln commentedon Jul 21, 2026
Interesting, thanks for the report! We'll have a look.
Hprogram commentedon Jul 22, 2026
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.
applyFluentbuilds a field-name→field map for the model on every invocation:Two things compound here:
{ ...acc }spread insidereducemakes construction O(fields²) — each iteration copies every previously accumulated entry.findUnique/findFirst/create/update/upsert/delete—applyModelinvokesapplyFluentin its property getter), even though the map is only read inside the fluent Proxy'sgettrap, i.e. only when you actually chain.relation()off the returned promise. For a plainfindFirst({ 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:findFirst({select:{id:true}})p50findMany({take:1})p50 (control — not a fluent action)findManyisn't in the fluent-props list, so it skipsapplyFluent— and stays flat at any relation count, which cleanly isolates the overhead to this path. A--cpu-profrun 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
gettrap 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.)fix(client): build fluent API field map lazily and in linear time
fix(client): build fluent API field map lazily and in linear time (#2…
fix(client): build fluent API field map lazily and in linear time (pr…