Skip to content

MaxListenersExceededWarning: Possible EventEmitter memory leak detected #577

Closed

Description

@aankur

Hi ,

i am using mysql2 with bluebird on nodejs 8.

as

const mysql = require('mysql2/promise');
const Promise = require("bluebird");
config.Promise = Promise;//plus database connection configuration
pool = mysql.createPool(config);

function  GetSqlConnection() {
    return  pool.getConnection().disposer(function(connection) {
        connection.release();
    });
};

after sometime i get hit by this warning,
i get , 11 end listeners added. 11 drain listeners added etc ...

at _addListener (events.js:281:19)
    at PoolConnection.addListener (events.js:298:10)
    at /home/test/servers/v6/project/node_modules/mysql2/promise.js:8:14
    at Array.forEach (native)
    at inheritEvents (/home/test/servers/v6/project/node_modules/mysql2/promise.js:7:6)
    at new PromiseConnection (/home/test/servers/v6/project/node_modules/mysql2/promise.js:37:3)
    at /home/test/servers/v6/project/node_modules/mysql2/promise.js:228:17
    at /home/test/servers/v6/project/node_modules/mysql2/lib/pool.js:36:14
    at _combinedTickCallback (internal/process/next_tick.js:95:7)
    at process._tickCallback (internal/process/next_tick.js:161:9)
---------------------------------------------
    at process.emitWarning (internal/process/warning.js:154:18)
    at _addListener (events.js:289:17)
    at PoolConnection.addListener (events.js:298:10)
    at /home/test/servers/v6/project/node_modules/mysql2/promise.js:8:14
    at Array.forEach (native)
    at inheritEvents (/home/test/servers/v6/project/node_modules/mysql2/promise.js:7:6)
    at new PromiseConnection (/home/test/servers/v6/project/node_modules/mysql2/promise.js:37:3)
    at /home/test/servers/v6/project/node_modules/mysql2/promise.js:228:17
    at /home/test/servers/v6/project/node_modules/mysql2/lib/pool.js:36:14
    at _combinedTickCallback (internal/process/next_tick.js:95:7)
    at process._tickCallback (internal/process/next_tick.js:161:9)
---------------------------------------------
    at Pool.getConnection (/home/test/servers/v6/project/node_modules/mysql2/lib/pool.js:35:20)
    at /home/test/servers/v6/project/node_modules/mysql2/promise.js:224:14
    at Promise._execute (/home/test/servers/v6/project/node_modules/bluebird/js/release/debuggability.js:300:9)
    at Promise._resolveFromExecutor (/home/test/servers/v6/project/node_modules/bluebird/js/release/promise.js:483:18)
    at new Promise (/home/test/servers/v6/project/node_modules/bluebird/js/release/promise.js:79:10)
    at PromisePool.getConnection (/home/test/servers/v6/project/node_modules/mysql2/promise.js:223:10)
    at Db.GetSqlConnection (/home/test/servers/v6/project/db.js:34:23)
    at Db.verify (/home/test/servers/v6/project/db.js:254:31)

