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 Respostas
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
ESPECIALISTA
Uri
respondido há 2 anos
profile pictureAWS
ESPECIALISTA
avaliado há 2 anos
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
ESPECIALISTA
respondido há 2 anos
  • 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 ?

Você não está conectado. Fazer login para postar uma resposta.

Uma boa resposta responde claramente à pergunta, dá feedback construtivo e incentiva o crescimento profissional de quem perguntou.

Diretrizes para responder a perguntas