nodejs-firestore icon indicating copy to clipboard operation
nodejs-firestore copied to clipboard

HUGE memory leak problem

Open jakeleventhal opened this issue 7 years ago • 74 comments

Environment details

  • OS: Mac OS 10.15 Beta (19A573a)
  • Node.js version: v12.10.0
  • npm version: 6.10.3
  • @google-cloud/firestore version: 2.3.0

I'm still experiencing a memory leak potentially related to googleapis/gapic-generator-typescript#661. The following is from my yarn.lock:

"@grpc/grpc-js@^0.5.2":
  version "0.5.2"
  resolved "https://registry.yarnpkg.com/@grpc/grpc-js/-/grpc-js-0.5.2.tgz#8e39876033749e1611fe9fa181d9535077805abe"
  integrity sha512-NE1tP/1AF6BqhLdILElnF7aOBfoky+4ZOdZU/0NmKo2d+9F9QD8zGoElpBk/5BfyQZ3u1Zs+wFbDOFpVUzDx1w==
  dependencies:
    semver "^6.0.0"

"@grpc/proto-loader@^0.5.0", "@grpc/proto-loader@^0.5.1":
  version "0.5.1"
  resolved "https://registry.yarnpkg.com/@grpc/proto-loader/-/proto-loader-0.5.1.tgz#48492b53cdda353110b51a4b02f465974729c76f"
  integrity sha512-3y0FhacYAwWvyXshH18eDkUI40wT/uGio7MAegzY8lO5+wVsc19+1A7T0pPptae4kl7bdITL+0cHpnAPmryBjQ==
  dependencies:
    lodash.camelcase "^4.3.0"
    protobufjs "^6.8.6"

Quick note: because of the grpc problems that keep appearing here, we should probably put grpc version as part of the issue template

So it is clear that I'm actually using the "correct" grpc. My application makes many calls to firestore and I'm experiencing massive memory leaks. Screen Shot 2019-09-28 at 6 53 37 PM

I'm not actually seeing the error message described previously (MaxListenersExceededWarning), however, the memory usage on my application slowly and steady is increasing. I've taken several heap snapshots from local tests over the course of several hours and when comparing snapshots from a few hours apart, I notice that the top culprits for memory allocations are all related to grpc.

Here you can clearly see that the top 4 culprits for the memory delta between snapshots 12 and 4 are vastly more than everything else Screen Shot 2019-09-28 at 7 08 24 PM

Here are the contents of each from largest to smallest:

  1. (string): This by far is the fastest growing constructor. As you can see, there are 920k new allocations in the comparison between the two snapshots. Practically every single string here is ""(function anonymous( ) { return function BeginTransactionRequest(p){ if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null) this[ks[i]]=p[ks[i]] } })". And this all comes from message.js:13. This is a a file from the package protobufjs which is a dependency of grpc. Screen Shot 2019-09-28 at 7 47 17 PM

  2. (system): Essentially everything here seems to be coming from from the same message.js:13. Screen Shot 2019-09-28 at 7 29 51 PM I also have tens of thousands of objects that look like this (from grpc) Screen Shot 2019-09-28 at 8 10 43 PM

  3. (array): Practically every single array allocation here is a alloc size 32 and is linked to type.js:31 and namespace.js:95, both of which are also part of protobufjs. Screen Shot 2019-09-28 at 8 18 42 PM "Field" is also related to the same line numbers and is actually directly linked to grpc Screen Shot 2019-09-28 at 8 20 38 PM

  4. Array: There are 235k of these and they all look the same - Array with an alloc size of 32 with some connection to grpc Screen Shot 2019-09-28 at 7 12 35 PM

jakeleventhal avatar Sep 29 '19 02:09 jakeleventhal

Update: I tried updating to 0.5.4 based on the comments in this thread and it did not help

Here is the new yarn.lock:

"@grpc/grpc-js@^0.5.2":
  version "0.5.4"
  resolved "https://registry.yarnpkg.com/@grpc/grpc-js/-/grpc-js-0.5.4.tgz#20ee7880e69805cbc63a1c54a3af02cc6475c850"
  integrity sha512-aY4fTCz7jq7oKFmfAeZVqGzMCR5I9NLdY9E2fJ70QtGXwlJnTaN6cnbRmCk23/aKPx9UHqOtk2lyjpN6LbAaxw==
  dependencies:
    semver "^6.2.0"

