Skip to content

Memory grows without limit when $transaction([...]) batches vary in shape #30487

Open

Description

@s-minav

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 createMany get a new cache entry for every distinct row
    count. The single-query path already skips caching for createMany;
    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

  1. added
    bug/1-unconfirmed
    kind/bug
    on Sep 29, 2026
  2. DanielHabenichtWork commented on Oct 8, 2026

    @DanielHabenichtWork

    We hit the same thing with createMany inside an array-form $transaction, on @prisma/client 7.10.0 with @prisma/adapter-pg (Node 24).

    Our background job replaces the rows of ~1,000 groups, one batch per group:

    await prisma.$transaction([
      prisma.entry.deleteMany({ where: { groupId, date: { gte: since } } }),
      prisma.entry.createMany({ data: rows }), // 300–3,600 rows, a different count 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"), but requestBatch stores 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 xxxMany functions 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.

  3. MappleTVGit commented on Oct 18, 2026

    @MappleTVGit

    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 createMany inside 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:

    await prisma.$transaction([
      prisma.accessLogEntry.createMany({ data: rows }), // ~9,500 rows per run, count differs every time
      prisma.accessLogPosition.upsert({ where: { datei }, update: { inode, position }, create: { datei, inode, 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):

    • Sampling heap profile over 2 h: 35 MB of 43 MB live sampled allocations were allocated under compileBatch (query_compiler_fast_bg.js) called from requestBatch in the client runtime — i.e. the compiled batch plans are what is being retained, ~17 MB/h.
    • Object histogram (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.
    • The built runtime confirms the asymmetry: request() skips getSingle/setSingle when action is createMany/createManyAndReturn, while requestBatch() always does this.#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(...) })) routes createMany through 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 in requestBatch), and ideally bounding the cache by size rather than entry count. Note that #30494 (debug argsHistory keeping 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.

  4. jakwuh commented on Oct 22, 2026

    @jakwuh

    Another variant of this, where the batch shape does not vary: a fixed-size createMany plus one $executeRaw in an array-form $transaction. createMany alone in the batch stays flat, but adding a tagged-template $executeRaw whose 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 full createMany plan.

    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-pg 7.10.0, pg 8.23.1, Node 24.21.0 (alpine), PostgreSQL 17.

    Minimal reproduction

    schema.prisma:

    generator client {
      provider = "prisma-client"
      output   = "./generated"
    }
    
    datasource db {
      provider = "postgresql"
    }
    
    model Message {
      id   Int    @id
      body String
    }
    
    model Cursor {
      id     Int @id
      lastId Int
    }

    repro.ts (node --expose-gc repro.ts batch|batch-no-raw|interactive):

    // node --expose-gc repro.ts <batch|batch-no-raw|interactive>
    import { PrismaPg } from "@prisma/adapter-pg";
    import { PrismaClient } from "./generated/client.ts";
    
    const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }) });
    const mode = process.argv[2] ?? "batch";
    const heap = () => { global.gc!(); return (process.memoryUsage().heapUsed / 1048576).toFixed(0); };
    
    await prisma.$executeRaw`CREATE TABLE IF NOT EXISTS "Message" (id int PRIMARY KEY, body text NOT NULL)`;
    await prisma.$executeRaw`CREATE TABLE IF NOT EXISTS "Cursor" (id int PRIMARY KEY, "lastId" int NOT NULL)`;
    
    for (let page = 0; page <= 600; page++) {
      if (page % 100 === 0) console.log(mode, "page", page, "heapUsed", heap(), "MB");
      // Always exactly 100 rows: the batch shape never changes.
      const data = Array.from({ length: 100 }, (_, i) => ({ id: page * 100 + i, body: "x".repeat(2000) }));
      const cursor = page * 100 + 99;
      if (mode === "interactive") {
        await prisma.$transaction(async (tx) => {
          await tx.message.createMany({ data, skipDuplicates: true });
          await tx.$executeRaw`INSERT INTO "Cursor" VALUES (1, ${cursor}) ON CONFLICT (id) DO UPDATE SET "lastId" = EXCLUDED."lastId"`;
        });
      } else if (mode === "batch-no-raw") {
        await prisma.$transaction([prisma.message.createMany({ data, skipDuplicates: true })]);
      } else {
        await prisma.$transaction([
          prisma.message.createMany({ data, skipDuplicates: true }),
          prisma.$executeRaw`INSERT INTO "Cursor" VALUES (1, ${cursor}) ON CONFLICT (id) DO UPDATE SET "lastId" = EXCLUDED."lastId"`,
        ]);
      }
    }
    await prisma.$disconnect();

    Output (heapUsed after GC, MB):

    page [createMany, $executeRaw] [createMany] interactive
    0 16 16 16
    200 34 17 15
    400 55 17 15
    600 75 17 15

    ~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 or createMany, or bounds the cache by size, would cover this case too.

  5. prisma-asks commented on Oct 22, 2026

    @prisma-asks

    @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

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

    bug/1-unconfirmedkind/bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions