prisma: Memory leak with RSS on concurrent query's with a larger dataset.

Bug description

My stack i am using NodeJS 20.17 + NestJS 10.4 + Prisma v5.20

The problem is a high usage of RSS in comparison to the heap. I noticed this problem in our AWS environment (we are using ECS) first, the problem happens on our service application, where we have multiple services running that reads and writes to the DB from our app. The service started crashing and then started becoming more frequent (i scaled the service all the way upto 32 gb ram and the crashes become less frequent but still happen)

I also did a profiling of the app on my local and here is the RSS usage of the app. image

The only way i was able to reproduce this was to get the dataset size from our prod env and then have it run locally on my workstation ( it even crashed my workstation once). You need to have certain amount of data being queried frequently that causes this leak.

Something in the driver is going wrong with async or concurrent requests (i even tried the new experimental feature with pg driver to see if it fixed the issue in my case but it did not) which i believe is the primary cause. At first i though it might be a node.js container issue with alpine/bookworm/bullseye but the only thing those change is the system garbage collection that manages RSS but something on the system in being retained that could be problematic as i was able to reproduce it on my system (ubuntu desktop) too.

Would like to here from anyone having similar issues or problems. Few relevant issues i found : https://github.com/prisma/prisma/issues/23881 https://github.com/prisma/prisma/issues/23661

How to reproduce

This is a little problematic, as there are no direct steps to do so. The only thing i can think of is using a similar desing pattern as we have:

  1. NestJS CronJob (run multiple cron jobs in parallel) ->
  2. Let each cron job (we make sure that no single cron of the same type is running in parallel, so they can only run if the previous job is finished) query a table with linked tables of size at least 50k-100k data points, you don’t need all the data just subset lets say last 10k data points (or 1 day worth of data)
  3. Process that data.
  4. Add data back to other tables with the processed data.

Expected behavior

Usually the RSS should go high then clear out, but the RSS stays extremely persistent and usually causes the system to crash. From my understanding the RSS is not being cleared as the NodeJS process is not responsible to clear it but the system core is responsible for clearing it, but something is making this exists in memory that blocks it from being cleared immediately after use.

Prisma information

// Add your schema.prisma
// Add your code using Prisma Client

---- Happy to share this more in a private setting with maintainers of the repo if you would like.

Environment & setup

  • OS: Prod runs in AWS ECS (node:20.17.0-bullseye) and local i have an Ubuntu 24.04 version.
  • Database: We use Aurora Postgress 15.4 on our main environments and Postgress Docker on local (v15).
  • Node.js version: 20.17 LTS

Prisma Version

My Local Build:

prisma                  : 5.20.0
@prisma/client          : 5.20.0
Computed binaryTarget   : debian-openssl-3.0.x
Operating System        : linux
Architecture            : x64
Node.js                 : v20.17.0
Query Engine (Node-API) : libquery-engine 06fc58a368dc7be9fbbbe894adf8d445d208c284 (at node_modules/@prisma/engines/libquery_engine-debian-openssl-3.0.x.so.node)
Schema Engine           : schema-engine-cli 06fc58a368dc7be9fbbbe894adf8d445d208c284 (at node_modules/@prisma/engines/schema-engine-debian-openssl-3.0.x)
Schema Wasm             : @prisma/prisma-schema-wasm 5.20.0-12.06fc58a368dc7be9fbbbe894adf8d445d208c284
Default Engines Hash    : 06fc58a368dc7be9fbbbe894adf8d445d208c284
Studio                  : 0.502.0
Done in 1.00s.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 1
  • Comments: 16 (1 by maintainers)

Most upvoted comments

Just adding that we too are experiencing something similar to this issue; We’ve narrowed it down to a simple findMany query in one of our cron tasks:

const inviteJourney = await prisma.inviteJourney.findMany({
  orderBy: { createdAt: 'desc' },
});

We’re running this query once a day for a batch export / reporting job, the table’s size at time of writing is 52mb (35,630 rows), but RSS grows from 254mb to 775mb (!). We’ve logged the output of process.memoryUsage() before and after this query and those are the values.

This memory does not get collected, and remains at the same level throughout the day. If the same pod then runs another scheduled task, we hit our memory limit and the pod restarts.

Originally we suspected a memory leak somewhere in our application code, but the above results are odd.

We’ll try querying the full results set using pagination, but an increase of ~500mb for a table 10x smaller than that is strange indeed.

For more context, we’re using Postgres, and the Schema for that table is very simple:

