AWS Lambda with ElasticCache


ElasticCache is a fully managed AWS offering. ElasticCache is compatible with Memcached, Redis, and Valkey. In this blog, you will learn to deploy a Redis server in AWS ElasticCache. You can configure the ElasticCache Redis server as a cluster or single server. But to make the learning easy, I have chosen to deploy Redis on a single server. In this blog, you will also learn how to create a VPC. Connect Lambda to a VPC and configure security groups.
Please remember to delete these resources once you are done. It will incur a lot of charges for these services.
1. Creating VPC
VPC or Virtual Private Cloud lets you deploy your services in an isolated virtual network that you configure. An AWS account comes with a default VPC for every region. For this tutorial, you will create a new VPC from scratch. Open the VPC page and click on Create VPC.
Select VPC and more. This will save a lot of time by automatically creating a lot of the networking stuff. Do not change the CIDR block if you are not sure. You may mistakenly set it to a public/reserved IP range.
Based on your needs, you may change the number of availability zones or the quantity of private/public AZs. No need to customize the subnet CIDR block. NAT gateways can be enabled only if Lambda needs to talk to the internet. NAT gateways are charged separately, so enable that only when needed. Set VPC endpoint to None in this case.
Click on Create VPC.
Your VPC preview should look something like this.
1.1 Creating Security Groups:
In the VPC page, under the Security menu you will find the link to Security Groups
On the Security Group page, click on Create security group.
The first security group will be created to be attached to Lambda. So, give it a proper name and write down the description. Most importantly, select the newly created VPC.
Do not change the Inbound/Outbound rules for this security group.
For the security group to be attached to ElasticCache, also name it, write down the description, and change the VPC.
In the Inbound rule, add a new inbound rule. This rule will allow requests from the previously created security group, SecurityGroupForLambda, on port 6379. 6379 is the default port for Redis. Click on Create.
2. Creating a Lambda Function
Create a Lambda function from scratch. You can choose any language you prefer. However, this article uses Python.
Expand the Additional Configurations section. Check the Enable VPC.
Select the VPC you created. Select both the Private Subnets. AWS recommends choosing a minimum of two Subnets. Select the SecurityGroupForLambda security group. Click on the Create function.
You need to create a Layer to use the Redis package. You can follow this Blog to create and attach the layer. Just use Python 3.11 base Image instead of Python 3.9.
Python and MongoDB in AWS Lambda with Layer
2.2 Updating Lambda Timeout
Go to the Lambda Configuration tab. Select General configuration. Click on Edit.
Update Timeout to 1 minute 0 seconds. If Lambda needs some time to establish the connection with Redis, it will not throw a timeout error.
2.2 Lambda Code
Copy and paste the code into Lambda. Deploy the code.
import os
import redis
# Example: Set your Redis host and port (or use environment variables)
REDIS_HOST = os.getenv("REDIS_HOST", "elastic_cache_rimary_endpoint")
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
def lambda_handler(event, context):
try:
# Create a Redis connection
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, ssl=True, ssl_cert_reqs="none", decode_responses=True)
# Set a key-value pair
r.set("lambda-test-key", "hello-from-lambda")
# Retrieve the value
value = r.get("lambda-test-key")
return {
"statusCode": 200,
"body": f"Successfully connected to Redis! Value: {value}"
}
except Exception as e:
return {
"statusCode": 500,
"body": f"Error connecting to Redis: {str(e)}"
}
3. Creating Elastic Cache
Go to the ElasticCache page, and in the dashboard, you will see the Redis OSS caches link.
Click on Create cache.
To deploy cache in a single Server, choose the following options.
Change the Number of Replicas to 1.
On the connectivity section, choose Create a new subnet group.
Give a proper name. Select the VPC you created. In the Selected subnets (4) section, click on Manage.
Select the Private subnets only. These two subnets were selected in Lambda as well.
Click on Next. On the next page, select the Security Group, SecurityGroupForCache.
Disable backup.
Click on Next. Review everything and make sure the VPC, Subnets, and Security Groups are right.
Click on Create. Wait for 5 to 10 minutes.
3.1 Change Primary Endpoint in Lambda Code
Once ElasticCache is available, open the cache page.
Copy the Primary endpoint except :6379. Paste it into Lambda code.
# Change elastic_cache_rimary_endpoint with primary endpoint
REDIS_HOST = os.getenv("REDIS_HOST", "elastic_cache_rimary_endpoint")
Go to the Test tab of Lambda. Click on Test.
If everything is configured properly, you will get the following result.
Subscribe to my newsletter
Read articles from Ritwik Math directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ritwik Math
Ritwik Math
As a seasoned senior web developer with a wealth of experience in Python, Javascript, web development, MySQL, MongoDB, and React, I am passionate about crafting exceptional digital experiences that delight users and drive business success.