What is the best way to limit requests for an API? Basically, we want to limit users to 360 API requests an hour (a request every 10 seconds). What comes to mind is tracking every API request and storing:
ip-address hourly-requests 1.2.3.4 77 2.3.4.5 34 3.4.5.6 124
If the ip-address requests is greater than 360, simply return a header with:
429 - Too Many Requests
Then rollback the counter hourly-requests every hour. This seems like an very inefficient method, since we have to make a MySQL query on every API request to increment the counter. Also, we would need a cron task to reset all counters every hour.
Is there a more elegant/efficient solution?
API limiting, which is also known as rate limiting, is an essential component of Internet security, as DoS attacks can tank a server with unlimited API requests. Rate limiting also helps make your API scalable. If your API blows up in popularity, there can be unexpected spikes in traffic, causing severe lag time.
You can try to use Redis, there are few pattern for rate limiting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With