This post is a reblog.
reblogged from 200
28

Notes

simple rolling rate-limit algorithm

Ok my last post on rate limiting. You had the right idea with averages. This uses 3 values per id to determine their rate. You can reduce it to a single cache item stored as a serialized array.

public function allow_hit($id, $limit_per_minute) {
  $key = md5($id);
  $thistime = time();

  $count = intval(Cache::get('rate-count', $key));
  $lasttime = intval(Cache::get('rate-last', $key));
  $average = intval(Cache::get('rate-average', $key));

  $diff = $thistime - $lasttime;
  $total = $count * $average;
  $newtotal = $total + $diff;
  $newaverage = $newtotal / ($count + 1);

  Cache::set('rate-count', $key, $count + 1, 60);
  Cache::set('rate-last', $key, $thistime, 60);
  Cache::set('rate-average', $key, $newaverage, 60);
        
  if ($count > $limit_per_minute && $newaverage < $limit_per_minute / 60) {
    return false;
  }

  return true;
}

Posted: 2009-03-12 14:17

Bjorn Stromberg

My name is , I have an odd fascination with octopus and I am currently in Austin, TX. 我會講中文~ 感謝個位來看我的網站. I hope you find something you like.

If you're looking for TumTaster, Tumblr Savior, or Hey Tumblr, they're in my extension collection :)



Ask / Archive / RSS -



If you're looking for my Enchanter Epic Quest Guide, it's still here.

My email address is bjorn@bjornstar.com

my secret heart is floating around here somewhere.

This tumblelog is powered by Tumblr.