├── .github ├── FUNDING.yml └── workflows │ └── main.yml ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── config └── .gitkeep └── src └── ThrottleSimultaneousRequests.php /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: imliam 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | jobs: 8 | test: 9 | runs-on: ${{ matrix.os }} 10 | 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | os: [ubuntu-latest] 15 | php: [8.4, 8.3, 8.2] 16 | laravel: [^12.0, ^11.0] 17 | dependency-version: [prefer-lowest, prefer-stable] 18 | include: 19 | - laravel: ^11.0 20 | testbench: ^9.0 21 | - laravel: ^12.0 22 | testbench: ^10.0 23 | 24 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} 25 | 26 | steps: 27 | - name: Checkout code 28 | uses: actions/checkout@v4 29 | 30 | - name: Setup PHP 31 | uses: shivammathur/setup-php@v2 32 | with: 33 | php-version: ${{ matrix.php }} 34 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick 35 | coverage: none 36 | 37 | - name: Install dependencies 38 | run: | 39 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 40 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction 41 | 42 | - name: Execute tests 43 | run: vendor/bin/phpunit 44 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-throttle-concurrent-requests` will be documented in this file 4 | 5 | ## 1.0.0 - 2018-07-11 6 | 7 | - Initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code held within. They make the code freely available in the hope that it will be of use to other developers. It would be extremely unfair for them to suffer abuse or anger for their hard work. 10 | 11 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the world that developers are civilized and selfless people. 12 | 13 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient quality to benefit the project. Many developers have different skill sets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 14 | 15 | ## Viability 16 | 17 | When requesting or submitting new features, first consider whether it might be useful to others. Open source projects are used by many developers, who may have entirely different needs to your own. Think about whether or not your feature is likely to be used by other users of the project. 18 | 19 | ## Procedure 20 | 21 | Before filing an issue: 22 | 23 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 24 | - Check to make sure your feature suggestion isn't already present within the project. 25 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 26 | - Check the pull requests tab to ensure that the feature isn't already in progress. 27 | 28 | Before submitting a pull request: 29 | 30 | - Check the codebase to ensure that your feature doesn't already exist. 31 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 32 | 33 | ## Requirements 34 | 35 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 36 | 37 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 38 | 39 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 40 | 41 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 42 | 43 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 44 | 45 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 46 | 47 | **Happy coding**! 48 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Liam Hammett 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Throttle Simultaneous Requests Middleware 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/imliam/laravel-throttle-simultaneous-requests.svg)](https://packagist.org/packages/imliam/laravel-throttle-simultaneous-requests) 4 | [![Total Downloads](https://img.shields.io/packagist/dt/imliam/laravel-throttle-simultaneous-requests.svg)](https://packagist.org/packages/imliam/laravel-throttle-simultaneous-requests) 5 | [![License](https://img.shields.io/github/license/imliam/laravel-throttle-simultaneous-requests.svg)](LICENSE.md) 6 | 7 | Throttle the current user's requests based on how many requests are currently being executed, in case any are time consuming before giving a response. 8 | 9 | This helps when some endpoints are more resource-intensive than others, and stops users from retrying requests that may not have even completed yet. 10 | 11 | This forces users of your API to interact in a different way by queuing their requests appropriately instead of spamming until they reach the request limit. 12 | 13 | When performing an action only the current user can perform, this also helps to ensure that the endpoint has a form of *idempotency* and any side effects can only occur once until a subsequent request is made. 14 | 15 | 16 | 17 | - [Laravel Throttle Simultaneous Requests Middleware](#laravel-throttle-simultaneous-requests-middleware) 18 | - [Installation](#installation) 19 | - [Usage](#usage) 20 | - [Why not use queues?](#why-not-use-queues) 21 | - [Why is no `Retry-After` header sent?](#why-is-no-retry-after-header-sent) 22 | - [Testing](#testing) 23 | - [Changelog](#changelog) 24 | - [Contributing](#contributing) 25 | - [Security](#security) 26 | - [Credits](#credits) 27 | - [License](#license) 28 | 29 | 30 | 31 | ## Installation 32 | 33 | You can install the package with [Composer](https://getcomposer.org/) using the following command: 34 | 35 | ```bash 36 | composer require imliam/laravel-throttle-simultaneous-requests:^2.0.0 37 | ``` 38 | 39 | Once installed to your project, add the middleware to your `App\Http\Kernel::$routeMiddleware` array. 40 | 41 | ```php 42 | protected $routeMiddleware = [ 43 | // ... 44 | 'simultaneous' => \ImLiam\ThrottleSimultaneousRequests\ThrottleSimultaneousRequests::class, 45 | ]; 46 | ``` 47 | 48 | ## Usage 49 | 50 | You can use the middleware like any other. For example, to limit a particular endpoint to only 3 concurrent requests by the same user: 51 | 52 | ``` php 53 | Route::get('/', 'HomeController@index')->middleware('simultaneous:3'); 54 | ``` 55 | 56 | ### Why not use queues? 57 | 58 | Queues have their place to defer time consuming tasks to a later date, however they are not always the most appropriate solution for a task. A given task could require use of limited hardware resources, or require some other kind of processing that does not make sense to run concurrently. 59 | 60 | [See how Stripe use concurrent request limiters...](https://stripe.com/blog/rate-limiters) 61 | 62 | ### Why is no `Retry-After` header sent? 63 | 64 | Most typical rate limiting solutions limit a user to a number of requests within a set time period, such as 100 requests per minute, so include a `Retry-After` header to let the requestor know when they are available to try again. 65 | 66 | This middleware does not add such a header to the response, due to the nature of the request taking a longer amount of time to complete there is no guaranteed time where the requestor can retry the request. Instead, it is up to the requestor to determine when to retry. 67 | 68 | ## Testing 69 | 70 | ``` bash 71 | composer test 72 | ``` 73 | 74 | ## Changelog 75 | 76 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 77 | 78 | ## Contributing 79 | 80 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 81 | 82 | ### Security 83 | 84 | If you discover any security related issues, please email liam@liamhammett.com instead of using the issue tracker. 85 | 86 | ## Credits 87 | 88 | - [Liam Hammett](https://github.com/imliam) 89 | - [All Contributors](../../contributors) 90 | 91 | ## License 92 | 93 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 94 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "imliam/laravel-throttle-simultaneous-requests", 3 | "description": "Throttle the current user's requests based on how many requests are currently being executed.", 4 | "keywords": [ 5 | "imliam", 6 | "laravel", 7 | "middleware", 8 | "throttle", 9 | "api", 10 | "laravel-throttle-simultaneous-requests" 11 | ], 12 | "homepage": "https://github.com/imliam/laravel-throttle-simultaneous-requests", 13 | "license": "MIT", 14 | "authors": [ 15 | { 16 | "name": "Liam Hammett", 17 | "email": "liam@liamhammett.com", 18 | "homepage": "https://liamhammett.com", 19 | "role": "Developer" 20 | } 21 | ], 22 | "require": { 23 | "php": "^8.0", 24 | "illuminate/http": "^11.0|^12.0", 25 | "illuminate/support": "^11.0|^12.0" 26 | }, 27 | "require-dev": { 28 | "phpunit/phpunit": "^11.0", 29 | "larapack/dd": "^1.0", 30 | "orchestra/testbench": "^9.0|^10.0" 31 | }, 32 | "autoload": { 33 | "psr-4": { 34 | "ImLiam\\ThrottleSimultaneousRequests\\": "src" 35 | } 36 | }, 37 | "autoload-dev": { 38 | "psr-4": { 39 | "ImLiam\\ThrottleSimultaneousRequests\\Tests\\": "tests" 40 | } 41 | }, 42 | "scripts": { 43 | "test": "vendor/bin/phpunit", 44 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage", 45 | "test:windows": "vendor\\bin\\phpunit", 46 | "test-coverage:windows": "vendor\\bin\\phpunit --coverage-html coverage" 47 | }, 48 | "config": { 49 | "sort-packages": true 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /config/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imliam/laravel-throttle-simultaneous-requests/5c01e906c74df7fd7911baa59c55b461c89a35c9/config/.gitkeep -------------------------------------------------------------------------------- /src/ThrottleSimultaneousRequests.php: -------------------------------------------------------------------------------- 1 | limit = (int) $limit; 52 | $this->setRequestSignature($request); 53 | 54 | if ($this->limit <= Cache::get($this->signature)) { 55 | throw new ThrottleRequestsException('Too Many Attempts.', null, $this->getHeaders()); 56 | } 57 | 58 | $this->increment(); 59 | 60 | return $next($request); 61 | } 62 | 63 | /** 64 | * Handle the outgoing response. 65 | * 66 | * @param \Illuminate\Http\Request $request 67 | * @param \Illuminate\Http\Response $response 68 | * @return mixed 69 | */ 70 | public function terminate($request, $response) 71 | { 72 | $this->decrement(); 73 | 74 | return $response; 75 | } 76 | 77 | /** 78 | * Get the number of remaining concurrent requests the user can run. 79 | */ 80 | protected function getRemainingRequests(int $limit): int 81 | { 82 | return max(0, $limit - Cache::get($this->signature)); 83 | } 84 | 85 | /** 86 | * Get headers to denote the current rate limits the user has. 87 | */ 88 | protected function getHeaders(): array 89 | { 90 | return [ 91 | 'X-RateLimit-Limit' => $this->limit, 92 | 'X-RateLimit-Remaining' => $this->getRemainingRequests($this->limit), 93 | ]; 94 | } 95 | 96 | /** 97 | * Manually set the signature for the current request. 98 | * 99 | * @param \Illuminate\Http\Request $request 100 | * @param string|null $signature 101 | * @return string 102 | */ 103 | public function setRequestSignature($request, $signature = null) 104 | { 105 | if (!empty($this->signature)) { 106 | return $signature; 107 | } 108 | 109 | $signature = $this->prefix . sha1($signature ?? $this->resolveRequestSignature($request)); 110 | $this->signature = $signature; 111 | 112 | return $signature; 113 | } 114 | 115 | /** 116 | * Resolve the request signature for the current requesting user. 117 | * 118 | * @param \Illuminate\Http\Request $request 119 | * @return string 120 | * @throws \RuntimeException 121 | */ 122 | protected function resolveRequestSignature($request) 123 | { 124 | if (!empty($this->signature)) { 125 | return $this->signature; 126 | } 127 | 128 | if ($user = $request->user()) { 129 | return $user->getAuthIdentifier(); 130 | } 131 | 132 | if ($route = $request->route()) { 133 | return $route->getDomain().'|'.$request->ip(); 134 | } 135 | 136 | throw new RuntimeException('Unable to generate the request signature. Route unavailable.'); 137 | } 138 | 139 | /** 140 | * Increment the count of currently running requests for the current user by 1. 141 | * 142 | * @return integer 143 | */ 144 | protected function increment(): int 145 | { 146 | $value = 1; 147 | 148 | if (Cache::has($this->signature)) { 149 | $value = Cache::get($this->signature) + 1; 150 | } 151 | 152 | Cache::put($this->signature, $value, $this->cacheForSeconds); 153 | 154 | return $value; 155 | } 156 | 157 | /** 158 | * Decrement the count of currently running requests for the current user by 1. 159 | */ 160 | protected function decrement(): int 161 | { 162 | if (! Cache::has($this->signature)) { 163 | return 0; 164 | } 165 | 166 | $value = Cache::get($this->signature) - 1; 167 | 168 | if ($value === 0) { 169 | Cache::forget($this->signature); 170 | return 0; 171 | } 172 | 173 | Cache::put($this->signature, $value); 174 | 175 | return $value; 176 | } 177 | } 178 | --------------------------------------------------------------------------------