model InviteJourney {
  id                  Int       @id @default(autoincrement())
  inviteCode          String?
  sessionId           String?   @unique
  customerId          String?
  checkoutId          String?
  cartId              String?
  orderId             String?
  stepId              String?
  fields              String[]
  values              String[]
  scentProfile        String[]
  fragranceFamily     String[]
  fragranceUsage      String?
  fragranceAppeal     String[]
  fragranceTaste      String[]
  genderIdentity      String?
  ownedFragrances     String[]
  selfDescription     String?
  demographic         String?
  customerCohort      String?
  emailAddress        String?
  marketingConsent    Boolean   @default(false)
  emailForLater       Boolean   @default(false)
  createdAt           DateTime  @db.Timestamptz(6)
  updatedAt           DateTime? @updatedAt

  @@index(fields: [inviteCode])
  @@index(fields: [customerId])
  @@index(fields: [orderId])
}

Thanks!

We thought we had the same problem with a memory leak as we had a nightly batch job that would make a large number of queries on a large dataset.

For us, it turned out there were many times where we made updates and deletes with empty inputs (ie, update/delete all these records, passing an array of record ids, but the array was empty).

At the application layer we made the code change to avoid making queries when the input was empty thinking it probably wasn’t going to have much of an improvement, but just something we should’ve done anyway, and the problem went away.

Anyway, unlikely to be the issue for most people here, but on the off chance it might have been an oversight for anyone else like it was for us, I thought I would mention it as it has resolved our memory leak issue.

Why this seems to have caused a memory leak we still do not know, and that could still be related to whatever resolves this issue.

Ok i am gonna add additional context here, as my first point that this is just related to to nested table filters may be incorrect.

I have another case where i have this function being called from a grpahql resolver:

async findAll(
    queryParams: TokenPriceHistoryQueryParams,
  ): Promise<TokenPriceHistory[]> {
    const { skip, take = 100000, cursor, where, orderBy } = queryParams;
    return this.prisma.tokenPriceHistory.findMany({
      skip,
      take,
      cursor,
      where,
      orderBy,
      include: {
        Token: true,
      },
    });
  }

Note this is a big table and if i just run this my RSS spikes to 15 gb (although the table size should not bigger than 100 MB (edit closer to 300MB) as i only have 3 million entries in the DB), for testing purposes i set the take to 100,000 so that the query would resolve itself.

I profiled the query on my local and here are the results:

image

My interceptor for this query

