I am using SvelteKit, Vite.js, and the mariadb package with Node.js in my application. I have the following code in the db.js file:
import mariadb from 'mariadb';
const databaseConnectionPoolConfig = {
...
};
let databaseConnectionPool = undefined;
export function createDatabaseConnectionPool() {
return databaseConnectionPool ??= mariadb.createPool(databaseConnectionPoolConfig);
}
Inside the hooks.server.js file, I have the following code:
import { createDatabaseConnectionPool } from '$lib/db';
createDatabaseConnectionPool();
When a hot reload is performed, the databaseConnectionPool is reset to undefined, but the connections in the pool are not closed, and new ones are created. I checked this by running the following query:
SHOW STATUS LIKE 'Threads_connected';
Which increases each time a hot reload is performed by the number of connections specified by the databaseConnectionPoolConfig.connectionLimit property.
How can I prevent this from happening?
I solved this issue by using the globalThis object. The globalThis object doesn't get reset when hot reloads occur, which allows the database connection pool to be preserved. Here's the solution I've come up with:
// hooks.server.js
globalThis.databaseConnectionPool ??= mariadb.createPool(databaseConnectionPoolConfig);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With