All Projects → sunspikes → php-ratelimiter

sunspikes / php-ratelimiter

Licence: MIT license
A framework independent rate limiter for PHP

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to php-ratelimiter

adaptive throttler
manages multiple throttlers with ability to ramp up and down
Stars: ✭ 31 (-47.46%)
Mutual labels:  rate-limiter, throttler
portara-website
Portara dashboard controller to change rate limit settings without redeploying your app
Stars: ✭ 42 (-28.81%)
Mutual labels:  rate-limiter, throttler
rush
rush.readthedocs.io/en/latest/
Stars: ✭ 42 (-28.81%)
Mutual labels:  rate-limiter, throttler
phalcon-throttler
Phalcon Throttler is a Rate Limiter for the PHP Phalcon Framework.
Stars: ✭ 19 (-67.8%)
Mutual labels:  rate-limiter, throttler
rate-limiter
The Rate Limiter Component provides a Token Bucket implementation to rate limit input and output in your application.
Stars: ✭ 156 (+164.41%)
Mutual labels:  rate-limiter
Slowapi
A rate limiter for Starlette and FastAPI
Stars: ✭ 169 (+186.44%)
Mutual labels:  rate-limiter
Portara
Portara directive is a rate limiter / throttler for GraphQL
Stars: ✭ 158 (+167.8%)
Mutual labels:  rate-limiter
Curiefense
Curiefense is a unified, open source platform protecting cloud native applications.
Stars: ✭ 136 (+130.51%)
Mutual labels:  rate-limiter
rl
Rate limit from stdin to stdout (drop or keep messages)
Stars: ✭ 38 (-35.59%)
Mutual labels:  rate-limiter
sample-spring-cloud-gateway
sample spring cloud application with embedded api gateway on spring cloud gateway with or without service discovery with eureka
Stars: ✭ 25 (-57.63%)
Mutual labels:  rate-limiter
gentle-force
Brute-force, error and request rate limiting
Stars: ✭ 45 (-23.73%)
Mutual labels:  rate-limiter
Limitrr
Light NodeJS rate limiting and response delaying using Redis - including Express middleware.
Stars: ✭ 203 (+244.07%)
Mutual labels:  rate-limiter
zlimiter
A toolkit for rate limite,support memory and redis
Stars: ✭ 17 (-71.19%)
Mutual labels:  rate-limiter
nestjs-ratelimiter
Distributed consistent flexible NestJS rate limiter based on Redis
Stars: ✭ 49 (-16.95%)
Mutual labels:  rate-limiter
Graphql Rate Limit
🚦 Fixed window rate limiting middleware for GraphQL. Use to limit repeated requests to queries and mutations.
Stars: ✭ 171 (+189.83%)
Mutual labels:  rate-limiter
nestjs-throttler-storage-redis
Redis storage provider for the nestjs-throttler package.
Stars: ✭ 56 (-5.08%)
Mutual labels:  throttler
Throttler
A rate limiting module for NestJS to work with Fastify, Express, GQL, Websockets, and RPC 🧭
Stars: ✭ 145 (+145.76%)
Mutual labels:  rate-limiter
redislimiter-spring-boot
an excellent API limiting framework for Spring boot/cloud application, especially for microservice project
Stars: ✭ 64 (+8.47%)
Mutual labels:  rate-limiter
asyncio-throttle
Simple, easy-to-use throttler for asyncio.
Stars: ✭ 95 (+61.02%)
Mutual labels:  throttler
Polite
Be nice on the web
Stars: ✭ 253 (+328.81%)
Mutual labels:  rate-limiter

PHP Ratelimiter

A framework independent, flexible and highly extensible rate limiter for PHP.

SensioLabsInsight Scrutinizer Code Quality Code Coverage Code Climate Build Status Latest Stable Version License

Installation

With Composer

It is best installed it through packagist by including sunspikes/php-ratelimiter in your project composer.json require:

    "require": {
        "sunspikes/php-ratelimiter":  "dev-master"
    }

Without Composer

You can also download it from Github, but no autoloader is provided so you'll need to register it with your own PSR-4 compatible autoloader.

Usage

Overview

// 1. Make a rate limiter with limit 3 attempts in 10 minutes
$cacheAdapter = new DesarrollaCacheAdapter((new DesarrollaCacheFactory())->make());
$settings = new ElasticWindowSettings(3, 600);
$ratelimiter = new RateLimiter(new ThrottlerFactory($cacheAdapter), new HydratorFactory(), $settings);

