The RateLimiter component controls how often an action can happen in your application. Symfony 8.2 makes it possible to create limiters at runtime and adds many features to the #[RateLimit] attribute introduced in Symfony 8.1.
Building Rate Limiters at Runtime
Rate limiters are defined in the framework.rate_limiter configuration and
each of them is injected separately. This doesn't work well when a service needs
many one-off limiters or when the limits are only known at runtime (e.g. because
they depend on the plan of the customer).
Symfony 8.2 adds a RateLimiterBuilder service to create limiter factories
on the fly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
use Symfony\Component\RateLimiter\RateLimiterBuilder;
class ReportController extends AbstractController
{
public function export(RateLimiterBuilder $limiterBuilder): Response
{
$plan = $this->getUser()->getPlan();
$limiter = $limiterBuilder
->slidingWindow(
id: 'export_'.$plan->getName(),
limit: $plan->getExportsPerHour(),
interval: '1 hour',
)
->create($this->getUser()->getUserIdentifier());
if (!$limiter->consume()->isAccepted()) {
throw new TooManyRequestsHttpException();
}
// ...
}
}
The builder provides the slidingWindow(), fixedWindow() and tokenBucket()
methods, compound() to combine several of them and noop() to disable
rate limiting conditionally. All of them return a RateLimiterFactoryInterface,
so you use the result like any configured limiter. The id argument is the
namespace used to store the state, so limiters created with the same id
share their state.
Exposing the Rate Limit in Response Headers
When #[RateLimit] rejects a request, the response includes a Retry-After
header. However, accepted requests tell nothing to the client about its remaining
quota. In Symfony 8.2, the new exposeHeaders option adds the X-RateLimit-*
headers used by many public APIs to both accepted and rejected responses:
1 2
#[RateLimit('api', exposeHeaders: true)]
public function index(): JsonResponse { /* ... */ }
1 2 3 4
HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 97
X-RateLimit-Reset: 1787403071
The value of X-RateLimit-Reset is a Unix timestamp. It comes from the new
getResetAt() method of the RateLimit objects returned by limiters, which tells
when the limiter is back to its full capacity. Responses that include these headers
are marked as private, so shared caches never store the counters of a client.
When several attributes apply to the same controller, the headers describe the limiter that is closest to rejecting the request, among those that enable the option. If the limiter that rejects a request doesn't enable it, the response includes none of these headers.
Caution
The option is disabled by default because these headers tell clients exactly how many attempts they have left. Don't enable it for sensitive limiters, like the ones that protect login or password reset forms.
Applying Rate Limits Conditionally
The #[RateLimit] attribute applies to every request that reaches its controller
and you could only narrow it down by HTTP method. That's not enough for common
needs, like using different quotas for anonymous and logged in users.
Symfony 8.2 adds an if option to define when the rate limit applies. Its
value can be a boolean, a closure or an expression, which can use security
functions like is_authenticated() and is_granted():
1 2 3 4 5 6 7 8 9 10 11 12 13 14
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpKernel\Attribute\RateLimit;
class ApiController extends AbstractController
{
// anonymous requests are limited by IP; the rest get a larger quota per user
#[RateLimit('anonymous_api', if: new Expression('!is_authenticated()'))]
#[RateLimit(
'user_api',
key: new Expression('current_user().getUserIdentifier()'),
if: new Expression('is_authenticated()'),
)]
public function index(): JsonResponse { /* ... */ }
}
When the condition is false, the attribute is skipped and no tokens are consumed. Keep in mind that a request that matches none of the conditions is not rate limited at all. Also, avoid conditions based on data sent by the client (e.g. a request header) because that would let clients choose their own limiter.
Injecting the Consumed Rate Limit
Some controllers need the state of the limiter that the attribute has just
consumed, for example to show the remaining quota to the user. In Symfony 8.2,
add an argument typed with the RateLimit class of the RateLimiter component
and Symfony injects the result of the attribute, without consuming more tokens:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
use Symfony\Component\HttpKernel\Attribute\RateLimit;
use Symfony\Component\RateLimiter\RateLimit as ConsumedRateLimit;
class ApiController extends AbstractController
{
#[RateLimit('api')]
public function index(ConsumedRateLimit $rateLimit): JsonResponse
{
return $this->json([
// ...
'quota' => [
'remaining' => $rateLimit->getRemainingTokens(),
'resets_at' => $rateLimit->getResetAt()?->format(\DATE_ATOM),
],
]);
}
}
When several attributes apply, the argument gets the rate limit with the fewest
remaining calls. If no attribute applies to the request (e.g. because the if
or methods options exclude it), the argument must be nullable or have a
default value. Otherwise, Symfony throws a LogicException.
Listening to Rejected Requests
When a request exceeds a limit, the #[RateLimit] attribute returns a 429
response and nothing else happens. There was no way to know which limiter
rejected the request or for which key, which is useful for logging, metrics
and spotting abusive clients.
In Symfony 8.2, the attribute dispatches a RateLimitExceededEvent right
before rejecting the request:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\RateLimiter\Event\RateLimitExceededEvent;
final class RateLimitLogger
{
public function __construct(
private LoggerInterface $logger,
) {
}
#[AsEventListener]
public function onRateLimitExceeded(RateLimitExceededEvent $event): void
{
$this->logger->warning('Rate limit "{limiter}" exceeded for "{key}" until {retry_after}.', [
'limiter' => $event->getLimiterName(),
'key' => $event->getKey(),
'retry_after' => $event->getRateLimit()->getRetryAfter()->format(\DATE_ATOM),
]);
}
}
The event is informational: listeners can't prevent the rejection or change the
response. It's only dispatched by the #[RateLimit] attribute, not by other
features that use rate limiters, like login throttling.
Rejecting Requests Before Resolving Arguments
Until now, #[RateLimit] consumed its tokens after resolving the controller
arguments. This means that requests that were going to be rejected still ran
all the value resolvers, which can be costly (e.g. loading an entity from the
database).
In Symfony 8.2, the attribute consumes its tokens as soon as the controller is
known. The only exception is when the key or if options need the
arguments: when they are a closure or an expression that uses the args variable:
1 2 3 4 5 6 7
// tokens are consumed first: rejected requests no longer query the database
#[RateLimit('api')]
public function show(Invoice $invoice): Response { /* ... */ }
// the key reads an argument, so tokens are consumed after resolving them
#[RateLimit('api', key: new Expression('args["invoice"].getCustomer().getEmail()'))]
public function download(Invoice $invoice): Response { /* ... */ }
This change needs no configuration, but it has a consequence: the rate limits
consumed early now run before attributes like #[IsGranted], whatever their order in the
controller. Requests that are later denied by those attributes consume tokens too.