Throttler

The Throttler class provides a very simple way to limit an activity to be performed to a certain number of attemptswithin a set period of time. This is most often used for performing rate limiting on API’s, or restricting the numberof attempts a user can make against a form to help prevent brute force attacks. The class itself can be usedfor anything that you need to throttle based on actions within a set time interval.

Overview

The Throttler implements a simplified version of the Token Bucketalgorithm. This basically treats each action that you want as a bucket. When you call the check() method,you tell it how large the bucket is, and how many tokens it can hold and the time interval. Each check() call uses1 of the available tokens, by default. Let’s walk through an example to make this clear.

Let’s say we want an action to happen once every second. The first call to the Throttler would look like the following.The first parameter is the bucket name, the second parameter the number of tokens the bucket holds, andthe third being the amount of time it takes the bucket to refill:

  1. $throttler = \Config\Services::throttler();
  2. $throttler->check($name, 60, MINUTE);

Here we’re using one of the global constants for the time, to make it a littlemore readable. This says that the bucket allows 60 actions every minute, or 1 action every second.

Let’s say that a third-party script was trying to hit a URL repeatedly. At first, it would be able to use all 60of those tokens in less than a second. However, after that the Throttler would only allow one action per second,potentially slowing down the requests enough that they attack is no longer worth it.

Note

For the Throttler class to work, the Cache library must be set up to use a handler other than dummy.For best performance, an in-memory cache, like Redis or Memcached, is recommended.

Rate Limiting

The Throttler class does not do any rate limiting or request throttling on its own, but is the key to makingone work. An example Filter is provided that implements a very simple rate limiting atone request per second per IP address. Here we will run through how it works, and how you could set it up andstart using it in your application.

The Code

You could make your own Throttler filter, at app/Filters/Throttle.php,along the lines of:

  1. <?php namespace App\Filters;
  2.  
  3. use CodeIgniter\Filters\FilterInterface;
  4. use CodeIgniter\HTTP\RequestInterface;
  5. use CodeIgniter\HTTP\ResponseInterface;
  6. use Config\Services;
  7.  
  8. class Throttle implements FilterInterface
  9. {
  10. /**
  11. * This is a demo implementation of using the Throttler class
  12. * to implement rate limiting for your application.
  13. *
  14. * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request
  15. *
  16. * @return mixed
  17. */
  18. public function before(RequestInterface $request)
  19. {
  20. $throttler = Services::throttler();
  21.  
  22. // Restrict an IP address to no more
  23. // than 1 request per second across the
  24. // entire site.
  25. if ($throttler->check($request->getIPAddress(), 60, MINUTE) === false)
  26. {
  27. return Services::response()->setStatusCode(429);
  28. }
  29. }
  30.  
  31. //--------------------------------------------------------------------
  32.  
  33. /**
  34. * We don't have anything to do here.
  35. *
  36. * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request
  37. * @param ResponseInterface|\CodeIgniter\HTTP\Response $response
  38. *
  39. * @return mixed
  40. */
  41. public function after(RequestInterface $request, ResponseInterface $response)
  42. {
  43. }
  44. }

When run, this method first grabs an instance of the throttler. Next, it uses the IP address as the bucket name,and sets things to limit them to one request per second. If the throttler rejects the check, returning false,then we return a Response with the status code set to 429 - Too Many Attempts, and the script execution endsbefore it ever hits the controller. This example will throttle based on a single IP address across all requestsmade to the site, not per page.

Applying the Filter

We don’t necessarily need to throttle every page on the site. For many web applications, this makes the most senseto apply only to POST requests, though API’s might want to limit every request made by a user. In order to applythis to incoming requests, you need to edit /app/Config/Filters.php and first add an alias to thefilter:

  1. public $aliases = [
  2. ...
  3. 'throttle' => \App\Filters\Throttle::class
  4. ];

Next, we assign it to all POST requests made on the site:

  1. public $methods = [
  2. 'post' => ['throttle', 'CSRF']
  3. ];

And that’s all there is to it. Now all POST requests made on the site will have to be rate limited.

Class Reference

  • check(string $key, int $capacity, int $seconds[, int $cost = 1])

Parameters:

  • $key (string) – The name of the bucket
  • $capacity (int) – The number of tokens the bucket holds
  • $seconds (int) – The number of seconds it takes for a bucket to completely fill
  • $cost (int) – The number of tokens that are spent on this actionReturns:TRUE if action can be performed, FALSE if notReturn type:bool

Checks to see if there are any tokens left within the bucket, or if too many havebeen used within the allotted time limit. During each check the available tokensare reduced by $cost if successful.

  • getTokentime()

Returns:The number of seconds until another token should be available.Return type:integer

After check() has been run and returned FALSE, this method can be usedto determine the time until a new token should be available and the action can betried again. In this case, the minimum enforced wait time is one second.