node-mysql2 icon indicating copy to clipboard operation
node-mysql2 copied to clipboard

Node process can't finish correctly after creation of Connection Pool

Open komanton opened this issue 2 years ago • 5 comments

I noticed that with some configuration of Connection Pool the Node process can't stop working and just hang. In my case, it appears in mocha tests when mocha process can't finish after all tests. This is simple project to reproduce the situation:

package.json

{
  "name": "mysql2-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "dependencies": {
    "mocha": "^10.2.0",
    "mysql2": "^3.2.0"
  },
  "author": "",
  "license": "ISC"
}

/test/test.js

const mysql = require('mysql2');

describe('test connection pool', function () {

  const pool = mysql.createPool({
    host: 'localhost',
    port: 3007,
    user: 'dev',
    password: 'dev',
    database: 'dev',
    multipleStatements: true,
    connectionLimit: 16,
    maxIdle: 0,
    idleTimeout: 60000,
    enableKeepAlive: true,
  });

  it('test stub', function () {
    // just place holder
  });

  this.afterAll(function () {
    console.log('Clean resources after all tests :');
  
    pool?.end();
  });  
});

Steps to reproduce:

  1. Run command npm test.
  2. All tests should be passed.

Actual behaviour: node process (i.e. mocha) is hang and can't finish. Expected behaviour: node process (i.e. mocha) should finish correctly.

Note 1: Actually, I think this is very important issue because it may affect not only mocha process but also some processes in Docker environment and Lambda where processes should quickly start and finish to satisfy auto-scalabity algorithms. Note 2: According to source code of mysql2, I noticed that in case of maxIdle < connectionLimit, mysql2 call clearTimeout. But looks like, it was forgotten to call clearTimeout on pool.end(). That's why 'event loop' is not empty, and it prevents a process from finishing.

komanton avatar Mar 27 '23 09:03 komanton

Thanks for your research. Can confirm this issue, clearing idle timer on pool end seems to solve it. I'll work on a fix & unit test

sidorares avatar Mar 28 '23 23:03 sidorares

I'm running into this issue also when running tests with maxIdle < connectionLimit.

Any suggested workarounds to more cleanly shutdown?

jeremysf avatar Jul 27 '23 19:07 jeremysf

@jeremysf As a work around, you can use mocha's --exit flag.

anton-fjg avatar Jul 28 '23 01:07 anton-fjg

I'm running into this issue also when running tests with maxIdle < connectionLimit.

Any suggested workarounds to more cleanly shutdown?

I've this issue too, I workaround this by just remove maxIdle

songpr avatar Aug 03 '23 15:08 songpr

I also have this issue, modify maxIdle doesn't work for me, but it works to add --exit in Mocha.

dennys avatar Sep 13 '23 05:09 dennys