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?
You can try to use Redis, there are few pattern for rate limiting