How to reuse postgres database connection client across multiple AWS Lambda invocations?

51 views Asked by At

I have a lambda which connects to postgres database using 'pg' package. Every time i create a new database connection, execute the query and close the connection. Lambda can invoke multiple times. How can i use the DB connection across all lambda executions so that no need to create a new connection every time.

1

There are 1 answers

1
Raisin On

You can reuse the client itself by generating it in the function handler's constructor, so it stays as long as the lambda function is warm, but gets recreated on cold starts. As for the connection itself, if you close it, it's closed.