Reputation: 1951
I have a lambda to connect to SQL Server database like this.
module.exports = async (event) => {
const sqlClient = getConnection(); // connection to ms SQL
doMyWork(sqlConnection) // my core lambda logic
closeConnection(sqlConnection) // closing Connection
}
when ever lambda is triggered, my SQL Server gets connected, work is done and connection is closed. Isn't there a way that i can use the connection object across multiple invocations of the lambda so that i can reduce a) no. of connection / disconnection attempts to server b) reduce the overall execution time of the lambda?
I have mentioned SQL Server here as I am currently using it here. as such I have to connect to MySQL and redis. what is the recommended way for connecting to databases (especially which support pools)?
Please suggest.
Upvotes: 12
Views: 12713
Reputation: 4399
Generally, there are 2 ways to address this problem.
Store the connections/connection pool in a variable that persists across Lambda invocations. How to do it depends on the runtime/language you use. An example with node.js
is here.
Use an external application that is long running and is able to persist a connection pool. Another Lambda function cannot do this and you'd need an EC2 or another long running compute instance. Thankfully AWS recently introduced RDS Proxy, which is a managed service that achieves this. It is however, still in preview.
For MSSQL/MySQL on RDS, you'll be able to use option 1 or 2 but for Redis you'll have to use option 1.
Upvotes: 11