// 2. Get a throttler for path /login 
$loginThrottler = $ratelimiter->get('/login');

// 3. Register a hit
$loginThrottler->hit()

// 4. Check if it reached the limit
if ($loginThrottler->check()) {
    // access permitted
} else {
    // access denied
}

// Or combine the steps 3 & 4
if ($loginThrottler->access()) {
    // access permitted
} else {
    // access denied
}

// To get the number of hits
print $loginThrottler->count(); // or count($throttler)

Configuration

By default PHP Ratelimiter uses the desarolla2 cache adapter, the sample configuration provided in config/config.php

You can configure the drivers in config.php, for example to use memcache change the driver to 'memcache'

return [
    'default_ttl' => 3600,
    'driver'      => 'memcache',
    'memcache' => [
        //....
    ],
];

Extending

The PHP Ratelimiter is highly extensible, you can have custom adapters by implementing Sunspikes\Ratelimit\Cache\Adapter\CacheAdapterInterface

For example to use Doctrine cache adapter

class DoctrineCacheAdapter implements CacheAdapterInterface
{
    public function __construct($cache)
    {
        $this->cache = $cache;
    }
    
    // Implement the methods
}

// Build adapter using APC cache driver
$adapter = new DoctrineCacheAdapter(new \Doctrine\Common\Cache\ApcCache());

Also you can have custom hydrators by implementing Sunspikes\Ratelimit\Throttle\Hydrator\DataHydratorInterface

For example to use a Symfony Request object instead of custom URL for ratelimiting

class RequestHydrator implements DataHydratorInterface
{
    public function hydrate($data, $limit, $ttl)
    {
        // Make the key string
        $key = $data->getClientIp() . $data->getPathInfo();

        return new Data($key, $limit, $ttl);
    }
}

// Hydrate the request to Data object
$hydrator = new RequestHydrator();

Then decorate or extend the HydratorFactory to recognize your data

use Hydrator\FactoryInterface;

class MyHydratorFactory implements FactoryInterface
{
    private $defaultFactory;

    public function __construct(FactoryInterface $defaultFactory)
    {
        $this->defaultFactory = $defaultFactory;
    }

    public function make($data)
    {
        if ($data instanceof Request) {
            return new RequestHydrator();
        }

        return $this->defaultFactory->make($data);
    }
}

Throttler types

Elastic Window

An elastic window throttler will allow X requests in Y seconds. Any further access attempts will be counted, but return false as status. Note that the window will be extended with Y seconds on every hit. This means there need to be no hits during Y seconds for the counter to be reset to 0.

See Overview example for instantiation.

Time-based throttlers

All the following throttlers use time functions, thus needing a different factory for construction:

$cacheAdapter = new DesarrollaCacheAdapter((new DesarrollaCacheFactory())->make());
$timeAdapter = new PhpTimeAdapter();

$throttlerFactory = new TimeAwareThrottlerFactory($cacheAdapter, $timeAdapter);
$hydratorFactory = new HydratorFactory();

//$settings = ...
$ratelimiter = new RateLimiter($throttlerFactory, $hydratorFactory, $settings);

Fixed Window

A fixed window throttler will allow X requests in the Y seconds since the first request. Any further access attempts will be counted, but return false as status. The window will not be extended at all.

// Make a rate limiter with limit 120 attempts per minute
$settings = new FixedWindowSettings(120, 60);

Moving Window

A moving window throttler will allow X requests during the previous Y seconds. Any further access attempts will be counted, but return false as status. The window is never extended beyond Y seconds.

// Make a rate limiter with limit 120 attempts per minute
$settings = new MovingWindowSettings(120, 60);

Leaky Bucket

A leaky bucket throttler will allow X requests divided over time Y.

Any access attempts past the threshold T (default: 0) will be delayed by Y / (X - T)

access() will return false if delayed, hit() will return the number of milliseconds waited

Note: Time limit for this throttler is in milliseconds, where it is seconds for the other throttler types!

// Make a rate limiter with limit 120 attempts per minute, start delaying after 30 requests
$settings = new LeakyBucketSettings(120, 60000, 30);

Retrial Queue

The retrial queue encapsulates another throttler. When this throttler receives a hit which would fail on the internal throttler, the request is delayed until the internal throttler has capacity again.

// Make a leaky bucket ratelimiter which delays any overflow
$settings = new RetrialQueueSettings(new LeakyBucketSettings(120, 60000, 120));

Author

Krishnaprasad MG [@sunspikes]

Contributing

Please feel free to send pull requests.

License

This is an open-sourced software licensed under the MIT license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].