"@grpc/proto-loader@^0.5.0", "@grpc/proto-loader@^0.5.1":
  version "0.5.2"
  resolved "https://registry.yarnpkg.com/@grpc/proto-loader/-/proto-loader-0.5.2.tgz#c84f83be962f518bc303ca2d5e6ef2239439786c"
  integrity sha512-eBKD/FPxQoY1x6QONW2nBd54QUEyzcFP9FenujmoeDPy1rutVSHki1s/wR68F6O1QfCNDx+ayBH1O2CVNMzyyw==
  dependencies:
    lodash.camelcase "^4.3.0"
    protobufjs "^6.8.6"

jakeleventhal avatar Sep 29 '19 03:09 jakeleventhal

If it is of any help, the way I use firestore is as follows:

I have a file called firestore.js that looks like this:

import Firestore from '@google-cloud/firestore';

export default new Firestore();

I then import firestore and use it in other places like this:

import firestore from './modules/firestore';

const updateThing = async (req, res) => {
  try {
    const { docId, updatePayload } = req.body;

    await firestore.doc(`Things/${docId}`).update(updatePayload);

    return res.status(200).send();
  } catch (err) {
    console.error(err);
    return res.status(500).send();
  }
};

I can probably have a temporary workaround by just creating a new Firestore instance from within each function body, but fixing the underlying problem is a more sustainable approach.

Also, my application doesn't have any event listeners. The only operations it uses are get(), set(), and update()

jakeleventhal avatar Sep 29 '19 20:09 jakeleventhal

@jakeleventhal Thanks for the very detailed issue! Can you describe your work load a bit? It would help to know how many requests you are sending and if the memory usage tapers off once those requests are processed.

schmidt-sebastian avatar Sep 30 '19 16:09 schmidt-sebastian

I have a couple of observations here:

The string that is being constructed almost a million times looks like a generated variant of the protobuf.js Message constructor that is specific to various message types from the .proto files in the Firestore library. The most likely reason for that happening is that the .proto files are getting loaded repeatedly. Other memory usage from protobuf.js probably has the same cause. The library @grpc/proto-loader is essentially just a proxy for protobuf.js, so memory leaks there probably also have the same cause.

The Http2Subchannel objects from grpc are probably the result of repeatedly constructing new clients, and that version of the grpc library tends to keep channels and subchannels alive even when they are not being used. This is improved in @grpc/grpc-js version 0.6.x, mainly because subchannels with identical parameters will be reused.

murgatroid99 avatar Sep 30 '19 18:09 murgatroid99

@schmidt-sebastian So I have an API server that accepts HTTP requests from a another scheduling server. The scheduling server repeatedly sends jobs to the API to save user data.

There are many operations that occur but, for the most part, they can all be summarized as this:

  1. Fetch a large data report from a 3rd party API
  2. Parse that data to do one of or both of the following:
  • a) Create a document with set()
  • b) Modify an existing document with update()

There can be anywhere from 1-1000 or so firestore calls per minute per user. Each document that is updated is unique so there is no contention going on here.

I also have used log statements to see that functions are entering and exiting (and they all more or less follow a similar structure to what I wrote above). The scope of the firestore calls should be limited to just the function. Moreover, the firestore calls aren't throwing errors or anything and are updating documents successfully. Again, there are no event listeners anywhere in my code.

I have also tried not using a single instance of Firestore that I import throughout my code - I tried creating a new instance of Firestore within the body of each function that uses firestore. I tracked the number of instances of Firestore objects through memory snapshots and was able to see that the Firestore objects were successfully being deleted/deallocated at the end of each function; however, the metadata with all those strings/arrays/objects still persisted outside the scope of the functions.

I hope that clears up everything.

jakeleventhal avatar Oct 01 '19 02:10 jakeleventhal

@jakeleventhal we've hit with this kinds of problems too in cloud functions: https://github.com/firebase/firebase-functions/issues/536

The problems originate from grpc-js, which is still experimental.

What worked for us in the end was to downgrade our dependencies so it still uses the binary grpc which is much more mature and stable.

There's also a mechanism to force firestore to use binary grpc with the newer client version described here: https://github.com/firebase/firebase-functions/issues/536#issuecomment-531923813, however I have not tested that one as it is unsupported / untested if I understood correctly. That note also explains a bit why we are in this mess.

So, after grpc-js matures a bit, we’ll hop back to the latest versions.

swftvsn avatar Oct 01 '19 07:10 swftvsn

@swftvsn what functionality will be lost/what differences will there be? also, what is the syntax with ‘@google-cloud/firestore’

