Reputation: 613
I have a lambda application that needs to deal with RDS and Elasticache. Since the serverless context is stateless, I need to connect to these resources every time that the lambda is requested.
That said, I spent 0.5s to grab the database credentials from the Secrets manager and use them against RDS; another few milliseconds to connect on it. Now, double this time for Elasticache. In the end, I spent almost ~1.5 seconds only with resource prep steps.
Is there an alternative way to get these things done?
Upvotes: 0
Views: 48
Reputation: 4472
Lambda is not "stateless". When you make a request to a Lambda function for the first time ("cold" state), it starts up a "container" with the function to serve the request ("hot" state). Once the request is complete, the container hangs around in a suspended ("warm") state for somewhere in the 5 - 15 minutes range, ready to serve another request if one arrives. If no additional requests are made in that time, the container is destroyed.
This means that if you create and store your clients/connections/credentials in global variables, they will already exist if a warm container is used for a request, making the request much, much faster.
Here's an article from Serverless Framework that describes it in much more detail (note that it discusses an old way of keeping Lambdas warm, which is no longer recommended).
If you don't get requests to the Lambda frequently enough for it to be kept in a warm state, you can use Lambda's provisioned concurrency to ensure a given number of containers is always kept warm.
That's great for reducing Lambda start-up times and service connection times, but it's not a perfect solution and provisioned concurrency is a very expensive feature. For additional improvements, consider:
RDS Proxy: a proxy handler for RDS connections that allows Lambda to use them like a connection pool.
RDS IAM Auth: use IAM credentials to access RDS instead of user/pass that you need to retrieve from Secrets Manager.
Upvotes: 1