28
Notes
Notes
Simple rate-limiting algorithm?
OK let me propose another solution. Once you hit the limit a 60 second timeout begins and gets refreshed on each attempt. Also not exactly what Marco wanted, but workable.
public function allow_hit($id, $limit_per_minute)
{
$key = md5($id);
$count = intval(Cache::get('rate-limiter', $key));
if ($count > $limit_per_minute) {
Cache::replace('rate-limiter', $key, $count + 1, 60);
return false;
}
if ($count) {
Cache::increment('rate-limiter', $key, 1);
} else {
Cache::set('rate-limiter', $key, 1, /* ttl */ 60);
}
return true;
}
Posted: 2009-03-12 13:02