This tutorial implements a serverless application and deploy it to AWS Lambda using AWS SAM.
See Using Serverless Framework, if you prefer Serverless Framework over SAM.
If you do not have one, create a database following this guide.
If you do not have it already install AWS SAM as described here
In any folder run
sam init and select
Hello World Example as below:
Inside the hello-world folder install the redis client with:
Edit hello-world>app.js file as below. Replace the Redis URL (copy ioredis url from your Upstash console).
In the project folder run:
The output will be:
Deploy your function via
sam deploy --guided.
You can run your function locally with
sam local invoke
You can also test your function using AWS console. In your AWS Lambda section, click on your function. Scroll down to the code sections and click on the
Test button on the top right.
Congratulations, now your lambda function inserts entry to your Upstash database.
- You can write and deploy another function to just get values from the database.
- You can integrate API Gateway so you can call your function via http.
- You can learn about how to monitor your functions from CloudWatch as described here.
Although Redis connections are very lightweight, a new connection inside each Lambda function can cause a notable latency. On the other hand, reusing Redis connections inside the AWS Lambda functions has its own drawbacks. When AWS scales out Lambda functions, the number of open connections can rapidly increase. Fortunately, Upstash detects and terminates the idle and zombie connections thanks to its smart connection handling algorithm. Thanks to this algorithm; we have been recommending caching your Redis connection in serverless functions.
See the blog post about the database connections in serverless functions.