0
votes

If there is a Node.js Lambda function that creates a connection to a RDS Postgres database, is this connection automatically destroyed (i.e. without configuring any idle timeout setting) when the Lambda container is destroyed?

(I've seen mixed responses regarding this.)

1

1 Answers

1
votes

When Lambda runs your function, it creates an Execution Context, which would be your "Container" although it's more like a Micro-VM for betters isolation (as we learned at re:Invent 2018).

To quote from the documentation (emphasis mine).

After a Lambda function is executed, AWS Lambda maintains the execution context for some time in anticipation of another Lambda function invocation. In effect, the service freezes the execution context after a Lambda function completes, and thaws the context for reuse, if AWS Lambda chooses to reuse the context when the Lambda function is invoked again. This execution context reuse approach has the following implications:

Any declarations in your Lambda function code (outside the handler code, see Programming Model) remains initialized, providing additional optimization when the function is invoked again. For example, if your Lambda function establishes a database connection, instead of reestablishing the connection, the original connection is used in subsequent invocations. We suggest adding logic in your code to check if a connection exists before creating one.

[...]

When you write your Lambda function code, do not assume that AWS Lambda automatically reuses the execution context for subsequent function invocations. Other factors may dictate a need for AWS Lambda to create a new execution context, which can lead to unexpected results, such as database connection failures.

With regards to your question I'd conclude the following:

  • If Lambda has a frozen context stored away, it may use it, but there are no guarantees
  • Lambda may store your context for a while after the execution and thereby keeping up the database connection, if it has been established/stored outside of your handler function.
  • Lambda decides if and when to remove any frozen contexts and makes no guarantees when it will do that.

If you need to ensure that your connection gets terminated at the end of the execution, you have to do so yourself or keep it within the handler function, you can't rely on Lambda to do that for you.