Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Best Way to limit requests for each user

Hello community! I just want to know the best method that can limit the request (for an api) I mean, for example

user1: will have max 5req/seconds user2: will have max 50req/seconds user3: will have max 500req/seconds ...

user:: use an api key

and also to know why I posted this because if I use database record, I think that will increase more the performance of server

I not sure :)

but I want to know

tkanhs!



118.4k
Accepted
answer

You're going to have to record it somewhere. Something like memcached or redis would be faster than a database.

Also, you don't need to record every request - just the time of the last request. If someone is limited to 5 requests per second, that's 200 milliseconds per request. So on each request, check if the previous request happened more recently than 200 milliseconds ago. If it did, reject the request. Otherwise, honour the request and record the current time in milliseconds.

microtime() will probably be useful here.

interesting idea
working with redis

first time i will use it :D

thanks a lot !

thank you for sharing this info!

Keep in mind that you should do this atomic way. Avoid methods such as set.

In memcache you can do it using add method which will add a key only if it not exists and increment/decrement methods - this way you never set a value yourself

I guess the same should be possible with redis.

With database it wouldn't be so easy.

Okey thanks you !