I am trying to figure out the best way to limit API requests for a given key. Basically, I currently have a table field called counter where one every request I add 1 to the previous value.So I’m already logging every request but my question is that what is the most efficient way of limiting the output for a user where the limit is determined by n number of requests a month.
Now the solution I have at the moment is that you just compare if counter <= n and then proceed with getting the data but is there a better way of doing this ? considering that the data is cached and if you are querying the DB on every request for the counter you might as well request the data too..
Thanks
You could store the counter associated with each key directly in memory using something like php memcache. Then you could backup all the values into your database once a day in case of a server failure where you lose the data in memory you will only have lost the counts for part of one day.
Depending on how many keys you give out you would have to determine how much memory this would use and if it is a practical solution.
You could use a middle ground too and only cache the ones that have reached their limit each month. So every time a key reaches it’s maximum request count you flag it in memory. Then at the end of each month, when you reset the counts in the db you also flush them all out of memory.
This way you make the requests to your db until the user reaches the limit (since you’re querying the db anyways for the request) and then you stop querying the table.