createMany / createManyAndReturn compile a new plan on every call, and the plan and its compile time grow with the row count
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 35/100
- Issue type
- Feature
- Clarity
- Mostly clear
- Activity status
- Active
- Tech stack
- postgresql, typescript, wasm
- Domain
- backend-api-design, databases, performance
Research direction
Start by reading the plan cache exclusion in packages/client/src/runtime/core/engines/ClientEngine.ts and the parameterTupleList handling in packages/client-engine-runtime/src/query-plan.ts and packages/client-engine-runtime/src/interpreter/render-query.ts. The issue proposes compiling bulk inserts with a row-count-independent plan, but generated defaults, differing column sets, enum casts, duplicate handling, and connector support still need investigation. Done means repeated calls with the same model, columns, and selection can share a compact cached plan while preserving these behaviors.
Written by the indexing model from the issue text.
Description
Package and version
[email protected], @prisma/[email protected], @prisma/[email protected] (latest 7.x), [email protected], prisma-client-js generator, compilerBuild default (fast).
What happened?
Every createMany / createManyAndReturn call runs the query compiler synchronously, and both the compile time and the compiled plan grow linearly with the number of rows. Repeating a call with the same row count and the same fields does not help: nothing is cached.
Measured with the reproduction below (one model with 12 inserted columns, PostgreSQL 17 in a local container, 200 calls per row count after 5 warm-up calls; two runs, both shown as run 1 / run 2):
| Call | Rows | Wall time per call, median (ms) | Synchronous compile per call, median (ms) | Compiles per call | Compiled plan size |
|---|---|---|---|---|---|
createMany |
5 | 0.90 / 0.95 | 0.31 / 0.28 | 1 | 11.5 KB |
createMany |
50 | 6.67 / 7.01 | 2.60 / 2.66 | 1 | 112 KB |
createMany |
500 | 42.66 / 44.40 | 22.69 / 22.55 | 1 | 1,117 KB |
createManyAndReturn |
500 | 43.59 / 42.78 | 22.46 / 23.12 | 1 | 1,117 KB |
$transaction([createMany]) |
500 | 43.28 / 44.00 | 22.61 / 22.52 | 1 | 1,117 KB |
create (1 row, reference) |
1 | 0.33 / 0.33 | — | 0 | — |
- The compile cost is about 0.045 ms and the plan about 2.2 KB per row (12 columns). At 500 rows the compile is about half of the wall time of the call.
QueryCompiler.compileis a synchronous WebAssembly call, so the event loop is blocked for that time; other requests on the same process wait.- I measured the same per-row cost on a different, 50-model synthetic schema (500 rows: 22.4-23.2 ms compile, 1,116 KB plan), so it does not seem to depend on schema size.
- The one-query
$transaction([...])also compiled on every call in 7.10.1. I did not trace why. Onv7, #30581 now excludes every batch that contains acreateManyfrom the cache on purpose.
Why (from the code, v7 at 92d8025e):
- The plan cache is skipped on purpose:
ClientEngine.tsL817-L823We do not cache
createManyandcreateManyAndReturnqueries as they are very unlikely to benefit from caching due to their high variability in parameters, which leads to a very high cache miss rate and potential cache bloat. - That variability comes from the plan's shape. For a 2-row
createMany(dumped from thecompilereturn value), thetemplateSqlhas one{"type":"parameter"}fragment per row × column (24 for 2 rows × 12 columns), with theVALUES (…), (…)separators as string chunks, and oneletbinding per row for each generated default (@generated$row0$createdAt,@generated$row1$createdAt, …). So a plan is specific to the row count, which is why caching it does not pay, and why compiling it costs time proportional to the rows.
What did you expect to happen?
Inserting N rows with the same set of fields should not compile a plan whose size and compile time grow with N, and calls with the same set of fields should be able to share one cached plan.
Possible direction (a proposal; I have not prototyped it): the plan language already has a fragment that renders a variable-length list of tuples from a single argument, parameterTupleList (query-plan.ts L76-L82, rendered in render-query.ts L152-L161), and the interpreter already splits such a list into chunks by the adapter's bind-parameter limit when the query is chunkable (render-query.ts L344-L377). If the compiler emitted the VALUES list of createMany / createManyAndReturn as one parameterTupleList bound to a single list placeholder (each row becoming a tuple in column order), and parameterization turned data: [...] into that one placeholder, then:
- the plan would no longer depend on the row count, so compile time would stay constant, and
- the plan could be cached under a key made of the model, the set of columns and the selection, so
isCacheableQuerywould no longer need to exclude these actions.
Open points I can see but have not checked:
- generated defaults (
now(),cuid(),uuid(), …) are currently per-rowletbindings; they would need to be evaluated per tuple at execution time; - rows that provide different sets of fields: the column set would have to be part of the cache key (or missing values rendered as
DEFAULT); - per-value enum casts (
CAST($n::text AS "Enum"), see also #29715) would have to become a per-column template; skipDuplicates, and connectors without multi-rowVALUES.
Minimal reproduction
mkdir createmany-compile && cd createmany-compile
npm init -y
npm i [email protected] @prisma/[email protected] @prisma/[email protected] pg
docker run -d --name cm-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=bulk -p 127.0.0.1:55432:5432 postgres:17-alpine
# schema.prisma and prisma.config.ts below (prisma.config.ts points at the container)
npx prisma generate
npx prisma db push
node bench-createmany.cjs postgresql://postgres:[email protected]:55432/bulk 200
node bench-createmany.cjs postgresql://postgres:[email protected]:55432/bulk 1 dump # prints the plan of a 2-row createMany
schema.prisma
generator client {
provider = "prisma-client-js"
output = "./generated"
}
datasource db {
provider = "postgresql"
}
enum Status {
A
B
C
}
model Item {
id Int @id @default(autoincrement())
groupId Int
name String
code String?
note String?
status Status @default(A)
amount Decimal? @db.Decimal(12, 2)
qty Int @default(0)
active Boolean @default(true)
meta Json?
createdAt DateTime @default(now())
extA String?
extB Int?
extC DateTime?
}
prisma.config.ts
import { defineConfig } from 'prisma/config'
export default defineConfig({
schema: 'schema.prisma',
datasource: { url: 'postgresql://postgres:[email protected]:55432/bulk' },
})
bench-createmany.cjs
// node bench-createmany.cjs <database url> [samples=200] [dump]
// Per call: wall time of the awaited call, synchronous time spent in QueryCompiler.compile/compileBatch,
// number of compiles, and the size of the last compiled plan. Every call uses the same row count and
// the same fields, so after the first call a plan cache could serve it.
const path = require('node:path');
const { performance } = require('node:perf_hooks');
const [url, samplesArg = '200', mode] = process.argv.slice(2);
const SAMPLES = Number(samplesArg);
const { QueryCompiler } = require('./generated/query_compiler_fast_bg.js');
let compiles = 0;
let compileMs = 0;
let lastPlan = '';
for (const method of ['compile', 'compileBatch']) {
const orig = QueryCompiler.prototype[method];
QueryCompiler.prototype[method] = function (...args) {
const t = performance.now();
const out = orig.apply(this, args);
compileMs += performance.now() - t;
compiles++;
lastPlan = typeof out === 'string' ? out : JSON.stringify(out);
return out;
};
}
const { PrismaClient } = require('./generated');
const { PrismaPg } = require('@prisma/adapter-pg');
const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: url }) });
const rows = (n, salt) =>
Array.from({ length: n }, (_, i) => ({
groupId: 1, name: `r${salt}-${i}`, code: `c${i}`, note: null, status: 'B', amount: `${i}.50`,
qty: i, active: i % 2 === 0, extA: `x${i}`, extB: i, extC: new Date(1700000000000 + i),
}));
const pct = (a, p) => {
const s = [...a].sort((x, y) => x - y);
return +s[Math.min(s.length - 1, Math.ceil(s.length * p) - 1)].toFixed(2);
};
const ops = {
createMany: (d) => prisma.item.createMany({ data: d }),
createManyAndReturn: (d) => prisma.item.createManyAndReturn({ data: d, select: { id: true } }),
'$transaction([createMany])': (d) => prisma.$transaction([prisma.item.createMany({ data: d })]),
};
(async () => {
await prisma.$executeRaw`TRUNCATE "Item" RESTART IDENTITY`;
if (mode === 'dump') {
await ops.createMany(rows(2, 'dump'));
console.log(lastPlan);
return prisma.$disconnect();
}
const results = [];
for (const [op, run] of Object.entries(ops)) {
for (const n of [5, 50, 500]) {
for (let w = 0; w < 5; w++) await run(rows(n, `warm${w}`));
const wall = [];
const comp = [];
const c0 = compiles;
for (let s = 0; s < SAMPLES; s++) {
if (s % 20 === 0) await prisma.$executeRaw`TRUNCATE "Item" RESTART IDENTITY`;
const data = rows(n, s);
const cm = compileMs;
const t = performance.now();
await run(data);
wall.push(performance.now() - t);
comp.push(compileMs - cm);
}
results.push({
op, rows: n,
wallMedianMs: pct(wall, 0.5), wallP95Ms: pct(wall, 0.95),
compileMedianMs: pct(comp, 0.5),
compilesPerCall: (compiles - c0) / SAMPLES,
planKB: +(lastPlan.length / 1024).toFixed(1),
});
}
}
// Reference: single-row create, served from the plan cache after the first call.
const one = rows(1, 'one')[0];
for (let w = 0; w < 5; w++) await prisma.item.create({ data: one, select: { id: true } });
const wall = [];
const c0 = compiles;
for (let s = 0; s < SAMPLES; s++) {
const t = performance.now();
await prisma.item.create({ data: { ...one, name: `s${s}` }, select: { id: true } });
wall.push(performance.now() - t);
}
results.push({ op: 'create (reference)', rows: 1, wallMedianMs: pct(wall, 0.5), wallP95Ms: pct(wall, 0.95), compilesPerCall: (compiles - c0) / SAMPLES });
console.table(results);
await prisma.$disconnect();
})().catch((e) => {
console.error(e);
process.exit(1);
});
Environment
- Node.js 24.23.0
- OS: macOS, arm64
- Package manager: npm
- Database: PostgreSQL 17.11 (
postgres:17-alpine, local Docker)
Additional context
Related: #30581 (batches containing createMany are no longer cached, because those plans grow with the row count and bloated the batch cache), #30487 (batch cache growth with varying batch shapes), #29715 (per-value enum casts in bulk inserts).
- Dominant language
- TypeScript
- Stars
- 47.8k
- Forks
- 2.6k
- Avg merge
- 1d 21h
- Merged PRs (30d)
- 227
Getting set up
- Ships a Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from prisma/orm
-
bug/1-unconfirmed kind/bug
Difficulty 1/5 Under an hour Newbie friendliness 90/100
Maintainers usually reply within 1 day
-
get-platform: distros with ID_LIKE=alpine are not detected as musl, so glibc engines are used on Alpine-based imagesPossibly taken A pull request linked to this issue is open or already merged. Open
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
prisma/orm#31281 · 1 comment ·
Maintainers usually reply within 1 day
-
adapter-pg: connectToShadowDb connects to the main database when built from a connection stringMay be free again @cestercian claimed this 10 days ago, and no pull request is open. Open
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
prisma/orm#31196 · 1 comment ·
Maintainers usually reply within 1 day
-
[Prisma 8] Type-check time grows exponentially with chained .include() callsPossibly taken @SiKreuz claimed this 13 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
prisma/orm#31161 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
prisma/orm#31125 · 4 comments · 6 reactions ·
Maintainers usually reply within 1 day
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
tashfeenahmed/freellmapi#2305 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
prime-radiant-inc/evener#8335 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
vercel-labs/ui#1921 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
Difficulty 1/5 1-3 hours Newbie friendliness 65/100
microsoft/monaco-editor#5626 ·
Maintainers usually reply within 1 day