Skip to content

Commit 0b5a944

Browse files
Implement mysql connection pooling
## What? Implement mysql connection pooling to automatically handle server disconnects. See: - https://www.npmjs.com/package/mysql#server-disconnects - https://www.npmjs.com/package/mysql#pooling-connections Note that, because a ClearDB connection string is utilized rather than mysql connection options when deploying to Heroku, it is not possible to define a connectionLimit in the [pool options](https://www.npmjs.com/package/mysql#pool-options). As a result the default value (10) is used. ## Why? The following error was present in logs locally and on heroku resulting in app crashes: ``` error - uncaughtException: Error: Connection lost: The server closed the connection. at Protocol.end (/Users/patrick.puente/node-projects/demo-tax-provider/node_modules/mysql/lib/protocol/Protocol.js:112:13) at Socket.<anonymous> (/Users/patrick.puente/node-projects/demo-tax-provider/node_modules/mysql/lib/Connection.js:94:28) at Socket.<anonymous> (/Users/patrick.puente/node-projects/demo-tax-provider/node_modules/mysql/lib/Connection.js:526:10) at Socket.emit (events.js:412:35) at Socket.emit (domain.js:470:12) at endReadableNT (internal/streams/readable.js:1317:12) at processTicksAndRejections (internal/process/task_queues.js:82:21) { fatal: true, code: 'PROTOCOL_CONNECTION_LOST' } ``` Heroku logs also included the following: ``` 2021-12-30T21:27:52.182117+00:00 heroku[web.1]: Process exited with status 1 2021-12-30T21:27:52.244218+00:00 heroku[web.1]: State changed from up to crashed ``` ## Testing / Proof After implementing connection pooling, the error was no longer present in logs locally or in Heroku logs. Zero or multiple connections could be observed in the ClearDB dashboard without app crashes. @bigcommerce/api-client-developers
1 parent 9690ad2 commit 0b5a944

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

lib/dbs/mysql.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ const MYSQL_CONFIG = {
1111
};
1212

1313
// For use with Heroku ClearDB
14-
// Other mysql: https://www.npmjs.com/package/mysql#establishing-connections
15-
const connection = mysql.createConnection(process.env.CLEARDB_DATABASE_URL ? process.env.CLEARDB_DATABASE_URL : MYSQL_CONFIG);
16-
const query = promisify(connection.query.bind(connection));
14+
// Other mysql: https://www.npmjs.com/package/mysql#pooling-connections
15+
const pool = mysql.createPool(process.env.CLEARDB_DATABASE_URL ? process.env.CLEARDB_DATABASE_URL : MYSQL_CONFIG);
16+
const query = promisify(pool.query.bind(pool));
1717

1818
// Use setUser for storing global user data (persists between installs)
1919
export async function setUser({ user }: SessionProps) {

0 commit comments

Comments
 (0)