To reproduce, use the lb4 cli generators to make a new mysql datasource, model, repo, and controller. Then call "get" on that route via HTTP many times while watching "show processlist;" in MySQL. You will see loopback is making a new connection for each http request rather than paying attention to the "connectionLimit" param. Keep calling the HTTP route and you can create many more connections than "connectionLimit" should be allowing.
inside "node_modules/loopback-connector-mysql/lib/mysql.js". line "this.client = mysql.createPool(options);" gets called for HTTP every request. This means every HTTP request creates a new connection. This can quickly bring down a web service when the MySQL server hits its own connection limit.
The "connectionLimit" MySql datasource param doesn't help with this issue at all. It just gets passed through to the new connection in "options" in the line mentioned above.
Don't make more connections than the MySql datasource connectionLimit param.
_See Reporting Issues for more tips on writing good issues_
For anyone running out of mysql connections in loopback 4, here is a work around. This works by turning the datasource into more of a singleton so loopback doesn't keep re-constructing it and causing it to re-connect to MySql for each http request.
import { inject } from '@loopback/core';
import { juggler } from '@loopback/repository';
/**
* This stores an instance of this datasource to prevent MySQL
* from running out of connections. For some reason loopback
* re-constructs this data source on every request.
*/
let singletonInstance: MysqlDataSource | null = null;
export default class MysqlDataSource extends juggler.DataSource {
static dataSourceName = 'mysql';
constructor(
) {
if (singletonInstance) {
return singletonInstance;
}
super({
connectionLimit: 10,
name: "mysql",
connector: "mysql",
host: process.env.MYSQL_HOST,
port: process.env.MYSQL_PORT,
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE
});
singletonInstance = this;
}
}
Closing this issue while i check that I'm not just binding the datasource improperly
Most helpful comment
For anyone running out of mysql connections in loopback 4, here is a work around. This works by turning the datasource into more of a singleton so loopback doesn't keep re-constructing it and causing it to re-connect to MySql for each http request.