Skip to content

Instantly share code, notes, and snippets.

@diaswrd
Last active August 4, 2016 20:01
Show Gist options
  • Save diaswrd/e84ea1043b120848bea1f9a5e1faeb62 to your computer and use it in GitHub Desktop.
Save diaswrd/e84ea1043b120848bea1f9a5e1faeb62 to your computer and use it in GitHub Desktop.
API Memory Leaks cause

API Memory Leaks

So, I think I finally understand why this is happening when our APIs start:

image

This is not being caused by the huge amount of before/after remote calls in our main API like we first thought. It is instead caused by the amount of multiple before/afteRemotes on the same remote method (endpoint).

How to Fix

So, I got into the line described in the stack trace: at module.exports (/Users/diaswrd/dev/nanopay/api/modules/mintchip/remoteMethods/invites.js:66:11)

And look what I found there:

invites.beforeRemote('updateInviteById', checkInviteOwnership);
invites.beforeRemote('updateInviteById', checkInviteeAccepted);

// check if phoneNumber is in request
invites.beforeRemote('updateInviteById', function(ctx, instance, next) {
  var body = ctx.args.data;

  if (!body.phoneNumber) {
    return next({ status: 422, message: 'Invalid request' });
  }

  return next();
});

Yeah, that's right, three beforeRemote hooks for the same invites.updateInviteById. So I applied this small refactoring:

invites.beforeRemote('updateInviteById', function(ctx, instance, next) {
  async.series([
    function (cb) {
      checkInviteOwnership(ctx, instance, cb);
    },
    function (cb) {
      checkInviteeAccepted(ctx, instance, cb);
    },
  ], function (err) {
    if (err) {
      return next(err);
    }

    var body = ctx.args.data;

    if (!body.phoneNumber) {
      return next({ status: 422, message: 'Invalid request' });
    }

    next();
  });
});

Now, the memory leak warning for invites is gone and unit tests for mintchip/test/pendingInvites.js are still passing.

However, we still have one warning for /user/remoteMethods/user.js and when checking this file, I found 16 beforeRemotes and 15 afterRemotes, some of them duplicated, so it will be even more painful fun to rewrite.

Conclusion

Do not duplicate beforeRemote or afterRemote hooks, ever. Every time you do that, an angel cry blood and a new civil war starts in Africa. Please, be a good person.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment