Contributed by
Wouter De Jong
in #37546.
A “rate limiter” controls how frequently some event (e.g. an HTTP request or a login attempt) is allowed to happen. Rate limiting is commonly used as a defensive measure to protect services from excessive use.
Symfony 5.2 introduces a new RateLimiter component so you can add those protections to your own applications. For example, imagine that you want to apply the same restrictions as GitHub to your own APIs when used anonymously: 60 requests per hour and identify requests by the originating IP address.
First, configure a new rate limiter as follows:
1 2 3 4 5 6 7 | # config/packages/rate_limiter.yamlframework:rate_limiter:anonymous_api:strategy:fixed_windowlimit:60interval:'60minutes' |
Now, inject the rate limiter in your controllers or services and use it to check if the request should be allowed or not:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // src/Controller/ApiController.phpnamespaceApp\Controller;useSymfony\Bundle\FrameworkBundle\Controller\AbstractController;useSymfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;useSymfony\Component\RateLimiter\Limiter;classApiControllerextendsAbstractController{// the variable name must be: "rate limiter name" + "limiter" suffixpublicfunctionindex(Limiter$anonymousApiLimiter){// create a limiter based on the client's IP address// (you can also use a username/email, an API key, etc.)$limiter=$anonymousApiLimiter->create($request->getClientIp());// try to consume a resource; if it's accepted, serve the request// otherwise, return a 429 (Too Many Requests) errorif(false===$anonymousApiLimiter->consume()->isAccepted()){thrownewTooManyRequestsHttpException();}// ...}// ...} |
That’s it! The RateLimiter component implements many other features and provides two different strategies to control the limits: “fixed window” and “token bucket”. Read the RateLimiter docs to learn all about its features.