In this tutorial, we will throttle AWS Lambda functions using Serverless Redis based on the client's IP address.
1 Serverless Project Setup#
If you do not have it already, install serverless framework via:
npm install -g serverless
In any folder run
serverless as below:
See Using AWS SAM, if you prefer AWS SAM over Serverless Framework.
Inside the project folder create a node project with the command:
Then install the redis client and rate limiting libraries with:
serverless.yml as below. Copy your Redis URL from console and replace below:
For the best performance choose the same region for your Lambda function and Upstash database.
2 Create a Redis (Upstash) Database#
Create a database from Upstash console
Edit handler.js and replace your REDIS_URL below.
Above, we have configured the rate limiting to accept 1 request from the same IP address in 5 seconds.
4 Deploy and Try the API#
Deploy your functions with:
The command will deploy the function and show the endpoint url. Click to the endpoint url. If you refresh your page, you will see that your request is throttled.