Search code examples
databaseamazon-web-servicesaws-lambdaredis

Redis Instance Reuse in AWS Lambda


Question:

I'm using Redis as a caching database within my AWS Lambda functions, and I have a question regarding how Redis works under the hood when reusing the same Redis client instance across different Lambda invocations.

I use a single Redis client instance to avoid creating a new connection every time a Lambda function is invoked. My concern is about the potential side effects when multiple Lambda instances are invoked simultaneously.

Scenario:

  • Lambda 1 starts and initiates multiple Redis operations using the multi/exec commands.
  • At the same time, Lambda 2 is invoked and performs a simple Redis add operation using the same Redis client instance.
  • If Lambda 2 completes its operation and Lambda 1 calls discard, will the discard command in Lambda 1 affect the Redis operations in Lambda 2?

My Questions:

  1. Does reusing the same Redis client instance across different Lambda invocations cause any interference between the operations of those invocations as they share the same instance connection?
  2. Should I create a new Redis client instance for each Lambda invocation to avoid potential conflicts?

Solution

  • No, you don't need a separate Redis instance for each lambda invocation because:

    • Redis is single threaded. Meaning it will execute one command at a time. it may seems like you are running two or more commands simultaneously but they'll execute one after the another.
    • As mentioned here Redis transactions are atomic, which means all the commands will be executed as single operation and if any command fails it will rollback the whole transaction.