Understanding throttling classes and goals

So far, we haven't established any limits on the usage of our API, and therefore, both authenticated and unauthenticated users can compose and send as many requests as they want to. We only took advantage of the pagination features available in Django REST Framework to specify how we wanted large result sets to be split into individual pages of data. However, any user can compose and send thousands of requests to be processed without any kind of limitation.

Obviously, it is not a good idea to deploy such an API encapsulated in a microservice in a cloud platform. A wrong usage of the API by any user could cause the microservice to consume a huge amount of resources, and the cloud platform bills would reflect this situation.

We will use the throttling capabilities available in Django REST Framework to configure the following global limitations to the usage of our API, based on whether the requests come from unauthenticated or authenticated users. We will define the following configuration:

  • Unauthenticated users: They will be able to run a maximum of 5 requests per hour
  • Authenticated users: They will be able to run a maximum of 20 requests per hour

In addition, we want to configure a maximum of 25 requests per hour to the ESRB ratings-related views, no matter whether the user is authenticated or not.

Django REST Framework provides three throttling classes (as listed in the following table), in the rest_framework.throttling module. All of them are subclasses of the SimpleRateThrottle superclass, which is a subclass of the BaseThrottle superclass. The classes allow us to set the maximum number of requests per period that will be computed based on different mechanisms to determine the previous request information to specify the scope. The previous request information for throttling is stored in the cache and the classes override the get_cache_key method that determines the scope:

Throttling class name

Description

AnonRateThrottle

This class limits the rate of requests that an anonymous user can make. The IP address of the request is the unique cache key. Hence, bear in mind that all the requests coming from the same IP address will accumulate the total number of requests.

UserRateThrottle

This class limits the rate of requests that a specific user can make. For authenticated users, the authenticated user id is the unique cache key. For anonymous users, the IP address of the request is the unique cache key.

ScopedRateThrottle

This class limits the rate of requests for specific parts of the API identified with the value assigned to the throttle_scope property. The class is useful when we want to restrict access to specific parts of the API with different rates.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.114.125