DEV Community

Cover image for Restrain the Rate of Requests with Throttling in Django
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on

Restrain the Rate of Requests with Throttling in Django

If the server is working and the server application is running, there is no way a request can't be executed by the server and not return a response or an error.

However, there may be times when you want to regulate the number of requests on a specific endpoint.

Problem

You have a special endpoint for SMS verification when a password change request is made. Sounds nice, huh? Until you have a special user who will click on the button to request the SMS 10 times and the requests will be executed. That means 9 costly SMS were billed.

Not great! We want a way to only allow the next SMS requested after 1 minute. How to do it in Django?

Solution

We'll use throttling. It's similar to permissions in a way it determines if a request should be allowed. But it's used to indicate a temporary state and is used to control the rate of requests that clients can make to an API.

Let's say you have the SMS viewset that is registered in the routers.py file like this.

class SMSViewSet(viewsets.ViewSet):
    http_method_names = ("post",)

...
router.register(r"password", viewsets.SMSViewSet, basename="password")
Enter fullscreen mode Exit fullscreen mode

Before configuring, we need to add a new attribute to the SMSViewSet class called throttle_scope.

class SMSViewSet(viewsets.ViewSet):
    http_method_names = ("post",)
    throttle_scope = "password-reset"
...
Enter fullscreen mode Exit fullscreen mode

And finally, in the REST_FRAMEWORK configuration in the settings.py file, add the DEFAULT_THROTTLE_CLASSES and the DEFAULT_THROTTLE_RATES settings.

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.ScopedRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'password-reset': '1/minute',
    }
}
Enter fullscreen mode Exit fullscreen mode

Following the documentation, The ScopedRateThrottle class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a .throttle_scope property.

You can learn more about throttling here.

Article posted using bloggu.io. Try it for free.

Top comments (1)

Collapse
 
fayomihorace profile image
Horace FAYOMI

Thanks a lot for this hint.