Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse database connection across multiple AWS Lambda invocations

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.

like image 642
Lakshman Pilaka Avatar asked Mar 15 '26 00:03

Lakshman Pilaka


1 Answers

Generally, there are 2 ways to address this problem.

  1. 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.

  2. 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.

like image 119
ubi Avatar answered Mar 16 '26 13:03

ubi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!