This article is part of the CakeDC Advent Calendar 2025 (December 21st 2025)
Rate limiting a specific endpoint of your application can be a life saver. Sometimes you can't optimize the endpoint and it'll be expensive in time or CPU, or the endpoint has a business restriction for a given user.
In the past, I've been using https://github.com/UseMuffin/Throttle a number of times to provide rate limiting features to CakePHP.
Recently, I've been watching the addition of the RateLimitMiddleware to CakePHP 5.3, I think it was a great idea to incorporate these features into the core and I'll bring you a quick example about how to use it in your projects.
Let's imagine you have a CakePHP application with an export feature that will take some extra CPU to produce an output, you want to ensure the endpoint is not abused by your users.
In order to limit the access to the endpoint, add the following configuration to your config/app.php
// define a cache configuration, Redis could be a good option for a fast and distributed approach
'rate_limit' => [
'className' => \Cake\Cache\Engine\RedisEngine::class,
'path' => CACHE,
'url' => env('CACHE_RATE_LIMIT_URL', null),
],
Then, in your src/Application.php middleware method, create one or many configurations for your rate limits. The middleware allows a lot of customization, for example to select the strategy, or how are you going to identify the owner of the rate limit.
->add(new RateLimitMiddleware([
'strategy' => RateLimitMiddleware::STRATEGY_FIXED_WINDOW,
'identifier' => RateLimitMiddleware::IDENTIFIER_IP,
'limit' => 5,
'window' => 10,
'cache' => 'rate_limit',
'skipCheck' => function ($request) {
return !(
$request->getParam('controller') === 'Reports' &&
$request->getParam('action') === 'index'
);
}
]))
In this particular configuration we are going to limit the access to the /reports/index endpoint (we skip everything else) to 5 requests every 10 seconds.
You can learn more about the middleware configuration here https://github.com/cakephp/docs/pull/8063 while the final documentation is being finished.
This article is part of the CakeDC Advent Calendar 2025 (December 21st 2025)
BUT...
It is not like we want to detroy what you have created but...
And we have to report it, it is our job...
It is not like we think
I mean
I know you think
But remmember we are here to help xD
Happy Holidays to ya'll folks!