Reputation: 71
I'm using typeorm "typeorm": "0.3.9" in a serverless architecture using AWS lambdas + RDS Proxy.
Following some suggestions I found on the internet, I chose to keep a connection open after the lambdas are executed so that it can be reused by the next lambda execution.
My problem is that there is a scenario where my RDS Proxy closes a connection (which it considers idle) but the reference of that connection is still being used by a lambda and then an error occurs.
To solve this problem I tried using typeorm to check if there is an active connection with the following code:
// Returns true even when the RDS Proxy has already killed the connection.
if (!this.dataSource.isInitialized) {
await this.dataSource.initialize();
}
When I tested it I noticed that this validation understands that there is an established connection even when the RDS Proxy has already killed the connection.
Can anyone suggest me a way to check if there is an established connection to the database before opening a new connection?
Upvotes: 1
Views: 1426
Reputation: 131
I was able to find a good solution for this. Just run a query and re-establish the connection if it fails.
This is a snippet from a middy middleware but you should be able to see what I mean....
if (datasource) {
try {
// run a quick query to validate the connection, the lambda may have destroyed it
await datasource.query('select version()');
request.context.datasource = datasource;
// We have a valid connection we can return;
return;
} catch (e) {
console.warn('check connection failed, re-establishing connection', e);
datasource = undefined;
}
}
... establish a connection
Upvotes: 0