AWS Lambda pioneered serverless space. Many developers think that serverless is the future of development. It gives you the true pay-per-use model, relieves you from the maintenance and scaling of the backend infrastructure. But it also comes with challenges. One of those is its statelessness. You need to keep the state in an external data store. Unfortunately most of the popular data stores are connection based. But as we explained in this post, managing connections can become painful in serverless. That’s why, we have developed a high performance REST API on top of Upstash Redis. In this blog post, I will implement a very basic stateful api (page counter) on AWS Lambda and Upstash Redis using the REST API.
See the live demo: https://3jyz1n07o8.execute-api.us-east-1.amazonaws.com/count
We will use the serverless framework to deploy our application.
Install fetch via
npm install node-fetch. Then create a database from the Upstash console. Click the REST API button and copy the url and token. Update handler.js as below:
Add API endpoint to the serverless.yml as below:
You can the functions locally:
serverless invoke local -f hello
You can deploy with:
The command will output the url which you can check in your browser.
- For the best performance, your database and AWS Lambda function should be in the same region.
- Thanks to the REST API, we do not need to manage database connections and we do not need any Redis client.
- Do not share your API token publicly. If leaked mistakenly, you can revoke it by resetting your database’s password.
- If you want to run multiple commands in a single function, use pipeline API for the best performance.