We have a cc task which queries a mysql database. We are reaching db connection limit constraints during high demand periods and I suspect the reason is because currently our code opens a connection pool with each request and closes the pool thereafter.
I think it would be better practice to reuse the same connection pool with each cc task request, instead of starting a new one, however I’m unsure where and how to save the pool globally and persistently in order to re-use it??
Assuming ‘global’ were a journey object that persists even after requests finish, I would like open and save the connection pool to the global object and then reuse as required e.g:
const mysql = require(‘mysql2’);
// Check if a pool already exists
if (!global.mysqlPool) {
// Create a connection pool
global.mysqlPool = mysql.createPool({
host: ‘your_database_host’,
user: ‘your_database_user’,
password: ‘your_database_password’,
database: ‘your_database_name’,
waitForConnections: true,
connectionLimit: 10, // Adjust the number based on your requirements
queueLimit: 0,
});
// Add an event listener to handle pool errors
global.mysqlPool.on(‘error’, (err) => {
console.error(‘MySQL Pool Error:’, err);
});
}
function executeQuery() {
global.mysqlPool.getConnection((err, connection) => {
if (err) {
console.error(‘Error getting connection from pool:’, err);
return;
}
// Use the connection for database operations
connection.query('SELECT * FROM your_table', (queryError, results) => {
// Release the connection back to the pool when done with it
connection.release();
if (queryError) {
console.error('Error executing query:', queryError);
return;
}
// Process the results here
console.log('Query results:', results);
});
});
}
// Example: Execute the query function
executeQuery();
If there is a better way of interfacing with a DB from cc tasks, please let me know.
Many thanks.