createMany / createManyAndReturn compile a new plan on every call, and the plan and its compile time grow with the row count

Open
#31,324 1 comment 0 reactions 0 assignees View on GitHub

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

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.compile is 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. On v7, #30581 now excludes every batch that contains a createMany from the cache on purpose.

Why (from the code, v7 at 92d8025e):

  1. The plan cache is skipped on purpose: ClientEngine.ts L817-L823

    We do not cache createMany and createManyAndReturn queries 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.

  2. That variability comes from the plan's shape. For a 2-row createMany (dumped from the compile return value), the templateSql has one {"type":"parameter"} fragment per row × column (24 for 2 rows × 12 columns), with the VALUES (…), (…) separators as string chunks, and one let binding 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 isCacheableQuery would no longer need to exclude these actions.

Open points I can see but have not checked:

  • generated defaults (now(), cuid(), uuid(), …) are currently per-row let bindings; 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-row VALUES.
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

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from prisma/orm

All issues in prisma/orm

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.