How can I debug a memory leak on my Apollo GraphQL server?

江枫思渺然 提交于 2019-12-23 10:49:21

问题


I have a graphql server with multiple endpoints. It is basically just a CRUD app, so I'm honestly not sure why there's a memory leak. The only potentially leaky endpoint I have is one that uploads pics to S3.

I've been looking around and have tried taking heap snapshots and comparing them but I'm not even sure which endpoint is the culprit. This is the flow I've been following:

  1. Start the server with the --inspect flag: nodemon --inspect --exec babel-node src/index.js
  2. Take a heap snapshot before I do anything
  3. Start my front end app and hit the endpoint I think has the memory leak (the one where I upload a photo)
  4. Take a heap snapshot again and compare the two

Is this the correct flow for finding a memory leak? Is there a better way of doing this without having to guess which endpoint it is coming from? Are there perhaps tools I can use online that can help me find the source of the memory leak in production without having to guess like this? Perhaps something like Datadog or something?

Update: From Heroku's metrics, it looks like the memory usage increases every time a request is made?

But my src/index.js file doesn't do anything special:

import { ApolloServer, gql } from "apollo-server";
import { connectDb, models } from "./models";

import schema from "./schema";
import resolvers from "./resolvers";
import contexts from "./contexts";

const server = new ApolloServer({
  typeDefs: schema,
  resolvers,
  context: async ({ req, connection }) => {
    console.log(req.body.query);
    console.log(req.body.variables);

    const { getCurrentUser } = contexts;

    const currentUser = await getCurrentUser(req);
    return { models, currentUser };
  },
});

connectDb().then(async () => {
  server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
    console.log(`🚀  Server ready at ${url}`);
  });
});

回答1:


You are on the right path. The guide I'm about to link to begins by following a similar approach to the one you've taken. I'll link to the section that talks about monitoring memory in real time, which is available when you Record allocation timeline in chrome://inspect

https://marmelab.com/blog/2018/04/03/how-to-track-and-fix-memory-leak-with-nodejs.html#watching-memory-allocation-in-real-time




回答2:


You could try to use clinic in order to debug and profile the app. pretty good tool for nodeJS.




回答3:


You could user node-memwatch to detect where is memory leak.

It also might be a known issue, here is the link with a similar issue.



来源:https://stackoverflow.com/questions/58897099/how-can-i-debug-a-memory-leak-on-my-apollo-graphql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!