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回答
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
エキスパート
Uri
回答済み 2年前
profile pictureAWS
エキスパート
レビュー済み 2年前
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
エキスパート
回答済み 2年前
  • 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 ?

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