Activity

  1. sidorares commented on Jun 2, 2017

    @sidorares
    Owner

    thanks for report @aankur

    might be side effect of #567 @Myhlamaeus can you have a look?

  2. sidorares commented on Jun 2, 2017

    @sidorares
    Owner

    @aankur could you reduce your case to something completely self contained?

  3. aankur commented on Jun 2, 2017

    @aankur
    Author
    "use strict";
    const ini = require('ini');
    const fs = require("fs");
    const config = ini.parse(fs.readFileSync('./config.ini', 'utf-8'));
    const Db = require("./db.js")(config.db);
    
    
    async function test()
    {
            for(let i=0;i<20;i++)
            {
                    await Db.Verify("abcd");
            }
    }
    
    test();

    db access file

    "use strict";
    const Promise = require("bluebird");
    const mysql = require('mysql2/promise');
    const Db = function (config) {
        this.config = config;
        this.config.Promise = Promise;
        this.pool = mysql.createPool(this.config);
    };
    
    module.exports = function (config) {
        return new Db(config);
    };
    
    Db.prototype.GetSqlConnection = function () {
        return  this.pool.getConnection().disposer(function(connection) {
            connection.release();
        });
    };
    
    Db.prototype.Verify= function VerifyRoom(email)
    {
    
        return Promise.using(this.GetSqlConnection(), async (connection) => {
    
            try {
                const [password] = await connection.execute("SELECT password from `user` where email=?",email);
                return password;
            }
            catch (ex)
            {
                return Promise.reject({exception : ex,error : new Error(ex)});
            }
    
        });
    };
  4. hijaq commented on Jun 2, 2017

    @hijaq

    Can confirm having the same error and it happens only when using bluebird's using with disposer method to release connections and mysql2 1.3.0+ package. The small code to reproduce:

    const Promise = require('bluebird');
    const mysql = require('mysql2/promise');
    
    const pool = mysql.createPool({
      connectionLimit: 1,
      host: 'localhost',
      port: 3306,
      user: 'user',
      password: 'password',
      database: 'dbname',
      Promise,
    });
    
    const conn = () => Promise.using(pool
      .getConnection()
      .disposer(c => {
        c.release();
        console.log(`release connection`);
      }), c => c);
    
    const getUser = (uid) => conn().then(c => c
      .query('SELECT * FROM users WHERE user_id=?', [uid])
      .then(([rows]) => (rows.length === 1 ? rows[0] : Promise.reject('user not found'))));
    
    Promise
      .all([...Array(10).keys()]
        .map(uid => getUser(uid)
          .catch(err => console.error(`Unable to get user ${uid}: ${err}`))))
      .then(profiles => profiles
        .forEach(profile => console.log(JSON.stringify(profile))))
      .then(() => pool.end());

    result:

    bash-3.2$ node index.js
    release connection
    release connection
    release connection
    release connection
    release connection
    release connection
    release connection
    release connection
    (node:19740) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
    release connection
    (node:19740) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 end listeners added. Use emitter.setMaxListeners() to increase limit
    release connection
    Unable to get user 0: user not found
    Unable to get user 5: user not found
    Unable to get user 6: user not found
    undefined
    {"user_id":1,"username":"johndoe","avatar":"https://example.com/default.png","first_name":"John","last_name":"Doe"}
    // other users ....
    
  5. sidorares commented on Jun 3, 2017

    @sidorares
    Owner

    thanks @aankur @hijaq will try to investigate

  6. thexeos commented on Jun 3, 2017

    @thexeos

    I've opened the issue for this in different mysql project mysqljs/mysql#1742 by accident.

    I got the traces with --trace-warnings flag for Node v7.10.0:

    [02/06/2017 23:39:30.414] [ERROR] (node:5875) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:262:19)
    at PoolConnection.addListener (events.js:279:10)
    at /appRoot/node_modules/mysql2/promise.js:8:14
    at Array.forEach (native)
    at inheritEvents (/appRoot/node_modules/mysql2/promise.js:7:6)
    at new PromiseConnection (/appRoot/node_modules/mysql2/promise.js:37:3)
    at /appRoot/node_modules/mysql2/promise.js:201:17
    at /appRoot/node_modules/mysql2/lib/pool.js:36:14
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
    [02/06/2017 23:49:30.550] [ERROR] (node:5875) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 end listeners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:262:19)
    at PoolConnection.addListener (events.js:279:10)
    at /appRoot/node_modules/mysql2/promise.js:8:14
    at Array.forEach (native)
    at inheritEvents (/appRoot/node_modules/mysql2/promise.js:7:6)
    at new PromiseConnection (/appRoot/node_modules/mysql2/promise.js:37:3)
    at /appRoot/node_modules/mysql2/promise.js:201:17
    at /appRoot/node_modules/mysql2/lib/pool.js:36:14
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
    [02/06/2017 23:49:30.554] [ERROR] (node:5875) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:262:19)
    at PoolConnection.addListener (events.js:279:10)
    at /appRoot/node_modules/mysql2/promise.js:8:14
    at Array.forEach (native)
    at inheritEvents (/appRoot/node_modules/mysql2/promise.js:7:6)
    at new PromiseConnection (/appRoot/node_modules/mysql2/promise.js:37:3)
    at /appRoot/node_modules/mysql2/promise.js:201:17
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
    [02/06/2017 23:49:30.555] [ERROR] (node:5875) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connect listeners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:262:19)
    at PoolConnection.addListener (events.js:279:10)
    at /appRoot/node_modules/mysql2/promise.js:8:14
    at Array.forEach (native)
    at inheritEvents (/appRoot/node_modules/mysql2/promise.js:7:6)
    at new PromiseConnection (/appRoot/node_modules/mysql2/promise.js:37:3)
    at /appRoot/node_modules/mysql2/promise.js:201:17
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
    [02/06/2017 23:49:30.555] [ERROR] (node:5875) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 enqueue listeners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:262:19)
    at PoolConnection.addListener (events.js:279:10)
    at /appRoot/node_modules/mysql2/promise.js:8:14
    at Array.forEach (native)
    at inheritEvents (/appRoot/node_modules/mysql2/promise.js:7:6)
    at new PromiseConnection (/appRoot/node_modules/mysql2/promise.js:37:3)
    at /appRoot/node_modules/mysql2/promise.js:201:17
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

    I am not using bluebird however.

  7. aankur commented on Jun 3, 2017

    @aankur
    Author

    i am able to reproduce it without bluebird disposer

    Db.prototype.Verify= function Verify(email)
    {
      
       const connection = await  this.pool.getConnection();
           try
           {
       		
              const [password] = await connection.execute("SELECT password from `user` where email=?",email);           
               connection.release();
               return password;
           }
           catch(ex)
           {
       	connection.release();
               return Promise.reject({exception : ex,error : new Error(ex)});
           }
    
       });
  8. added a commit that references this issue on Jun 3, 2017
  9. thexeos commented on Jun 3, 2017

    @thexeos

    The remaining question is: how should the pool behave when it is actively using 10+ connections. For example, when multiple queries are running in parallel to aggregate data or alter table. The event listeners should be present until the query is done executing.

    Maybe some kind of a super-callback function that will only be attached once and then route and process events centrally. I can see situations when 50 or more connections will be managed by the pool at the same time, and they can all be in an active state at once. That would also mean 50 * 4 = 200 event listeners on one object.

  10. sidorares commented on Jun 7, 2017

    @sidorares
    Owner

    @thexeos EventEmitter warning is issued when you attach more then 10 listeners per event to one target. Pool attaches event per connection: conn1.on('connect') => pool.emit('connect') conn2.on('connect') => pool.emit('connect') etc

  11. rlidwka commented on Jun 9, 2017

    @rlidwka

    I have the similar issue here, and that's how I reproduce it:

    let mysql = require('mysql2/promise')
    
    let pool = mysql.createPool({
      host: '127.0.0.1',
      user: 'root',
      connectionLimit: 2
    })
    
    ;(async function () {
    
      for (let i=0; i<15; i++) {
        let conn = await pool.getConnection()
        //console.log((await conn.query('SELECT NOW() as time'))[0][0].time)
        conn.release()
      }
    
    })().catch(console.log)

    Just create a pool, and repeatedly connect/release. After 10th connection a couple of warnings will appear:

    (node:3716) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
    (node:3716) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 end listeners added. Use emitter.setMaxListeners() to increase limit
    (node:3716) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit
    (node:3716) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connect listeners added. Use emitter.setMaxListeners() to increase limit
    (node:3716) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 enqueue listeners added. Use emitter.setMaxListeners() to increase limit
    

    Note that those 5 warnings are for different events: error, end, drain, connect and enqueue respectively.

    Using node v8.1.0, mysql2 v1.3.3.

  12. sidorares commented on Jun 9, 2017

    @sidorares
    Owner

    @rlidwka #578 should fix this but I was going to have a look and maybe refactor original implementation - just creating pool should not set up any additional listeners, only when you do pool.on('.... Also currently events fire from non-promise pool and pass unwrapped pool / poolconnection as parameter

  13. thexeos commented on Jun 10, 2017

    @thexeos

    @sidorares There are no pool.on('... in my code. My situation is very similar to @rlidwka's example:

    queue.on('message', function(payload) {
        try {
            storePayload(payload)
        } catch (err) {
            // Error handling
        }
    });
    
    async function storePayload(payload) {
        let connection = await pool.getConnection();
        await connection.beginTransaction();
    
         try {
              let [rs] = await connection.execute("...", [ ... ]);
              await connection.commit();
         } catch (err) {
              await connection.rollback();
              throw err;
         }
    
        connection.release();
    }
    

    It works until it receives 10+ messages simultaneously. Then it prints the warnings.

  14. bhstrifork commented on Jun 23, 2017

    @bhstrifork

    Any news on this? I just ran into this myself using version 1.3.5

  15. sidorares commented on Jun 23, 2017

    @sidorares
    Owner

    @bhstrifork sorry didn't have time yet. #578 should fix this but I really wanted to refactor original cause and that fix would no longer be relevant

  16. odino commented on Jul 16, 2017

    @odino
    Contributor

    Same issue right here -- any idea for a fix?

  17. added a commit that references this issue on Jul 28, 2017
    ddb7df6
  18. karthick4in commented on May 4, 2018

    @karthick4in

    go to this link. you issue related to this one.
    mysqljs/mysql#979

  19. kodekameleon commented on Sep 19, 2018

    @kodekameleon

    I'm still seeing this issue in 1.6.1

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions