Repository navigation
Description
Package and version
@prisma/[email protected]
What happened?
Our API ran out of heap roughly every 29 hours after moving to Prisma 7.
We traced it to the query plan cache: every $transaction([...]) whose
shape changes from call to call adds a new entry that is never reused,
and large batches make each entry several megabytes.
By "shape" I mean anything that survives parameterization: the number of
queries in the batch, and whether a field is null or a value. A batch
built from data - e.g. rows.map(r => prisma.x.upsert(...)) - almost
never repeats its shape, so almost every call is a cache miss that gets
stored.
The cache is limited to 1000 entries, but not by size. With ~450 upserts
per batch each entry is ~10 MB, so the process runs out of memory long
before the limit matters.
What did you expect to happen?
The cache should not be able to exhaust memory. Some options:
- don't cache batch plans at all, or not above N queries;
- limit the cache by size instead of entry count.
Minimal reproduction
Schema:
model Metric {
key String
hour DateTime
checks Int
latency Int?
speed Int?
@@id([key, hour])
}Script (node --expose-gc repro.js):
const { PrismaClient } = require('@prisma/client');
const { PrismaMariaDb } = require('@prisma/adapter-mariadb');
const prisma = new PrismaClient({
adapter: new PrismaMariaDb({ host: '127.0.0.1', port: 3306, user: 'root', password: 'pw', database: 'repro' }),
});
const rows = () => Array.from({ length: 400 + Math.floor(Math.random() * 70) }, (_, i) => ({
key: `k${i % 20}-${Math.floor(i / 20)}`,
hour: new Date(Date.UTC(2026, 0, 1, i % 24)),
checks: 4,
latency: Math.random() < 0.2 ? null : 80,
speed: Math.random() < 0.7 ? null : 90000,
}));
const upsert = (db, r) => db.metric.upsert({
where: { key_hour: { key: r.key, hour: r.hour } },
create: r,
update: { checks: r.checks, latency: r.latency, speed: r.speed },
});
(async () => {
for (let i = 0; i <= 40; i++) {
if (i % 4 === 0) {
global.gc();
console.log(i, (process.memoryUsage().heapUsed / 1048576).toFixed(1), 'MB');
}
await prisma.$transaction(rows().map((r) => upsert(prisma, r)));
}
await prisma.$disconnect();
})();The table starts empty; the script fills it itself.
Output on 7.10.0 (heapUsed after GC, MB):
| batch # | $transaction([...]) |
interactive $transaction(async tx => …) |
|---|---|---|
| 0 | 8.0 | 8.0 |
| 8 | 99.7 | 14.2 |
| 16 | 171.8 | 14.4 |
| 24 | 249.8 | 14.4 |
| 32 | 330.7 | 14.5 |
| 40 | 408.8 | 14.6 |
~10 MB is retained per batch with the array form. The interactive variant
writes exactly the same rows, one await at a time
($transaction(async (tx) => { for (const r of rows) await upsert(tx, r) })),
and stays flat.
Environment
- @prisma/client 7.10.0, @prisma/adapter-mariadb 7.10.0, mariadb 3.4.5
- MariaDB 12.3
- Node.js 24
- OS: Linux (Debian 12, Docker) in production, Windows 11 for the repro
Additional context
- Batches with
createManyget a new cache entry for every distinct row
count. The single-query path already skips caching forcreateMany;
the batch path doesn't. - Maybe related to Upgrading from 7.3.0 to 7.4.1 increased memory usage #29294 (OOM after 7.3.0 → 7.4.1), but I haven't
verified that. - Workaround: interactive transactions with sequential awaits for
data-dependent writes.
Activity
DanielHabenichtWork commentedon Oct 8, 2026
We hit the same thing with
createManyinside an array-form$transaction, on@prisma/client7.10.0 with@prisma/adapter-pg(Node 24).Our background job replaces the rows of ~1,000 groups, one batch per group:
From a heap dump:
… ← plans ← (Map table) ← #t (QueryPlanCache, batch map) ← #o ← _engine (PrismaClient)
Seems like createMany is still cached since: #29382 (7.8.0) skips caching createMany in the single-query path (
action !== "createMany" && action !== "createManyAndReturn"), butrequestBatchstores every batch plan via setBatch without that check.Since the cache key is the parameterized batch, every distinct row count is a new entry, and each entry holds per-row parameter descriptors, here ~2 MB per batch. With the default limit of 1,000 entries that is ~2 GB before anything is evicted, which matches where our job died.
Ignoring
xxxManyfunctions for batch transaction would be sufficient for me.Workaround from issue author works and I can only second a hard limit on actual size instead of count.
MappleTVGit commentedon Oct 18, 2026
Independent confirmation on @prisma/client 7.9.1 + @prisma/adapter-pg 7.9.1 (Postgres 16, Node 22.23.2 on Alpine arm64, Next.js 16.4 standalone), same mechanism as described above for
createManyinside an array-form$transaction.Pattern. A cron job imports Apache access logs every 15 minutes and writes each batch atomically together with its read position:
Symptoms. Heap grew by ~300 MB/day and never came back; the process died every 1.5–2 days with
FATAL ERROR: Reached heap limit(default V8 limit ≈ 550 MB on a 4 GB box).Evidence from the running process (inspector attached via
SIGUSR1, no restart):compileBatch(query_compiler_fast_bg.js) called fromrequestBatchin the client runtime — i.e. the compiled batch plans are what is being retained, ~17 MB/h.Runtime.queryObjects) after 5 h of uptime: 816k plain objects vs. 59k right after start. Among them 28 arrays with 9,500–19,000 elements of shape{ type: "stringChunk", chunk }, plus matching arrays of{ arity, scalarType, dbType }and{ prisma__type, prisma__value }— one set per cron run (the 19k ones are runs that also processed a rotated log file). That matches the batch plan cache holding one multi-megabyte entry per distinct row count.request()skipsgetSingle/setSinglewhenactioniscreateMany/createManyAndReturn, whilerequestBatch()always doesthis.#i?.setBatch(JSON.stringify(parameterizedBatch), plan)with no action check. Default LRU size is 1000 entries, so the limit never kicks in before the heap is gone.Workaround confirmed. Switching that one call site to an interactive transaction (
$transaction(async (tx) => { await tx.accessLogEntry.createMany(...); await tx.accessLogPosition.upsert(...) })) routescreateManythrough the single-query path, which bypasses the cache. After deploying this, the process starts at ~130 MB and the per-run growth is gone (I can add the 48 h curve from our 15-minute memory log if useful).+1 for not caching batch plans that contain
createMany/createManyAndReturn(mirroring #29382 inrequestBatch), and ideally bounding the cache by size rather than entry count. Note that #30494 (debugargsHistorykeeping the last ~25 plans) still retains a bounded amount of these large plans even when the cache is bypassed, so both together explain the "high but stable" floor after the workaround.jakwuh commentedon Oct 22, 2026
Another variant of this, where the batch shape does not vary: a fixed-size
createManyplus one$executeRawin an array-form$transaction.createManyalone in the batch stays flat, but adding a tagged-template$executeRawwhose parameter changes every call makes the heap grow linearly — presumably the raw query's values end up in the batch cache key, so every call is a new entry that also holds the fullcreateManyplan.In production this was a paging sync job (100 rows per page + a cursor upsert via
$executeRaw): ~3–5 KB retained per row, the container (512 MB heap) died with OOM. Locally, 1200 pages × 100 rows: 485 MB heap after GC with the batch, 28 MB with an interactive transaction. A batch of just[createMany, $executeRaw`SELECT ${p}`]still reached 462 MB, while[createMany]alone stayed at 59 MB.Versions:
@prisma/client/prisma/@prisma/adapter-pg7.10.0,pg8.23.1, Node 24.21.0 (alpine), PostgreSQL 17.Minimal reproduction
schema.prisma:repro.ts(node --expose-gc repro.ts batch|batch-no-raw|interactive):Output (heapUsed after GC, MB):
[createMany, $executeRaw][createMany]~100 KB retained per batch here (2 KB rows); with wider rows it scales accordingly.
Workaround (same as above): interactive
$transaction(async (tx) => …)— flat. A fix that skips caching batch plans containing raw queries orcreateMany, or bounds the cache by size, would cover this case too.prisma-asks commentedon Oct 22, 2026
@s-minav @DanielHabenichtWork @MappleTVGit @jakwuh Others have asked for this too, so we're tracking it together with their reports. We're working on this. It's tracked as PR #29785: bound QueryPlanCache batch memory by total query plans, which is open. We'll post updates here and at https://asks.prisma.cool/public/asks/01a0ef13-8398-701f-bbea-927a65427416