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 Respuestas
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
EXPERTO
Uri
respondido hace 2 años
profile pictureAWS
EXPERTO
revisado hace 2 años
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
EXPERTO
respondido hace 2 años
  • 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 ?

No has iniciado sesión. Iniciar sesión para publicar una respuesta.

Una buena respuesta responde claramente a la pregunta, proporciona comentarios constructivos y fomenta el crecimiento profesional en la persona que hace la pregunta.

Pautas para responder preguntas