jakeleventhal avatar Oct 01 '19 13:10 jakeleventhal

@swftvsn @schmidt-sebastian why is firestore not using the binary method of grpc until the other version is stable? what’s to be gained? this memory leak cost me close to $1k on gcp and is now a bottleneck for launching my product. i’m sure i’m not the only one experiencing issues like this

jakeleventhal avatar Oct 01 '19 13:10 jakeleventhal

@jakeleventhal The reasoning to use grpc-js is explained in this comment: https://github.com/firebase/firebase-functions/issues/536#issuecomment-531923813

We didn't lose any functionality we need when switching to earlier version, but of course we just checked everything we need. (We use typescript, so basically everything compiles -> you're good to go. ymmw etc. ofcourse.)

swftvsn avatar Oct 01 '19 14:10 swftvsn

Providing a different GRPC implementation via the constructor argument (as described in https://github.com/firebase/firebase-functions/issues/536#issuecomment-531923813) is fully supported. All currently available features in Firestore are compatible with both grpc and @grpc/grpc-js.

@murgatroid99 Do you have a rough idea of where in our stack this problem might best be addressed?

schmidt-sebastian avatar Oct 01 '19 17:10 schmidt-sebastian

I'm only really familiar with my end of the stack, so I can only say that it's somewhere above that. Probably this firestore library. Loading the same .proto file repeatedly is not an intended usage of @grpc/proto-loader, so I recommend that you find a way to load it only once per process.

Similarly, constructing many clients for the same service and backend is not the intended usage of either grpc library, but that should be a much smaller problem with the new release of grpc-js that gax should be picking up soon.

murgatroid99 avatar Oct 01 '19 18:10 murgatroid99

I spent some more time on this, but I am still not able to pinpoint the leak. What is interesting though is that this only seems to happen with set()/update()/delete() and not with a get() call.

After 2000 operations, my memory Profile looks like this:

Screen Shot 2019-10-01 at 2 50 05 PM

The memory usage does not go down even when all operations resolve.

schmidt-sebastian avatar Oct 01 '19 22:10 schmidt-sebastian

Is this confirmed to be fixed using the regular grpc library? i.e.

import grpc from 'grpc'

const firestore = new Firestore({ grpc })

jakeleventhal avatar Oct 02 '19 02:10 jakeleventhal

@schmidt-sebastian I don't know if it's related, but there is a similar issue in BigQuery: https://github.com/googleapis/nodejs-bigquery/issues/547

merlinnot avatar Oct 02 '19 06:10 merlinnot

@jakeleventhal I see similar memory profiles with both grpc and @grpc/grpc-js.

schmidt-sebastian avatar Oct 02 '19 15:10 schmidt-sebastian

It looks like the memory leak happens in one of our depend layers, so it might take a bit of work to track this down. The memory leak also exist when the Veneer client (which is an auto-generated SDK that we use for our request logic) is used directly. What is somewhat interesting is that we only seem to be leaking memory once we get responses from the backend - I see a steady increase of memory consumption only after requests are starting to get fulfilled.

With 2000 writes, FirestoreClient_innerApiCalls has a retained size of 99680 bytes that is mostly unaccounted for. There are also 2000 PromiseWrap and Promise objects on the stack that take up roughly this amount of memory.

schmidt-sebastian avatar Oct 02 '19 15:10 schmidt-sebastian

Great to see the investigation resulting some fruit @schmidt-sebastian - and sorry that I jumped to conclusion and thus wrote bs above..

swftvsn avatar Oct 02 '19 15:10 swftvsn

@schmidt-sebastian There is definitely a huge improvement using the legacy grpc (new Firestore({ grpc })). It's orders of magnitude different. These are tests run (with the exact same traffic/load)

grpc-js Screen Shot 2019-10-02 at 8 57 08 PM

grpc Screen Shot 2019-10-02 at 8 56 40 PM

You'll notice the memory is still climbing in the second example - but its very very minimal compared to the grpc-js version

jakeleventhal avatar Oct 03 '19 03:10 jakeleventhal

How are you measuring the memory usage? If you are using a JavaScript memory profiler, it may be omitting memory allocations by native code, which account for the majority of the memory usage of grpc.

murgatroid99 avatar Oct 03 '19 07:10 murgatroid99

The screenshots in the original post that show the memory profiler are using the chrome memory tool when running with the —inspect flag. The screenshots provided of the memory graph are the memory usage of my application on GKE

jakeleventhal avatar Oct 03 '19 07:10 jakeleventhal