tl;dr: If you don’t want to read the post check out the sample here.
If you are building an API, it is likely that at some point you will have the need to throttle requests. There might be several reasons for that but the core part is that you want to limit the amount of requests that a certain party (could be a user, ip, etc.) can perform over a period of time.
At Auth0 we are working on limitd, which implements the token bucket algorithm to support throttling scenarios. Since our API v2 uses hapi.js, we also decided to create patova, a limitd plug-in for hapi.js.
This post shows how easy it is to enable this feature in your application.
Requirements
Let’s assume that we have an API that uses basic authentication and we want to limit requests by user.
Implementation
Create a new directory and install the required modules:
Then create a file named server.js
with the following code (the sample is based on the hapi-basic-auth readme):
Start the server node server.js
and perform a request to make sure everything is working:
Create a file named limitd.config
to hold limitd’s configuration:
And start the limitd server:
Finally, add the patova plug-in to the hapi server:
That’s all there is to it!
Trying it out
Let’s make sure everything is working. Restart the server and perform 6 requests (remember we configured 5 req/sec as the limit):
The last one should display the following
As you can see, adding throttling to you hapi.js API is very simple. If you have questions or comments feel free to post them here or as issues in the project.