Skip to the stories
AI & ML

Symfony 8.2 Adds Runtime Rate Limits, Quota Headers and Rejection Events

  • Javier Eguiluz
  • 501 reads

Symfony 8.2 makes rate limits easier to tailor at runtime and adds quota visibility, conditional rules, controller access to limiter state and rejection events.

Symfony 8.2 Adds Runtime Rate Limits, Quota Headers and Rejection Events

Symfony 8.2 gives teams more control over where rate limits come from, when they apply and what an application can do with their state. The changes extend the RateLimiter component and the #[RateLimit] attribute added in Symfony 8.1. For applications with plan-based quotas, public APIs or expensive controller argument resolution, the practical gains are in flexibility and reduced wasted work.

Kevin Bond

Build limits from runtime data

Previously, applications defined limiters in framework.rate_limiter configuration and injected each one separately. That setup becomes awkward when a service needs many short-lived limiter configurations or when the limit depends on information available only during a request, such as a customer’s plan.

Symfony 8.2 adds a RateLimiterBuilder service that creates limiter factories in code. A controller can read a user’s plan, set an hourly export allowance from that plan, and create a limiter keyed to the user. The example uses a sliding window and calls consume() to check whether the export is accepted; if not, it raises a TooManyRequestsHttpException.

Ayyoub AFW-ALLAH

The builder also supports fixed windows, token buckets, compound limiters that combine several strategies, and a no-operation limiter for cases where limiting should be disabled. Each method returns a RateLimiterFactoryInterface, so the resulting factory works like one created through configuration. Its id determines the namespace for stored state: factories using the same identifier share that state. Teams should choose identifiers with that sharing behavior in mind, especially when building limiters dynamically.

Show clients their remaining quota

With Symfony 8.1’s attribute, rejected requests already received a Retry-After header. Accepted requests, however, gave clients no standard indication of how much capacity remained. Symfony 8.2 adds the exposeHeaders option to include X-RateLimit-* headers on accepted and rejected responses.

HypeMC

For example, an API can return the configured limit, remaining requests and reset time. X-RateLimit-Reset is a Unix timestamp, supplied through the new getResetAt() method on the RateLimit object. Responses carrying these headers are marked private, which keeps shared caches from storing one client’s quota counters and serving them to others.

When multiple rate-limit attributes apply to a controller, Symfony reports the limiter closest to rejecting the request among the limiters that have header exposure enabled. If the limiter that rejects the request has exposure disabled, the response has no rate-limit headers. The option is off by default, and that’s a sensible starting point: exposing remaining attempts can reveal useful information to someone probing a login or password-reset endpoint. Enable it selectively for APIs where client-side quota tracking is useful.

Marie CHARLES

Apply different rules to different requests

The attribute previously applied to every request reaching its controller, with the HTTP method as the main way to narrow its scope. Symfony 8.2 adds an if option, which can take a boolean, closure or expression. Expressions can use security functions such as is_authenticated() and is_granted().

That makes it possible to apply one limiter to anonymous traffic, keyed by IP, and another to authenticated users, keyed by their user identifier. When a condition is false, Symfony skips that attribute and consumes no tokens for it. But if a request matches none of the configured conditions, it receives no rate limit from those attributes. Conditions should be based on trusted application context; letting a client-controlled value choose the limiter could let that client select its own quota.

Nicolas Grekas

Use limiter state inside the controller

A controller can now receive the result of the rate-limit check as an argument typed with the RateLimiter component’s RateLimit class. That object exposes values such as remaining tokens and reset time, so a response can include quota details without consuming another token to retrieve them.

If several attributes apply, Symfony injects the result with the fewest remaining calls. A controller argument must be nullable or have a default value if the request may skip every relevant attribute, for example because of an if condition or HTTP-method restriction. Otherwise, Symfony throws a LogicException. This gives teams a direct way to return quota information in an API payload, alongside or instead of response headers.

Observe rejected requests and avoid wasted work

Symfony 8.2 dispatches a RateLimitExceededEvent immediately before the #[RateLimit] attribute rejects a request with a 429 response. Event listeners can use it to record which limiter and key were exceeded, along with the retry time. That information can support logging and metrics or help teams identify clients that repeatedly hit a limit.

The event is informational: listeners cannot cancel the rejection or change its response. It is also limited to rejections caused by the attribute; other features that use rate limiters, including login throttling, do not dispatch it.

There’s a performance change too. Symfony now consumes tokens as soon as it knows which controller will handle the request, before resolving controller arguments. A request that will be rejected can therefore avoid expensive value resolvers, such as loading an entity from a database. The exception is when the limiter’s key or if option needs controller arguments through a closure or an expression using args; Symfony must resolve those arguments first.

Early checks have a trade-off: they run before attributes such as #[IsGranted], regardless of their order on the controller. A request later denied by an access check will still have consumed tokens. Teams adopting the change should review how their limits interact with access checks and argument-based keys. The key question for the next release is how these controls fit together in real applications, particularly where dynamic quotas, authentication and costly request handling overlap.

Source: Javier Eguiluz · symfony.com

From the same set