Memory stats: {
  rss: '184.56 MB',
  heapTotal: '101.17 MB',
  heapUsed: '59.97 MB',
  external: '3.28 MB'
}
[Nest] 1008319  - 2024-10-11, 11:29:33 a.m.     LOG [LoggingInterceptor] Memory Usage (Before) - RSS: 183.84 MB, HeapTotal: 100.42 MB, HeapUsed: 61.82 MB, External: 3.30 MB
[Nest] 1008319  - 2024-10-11, 11:29:33 a.m.     LOG [LoggingInterceptor] Incoming request for TokenPriceHistoryResolver -> tokenPriceHistories with args: {}
Memory stats: {
  rss: '283.91 MB',
  heapTotal: '100.42 MB',
  heapUsed: '63.16 MB',
  external: '3.28 MB'
}
Memory stats: {
  rss: '628.16 MB',
  heapTotal: '99.67 MB',
  heapUsed: '62.38 MB',
  external: '3.29 MB'
}
Memory stats: {
  rss: '940.58 MB',
  heapTotal: '99.00 MB',
  heapUsed: '46.82 MB',
  external: '3.27 MB'
}
Memory stats: {
  rss: '1175.22 MB',
  heapTotal: '99.67 MB',
  heapUsed: '61.93 MB',
  external: '3.28 MB'
}
[Nest] 1008319  - 2024-10-11, 11:29:57 a.m.     LOG [LoggingInterceptor] Completed request for TokenPriceHistoryResolver -> tokenPriceHistories in 24249ms
[Nest] 1008319  - 2024-10-11, 11:29:57 a.m.     LOG [LoggingInterceptor] Memory Usage (After) - RSS: 1379.06 MB, HeapTotal: 414.88 MB, HeapUsed: 387.02 MB, External: 3.26 MB
[Nest] 1008319  - 2024-10-11, 11:29:57 a.m.     LOG [LoggingInterceptor] Memory Difference - RSS: 1195.21 MB, HeapTotal: 314.46 MB, HeapUsed: 325.20 MB, External: -0.03 MB, for the resolver TokenPriceHistoryResolver
Memory stats: {
  rss: '2020.97 MB',
  heapTotal: '1040.71 MB',
  heapUsed: '1005.84 MB',
  external: '3.26 MB'
}
Memory stats: {
  rss: '2031.10 MB',
  heapTotal: '1065.14 MB',
  heapUsed: '1020.41 MB',
  external: '3.29 MB'

Note the Memory spike i can understand that the query is being processed on a table of large size. What i don’t understand is why

  1. RSS usage goes from 200 MB to 2 GB to query this table.
  2. After the query is completed, the RSS and even the heap don’t return to the original amounts but persist in some amounts in the memory (note i have a cache in my graphql so the heap persisting for a bit longer makes sense to me but not the RSS). The RSS was not cleared up immediately even though the query had been completed. I get the garbage collector of the system should be at work for the RSS, but it seems like something sticky is left behind, making this memory persistently.

For testing purposes, I removed the include section in the above query, and I see a difference in RSS and heap usage, too as i guess it does not have to query another table. Here is an interceptor I have on my grahql query.

Memory stats: {
  rss: '180.98 MB',
  heapTotal: '98.92 MB',
  heapUsed: '60.90 MB',
  external: '3.29 MB'
}
[Nest] 974543  - 2024-10-11, 10:55:17 a.m.     LOG [LoggingInterceptor] Memory Usage (Before) - RSS: 180.89 MB, HeapTotal: 98.92 MB, HeapUsed: 58.78 MB, External: 3.27 MB
[Nest] 974543  - 2024-10-11, 10:55:17 a.m.     LOG [LoggingInterceptor] Incoming request for TokenPriceHistoryResolver -> tokenPriceHistories with args: {}
Memory stats: {
  rss: '404.27 MB',
  heapTotal: '98.25 MB',
  heapUsed: '46.88 MB',
  external: '3.27 MB'
}
[Nest] 974543  - 2024-10-11, 10:55:23 a.m.     LOG [LoggingInterceptor] Completed request for TokenPriceHistoryResolver -> tokenPriceHistories in 5819ms
[Nest] 974543  - 2024-10-11, 10:55:23 a.m.     LOG [LoggingInterceptor] Memory Usage (After) - RSS: 614.71 MB, HeapTotal: 229.36 MB, HeapUsed: 203.36 MB, External: 3.26 MB
[Nest] 974543  - 2024-10-11, 10:55:23 a.m.     LOG [LoggingInterceptor] Memory Difference - RSS: 433.82 MB, HeapTotal: 130.44 MB, HeapUsed: 144.58 MB, External: -0.01 MB, for the resolver TokenPriceHistoryResolver
Memory stats: {
  rss: '907.21 MB',
  heapTotal: '505.00 MB',
  heapUsed: '401.81 MB',
  external: '3.26 MB'
}
Memory stats: {
  rss: '893.13 MB',
  heapTotal: '505.00 MB',
  heapUsed: '402.09 MB',
  external: '3.31 MB'
}
...(some similar stats)
Memory stats: {
  rss: '897.65 MB',
  heapTotal: '509.92 MB',
  heapUsed: '476.81 MB',
  external: '3.30 MB'
}
Memory stats: {
  rss: '905.77 MB',
  heapTotal: '518.75 MB',
  heapUsed: '476.53 MB',
  external: '3.31 MB'
}
....(some more similar stats)
Memory stats: {
  rss: '965.93 MB',
  heapTotal: '578.00 MB',
  heapUsed: '534.92 MB',
  external: '3.35 MB'
}
Memory stats: {
  rss: '497.91 MB',
  heapTotal: '133.00 MB',
  heapUsed: '97.04 MB',
  external: '3.27 MB'
}
Memory stats: {
  rss: '515.10 MB',
  heapTotal: '126.82 MB',
  heapUsed: '91.12 MB',
  external: '3.26 MB'
}
Memory stats: {
  rss: '516.25 MB',
  heapTotal: '143.16 MB',
  heapUsed: '101.58 MB',
  external: '3.27 MB'
} ... more memory stats similar 

Profiler: image

One thing to note is that RSS usage also increased after the query was completed. I’m not sure if it’s one problem or multiple interrelated problems.

From a quick scan of our codebase, which uses Prisma everywhere, there seems to be no correlation between nested WHEREs and memory usage for us. Memory grows linearly after startup for all our nodes across all our services using Prisma. It looks to be a deeper issue with memory management in the library.

We’re trying to mitigate RSS OOM by setting BUN_JSC_forceRAMSize for Bun services and NODE_OPTIONS="--max-old-space-size=..." for Node services. Stay tuned on if it helps at all.