Debian Codegraph @

docs/api-guide/throttling.md

raw
1 ---
2 source:
3 - throttling.py
4 ---
5
6 # Throttling
7
8 > HTTP/1.1 420 Enhance Your Calm
9 >
10 > [Twitter API rate limiting response][cite]
11
12 Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
13
14 As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
15
16 Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.
17
18 Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
19
20 Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
21
22 **The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.**
23
24 **The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
25
26 ## How throttling is determined
27
28 As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
29
30 Before running the main body of the view each throttle in the list is checked.
31 If any throttle check fails an `exceptions.Throttled` exception will be raised, and the main body of the view will not run.
32
33 ## Setting the throttling policy
34
35 The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example.
36
37 REST_FRAMEWORK = {
38 'DEFAULT_THROTTLE_CLASSES': [
39 'rest_framework.throttling.AnonRateThrottle',
40 'rest_framework.throttling.UserRateThrottle'
41 ],
42 'DEFAULT_THROTTLE_RATES': {
43 'anon': '100/day',
44 'user': '1000/day'
45 }
46 }
47
48 The rates used in `DEFAULT_THROTTLE_RATES` can be specified over a period of second, minute, hour or day. The period must be specified after the `/` separator using `s`, `m`, `h` or `d`, respectively. For increased clarity, extended units such as `second`, `minute`, `hour`, `day` or even abbreviations like `sec`, `min`, `hr` are allowed, as only the first character is relevant to identify the rate.
49
50 You can also set the throttling policy on a per-view or per-viewset basis,
51 using the `APIView` class-based views.
52
53 from rest_framework.response import Response
54 from rest_framework.throttling import UserRateThrottle
55 from rest_framework.views import APIView
56
57 class ExampleView(APIView):
58 throttle_classes = [UserRateThrottle]
59
60 def get(self, request, format=None):
61 content = {
62 'status': 'request was permitted'
63 }
64 return Response(content)
65
66 If you're using the `@api_view` decorator with function based views you can use the following decorator.
67
68 @api_view(['GET'])
69 @throttle_classes([UserRateThrottle])
70 def example_view(request, format=None):
71 content = {
72 'status': 'request was permitted'
73 }
74 return Response(content)
75
76 It's also possible to set throttle classes for routes that are created using the `@action` decorator.
77 Throttle classes set in this way will override any viewset level class settings.
78
79 @action(detail=True, methods=["post"], throttle_classes=[UserRateThrottle])
80 def example_adhoc_method(request, pk=None):
81 content = {
82 'status': 'request was permitted'
83 }
84 return Response(content)
85
86 ## How clients are identified
87
88 The `X-Forwarded-For` HTTP header and `REMOTE_ADDR` WSGI variable are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `REMOTE_ADDR` variable from the WSGI environment will be used.
89
90 If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `REMOTE_ADDR` value will always be used as the identifying IP address.
91
92 It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](https://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
93
94 Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifying-clients].
95
96 ## Setting up the cache
97
98 The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details.
99
100 If you need to use a cache other than `'default'`, you can do so by creating a custom throttle class and setting the `cache` attribute. For example:
101
102 from django.core.cache import caches
103
104 class CustomAnonRateThrottle(AnonRateThrottle):
105 cache = caches['alternate']
106
107 You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute.
108
109 ## A note on concurrency
110
111 The built-in throttle implementations are open to [race conditions][race], so under high concurrency they may allow a few extra requests through.
112
113 If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See [issue #5181][gh5181] for more details.
114
115 ---
116
117 ## API Reference
118
119 ### AnonRateThrottle
120
121 The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
122
123 The allowed request rate is determined from one of the following (in order of preference).
124
125 * The `rate` property on the class, which may be provided by overriding `AnonRateThrottle` and setting the property.
126 * The `DEFAULT_THROTTLE_RATES['anon']` setting.
127
128 `AnonRateThrottle` is suitable if you want to restrict the rate of requests from unknown sources.
129
130 ### UserRateThrottle
131
132 The `UserRateThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
133
134 The allowed request rate is determined from one of the following (in order of preference).
135
136 * The `rate` property on the class, which may be provided by overriding `UserRateThrottle` and setting the property.
137 * The `DEFAULT_THROTTLE_RATES['user']` setting.
138
139 An API may have multiple `UserRateThrottles` in place at the same time. To do so, override `UserRateThrottle` and set a unique "scope" for each class.
140
141 For example, multiple user throttle rates could be implemented by using the following classes...
142
143 class BurstRateThrottle(UserRateThrottle):
144 scope = 'burst'
145
146 class SustainedRateThrottle(UserRateThrottle):
147 scope = 'sustained'
148
149 ...and the following settings.
150
151 REST_FRAMEWORK = {
152 'DEFAULT_THROTTLE_CLASSES': [
153 'example.throttles.BurstRateThrottle',
154 'example.throttles.SustainedRateThrottle'
155 ],
156 'DEFAULT_THROTTLE_RATES': {
157 'burst': '60/min',
158 'sustained': '1000/day'
159 }
160 }
161
162 `UserRateThrottle` is suitable if you want simple global rate restrictions per-user.
163
164 ### ScopedRateThrottle
165
166 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. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
167
168 The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting using a key from the request "scope".
169
170 For example, given the following views...
171
172 class ContactListView(APIView):
173 throttle_scope = 'contacts'
174 ...
175
176 class ContactDetailView(APIView):
177 throttle_scope = 'contacts'
178 ...
179
180 class UploadView(APIView):
181 throttle_scope = 'uploads'
182 ...
183
184 ...and the following settings.
185
186 REST_FRAMEWORK = {
187 'DEFAULT_THROTTLE_CLASSES': [
188 'rest_framework.throttling.ScopedRateThrottle',
189 ],
190 'DEFAULT_THROTTLE_RATES': {
191 'contacts': '1000/day',
192 'uploads': '20/day'
193 }
194 }
195
196 User requests to either `ContactListView` or `ContactDetailView` would be restricted to a total of 1000 requests per-day. User requests to `UploadView` would be restricted to 20 requests per day.
197
198 ---
199
200 ## Custom throttles
201
202 To create a custom throttle, override `BaseThrottle` and implement `.allow_request(self, request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
203
204 Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`.
205
206 If the `.wait()` method is implemented and the request is throttled, then a `Retry-After` header will be included in the response.
207
208 ### Example
209
210 The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
211
212 import random
213
214 class RandomRateThrottle(throttling.BaseThrottle):
215 def allow_request(self, request, view):
216 return random.randint(1, 10) != 1
217
218 [cite]: https://developer.twitter.com/en/docs/basics/rate-limiting
219 [permissions]: permissions.md
220 [identifying-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
221 [cache-setting]: https://docs.djangoproject.com/en/stable/ref/settings/#caches
222 [cache-docs]: https://docs.djangoproject.com/en/stable/topics/cache/#setting-up-the-cache
223 [gh5181]: https://github.com/encode/django-rest-framework/issues/5181
224 [race]: https://en.wikipedia.org/wiki/Race_condition#Data_race