Skip to content

Throttler usage #827

Description

@natanfelles

Hi, I was testing requests by browser to see the throttler work. But do not occurs any 429 HTTP Code response.

Then I created a Command to test this...

<?php namespace App\Commands;

use CodeIgniter\CLI\CLI;
use CodeIgniter\CLI\BaseCommand;

class TestThrottle extends BaseCommand
{
	protected $group       = 'Tests';
	protected $name        = 'test:throttle';
	protected $description = 'Test';

	public function run(array $params)
	{
		CLI::write('Test Throttle', 'light_green');

		$curl = \Config\Services::curlrequest();

		$runtime = 60; // Seconds to continue crawling

		$time    = time();
		$stop_at = $time + $runtime;

		$requests = 1; // The requests counter
		$codes    = []; // HTTP Status Codes and times responded

		while (time() <= $stop_at)
		{
			$response = $curl->get(base_url(), ['http_errors' => false]);

			$code = $response->getStatusCode();

			$codes[$code] = isset($codes[$code]) ? $codes[$code] + 1 : 1;

			switch (substr($code, 0, 1)) {
				case 2:
					$color = 'green';
					break;
				case 3:
					$color = 'blue';
					break;
				case 4:
					$color = 'red';
					break;
				case 5:
					$color = 'yellow';
					break;
				default:
					$color = 'white';
					break;
			}

			$code = CLI::color($code, $color);

			CLI::write('Seconds to end: ' . ($stop_at - time()) . ' - Request ' . $requests++ . ' [' . $code . ']');
			CLI::write('GET: ' . $response->getBody());
			//var_dump($response);exit;
		}

		// Results
		CLI::write('Results', 'light_green');

		CLI::write('Runtime: ' . $runtime . ' seconds');
		CLI::write('Rate of ' . ($requests / $runtime) . ' responses per second');

		foreach ($codes as $code => $times)
		{
			CLI::write("- Code {$code} was responded {$times} times.");
		}
	}

}

To avoid CLI errors after enable the Global Before Filter throttle, I added this in the begging of the before method of the Throttle Filter:

if ($request->isCLI())
{
	return;
}

$throttler = Services::throttler();

And in the Home controller index just an echo date('Y-m-d H:i:s'); to see the body get by the cURL.

Then, testing in the terminal by 60 seconds I had the following result:

Results
Runtime: 60 seconds
Rate of 43.85 responses per second
- Code 200 was responded 2485 times.
- Code 429 was responded 145 times.

By 10 seconds the following:

Runtime: 10 seconds
Rate of 52.8 responses per second
- Code 200 was responded 527 times.

My doubt is: Is "correct" have results like it?

  • I used the Files cache driver.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions