shared code between many lambdas

0

Hi team,

in my serverless application, I have many lambda functions that need to access to Redis cache,

I would like to know what is the best practice for this scenario, is:

  • to have one lambda that creates the connection to the Redis cluster and then returns the RedisClient, this lambda will be called by all other lambdas
  • or make the common code (that connects to Redis and return the Redis client) a layer that is used by all other lambdas?

Thank you!

2 Answers
1

I would not use a separate Lambda function just to create the connection. I am not even sure if it is possible. The other function runs in its own isolated execution environment so you can't share the connection.

You should create the connection in each Lambda function that needs it. You can use a Layer, but I prefer to just include the code in the function and call it where you need it.

profile pictureAWS
EXPERT
Uri
answered a year ago
profile pictureAWS
EXPERT
reviewed a year ago
0

The first option is an absolute no-no.

Take a look at this tutorial for an example - https://docs.aws.amazon.com/lambda/latest/dg/services-elasticache-tutorial.html

Make sure that the connection opening code is outside the event handler code in the lambda, otherwise a new connection will be opened with every event.

If you are concerned about high concurrency of lambda causing a high number of connections to Redis, you can set reserved concurrency on the lambda so the number of connections does not go beyond what your Redis cluster can accept. The clients will then have to implement retry in their code to handle throttles due to reserved concurrency on the lambdas.

profile pictureAWS
EXPERT
answered a year ago
  • Thank you! so it's better to use the code directly on each lambda function rather than using a layer code, to avoid latency in lambda init ?

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions