I've been looking over Lambdas for this new code base I'm working in. We're currently connecting directly to our RDS Aurora instances in our Lambdas, and I was looking into the best practices and started noticing areas that I think could be improved. I started going down a bit of a rabbit hole to make sure I understood most of this, but wanted to validate some thoughts I had and get insight from those that have actually done this.
One step at a time, but the thing that stood out to me immediately is that we initialize a connection to the database inside the handler function and it is always closed at the end. So this happens on every invocation. I've read many times that it's recommended to reuse these connections by initializing the connection outside the handler function.
If the connection is initialized once, I had wondered what would happen if the connection was dropped for whatever reason during the lifetime of the Lambda, and if it was invoked again. And I eventually got on the subject of RDS Proxy. In the end, I'm going to suggest that we look into using RDS Proxy.
Now back to the Lambdas. I had a few questions:
- Am I correct that we should be initializing the database connections outside the handler method? That way other invocations would reuse the connection.
- How do you authenticate the connection to the proxy? Do you use secrets in Secrets Manager or do you use IAM authentication? We currently use secrets right now, but the secret values are resolved on every invocation of the Lambda too, so I was thinking that was something we could reduce as well. I had read that IAM authentication would be a good benefit since we don't have to manage secrets in the Lambda, and the execution role would just need the right policy. But in the Lambda, we would still need to request an authToken. So in terms of request overhead, it doesn't sound like we would escape that.