Throttling#
Base#
- class dmr.throttling.SyncThrottle(max_requests: int, duration_in_seconds: Rate | int, *, cache_key: BaseThrottleCacheKey | None = None, backend: _BackendT | None = None, algorithm: BaseThrottleAlgorithm | None = None, response_headers: Iterable[BaseResponseHeadersProvider] | None = None)[source]#
Sync throttle type for sync endpoints.
Added in version 0.7.0.
- __call__(endpoint: Endpoint, controller: Controller[BaseSerializer], lock: AbstractContextManager[Any, Any]) None[source]#
Put your throttle business logic here.
Return
Noneif throttle check passed. Raisedmr.exceptions.TooManyRequestsErrorif throttle check failed. Raisedmr.response.APIErrorif you want to change the return code, for example, when some data is missing or has wrong format.
- __replace__(*, max_requests: int | None = None, duration_in_seconds: Rate | int | None = None, cache_key: BaseThrottleCacheKey | None = None, backend: _BackendT | None = None, algorithm: BaseThrottleAlgorithm | None = None, response_headers: Iterable[BaseResponseHeadersProvider] | None = None) Self#
Return a copy of this throttle, overriding only the given fields.
Any argument left as
Nonekeeps this throttle’s current value, soreplace(max_requests=2)changes just the limit. Also backscopy.replace(Python 3.13+) through__replace__.Added in version 0.12.0.
- collect_response_headers(endpoint: Endpoint, controller: Controller[BaseSerializer], remaining: int, reset: int, *, report_all: bool = False) dict[str, str]#
Collects response headers for all
response_headersclasses.
- full_cache_key(endpoint: Endpoint, controller: Controller[BaseSerializer]) str | None#
Get the full cache key value.
- provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) list[ResponseSpec]#
Provides responses that can happen when throttle triggers.
- replace(*, max_requests: int | None = None, duration_in_seconds: Rate | int | None = None, cache_key: BaseThrottleCacheKey | None = None, backend: _BackendT | None = None, algorithm: BaseThrottleAlgorithm | None = None, response_headers: Iterable[BaseResponseHeadersProvider] | None = None) Self#
Return a copy of this throttle, overriding only the given fields.
Any argument left as
Nonekeeps this throttle’s current value, soreplace(max_requests=2)changes just the limit. Also backscopy.replace(Python 3.13+) through__replace__.Added in version 0.12.0.
- report_usage(endpoint: Endpoint, controller: Controller[BaseSerializer]) dict[str, str][source]#
Report throttle usage stats.
- validate(controller_cls: type[Controller[BaseSerializer]], metadata: EndpointMetadata) None#
Validate throttling configuration at import time.
Added in version 0.16.0.
- class dmr.throttling.AsyncThrottle(max_requests: int, duration_in_seconds: Rate | int, *, cache_key: BaseThrottleCacheKey | None = None, backend: _BackendT | None = None, algorithm: BaseThrottleAlgorithm | None = None, response_headers: Iterable[BaseResponseHeadersProvider] | None = None)[source]#
Async throttle type for async endpoints.
Added in version 0.7.0.
- async __call__(endpoint: Endpoint, controller: Controller[BaseSerializer], lock: AbstractAsyncContextManager[Any, Any]) None[source]#
Put your throttle business logic here.
Return
Noneif throttle check passed. Raisedmr.exceptions.TooManyRequestsErrorif throttle check failed. Raisedmr.response.APIErrorif you want to change the return code, for example, when some data is missing or has wrong format.
- __replace__(*, max_requests: int | None = None, duration_in_seconds: Rate | int | None = None, cache_key: BaseThrottleCacheKey | None = None, backend: _BackendT | None = None, algorithm: BaseThrottleAlgorithm | None = None, response_headers: Iterable[BaseResponseHeadersProvider] | None = None) Self#
Return a copy of this throttle, overriding only the given fields.
Any argument left as
Nonekeeps this throttle’s current value, soreplace(max_requests=2)changes just the limit. Also backscopy.replace(Python 3.13+) through__replace__.Added in version 0.12.0.
- collect_response_headers(endpoint: Endpoint, controller: Controller[BaseSerializer], remaining: int, reset: int, *, report_all: bool = False) dict[str, str]#
Collects response headers for all
response_headersclasses.
- full_cache_key(endpoint: Endpoint, controller: Controller[BaseSerializer]) str | None#
Get the full cache key value.
- provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) list[ResponseSpec]#
Provides responses that can happen when throttle triggers.
- replace(*, max_requests: int | None = None, duration_in_seconds: Rate | int | None = None, cache_key: BaseThrottleCacheKey | None = None, backend: _BackendT | None = None, algorithm: BaseThrottleAlgorithm | None = None, response_headers: Iterable[BaseResponseHeadersProvider] | None = None) Self#
Return a copy of this throttle, overriding only the given fields.
Any argument left as
Nonekeeps this throttle’s current value, soreplace(max_requests=2)changes just the limit. Also backscopy.replace(Python 3.13+) through__replace__.Added in version 0.12.0.
- async report_usage(endpoint: Endpoint, controller: Controller[BaseSerializer]) dict[str, str][source]#
Async report throttle usage stats.
- validate(controller_cls: type[Controller[BaseSerializer]], metadata: EndpointMetadata) None#
Validate throttling configuration at import time.
Added in version 0.16.0.
- final class dmr.throttling.SyncOrAsyncThrottle(_sync_throttle: _SyncThrottleT, _async_throttle: _AsyncThrottleT)[source]#
Throttle that selects between a sync and async instance.
Use in global settings to apply a single throttling rule to both sync and async endpoints. Not allowed on controller or endpoint level.
Added in version 0.11.0.
Changed in version 0.16.0: Now it is generic.
- resolve(*, is_async: Literal[True]) _AsyncThrottleT[source]#
- resolve(*, is_async: Literal[False]) _SyncThrottleT
- resolve(*, is_async: bool) _AsyncThrottleT | _SyncThrottleT
Return the throttle instance matching is_async requirement.
Changed in version 0.16.0: Replaced throttle_cls parameter with simpler is_async.
- final class dmr.throttling.Rate(*values)[source]#
Throttling rates in seconds.
- second#
1 second.
- minute#
60 seconds.
- hour#
60 * 60 seconds.
- day#
24 * 60 * 60 seconds.
- class dmr.throttling.ThrottlingReport(controller: Controller[BaseSerializer])[source]#
Get throttling data to be reported in response headers.
Unlike
dmr.exceptions.TooManyRequestsError, which reports the first stat for throttle that is failing, it reports all stats for all throttles.It will make N (which is the number of throttles) requests to cache.
Warning
This class does not handle exceptions at all. Because we don’t know how to report headers for failing cache connections. If you want to handle errors, catch them explicitly.
Added in version 0.7.0.
Backends#
- class dmr.throttling.backends.CachedRateLimit[source]#
Bases:
TypedDictRepresentation of a cached object’s metadata.
- class dmr.throttling.backends.BaseThrottleSyncBackend[source]#
Base class for all throttling backends.
It must provide sync and async API for sync and async throttling classes.
- abstractmethod get(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle, *, cache_key: str) CachedRateLimit | None[source]#
Sync get the state with no increments.
- abstractmethod incr(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle, *, cache_key: str, algorithm: BaseThrottleAlgorithm) CachedRateLimit[source]#
Sync increment cached rate limit state.
Can be atomic, can be non atomic. Atomicity needs to be documented.
- lock(lock: AbstractContextManager[Any, Any]) AbstractContextManager[Any, Any][source]#
Return the context manager to acquire for increment.
- class dmr.throttling.backends.BaseThrottleAsyncBackend[source]#
Base class for all throttling backends.
It must provide sync and async API for sync and async throttling classes.
- abstractmethod async get(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: AsyncThrottle, *, cache_key: str) CachedRateLimit | None[source]#
Sync get the state with no increments.
- abstractmethod async incr(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: AsyncThrottle, *, cache_key: str, algorithm: BaseThrottleAlgorithm) CachedRateLimit[source]#
Async increment cached rate limit state.
- lock(lock: AbstractAsyncContextManager[Any, Any]) AbstractAsyncContextManager[Any, Any][source]#
Return the context manager to acquire for increment.
- class dmr.throttling.backends.SyncDjangoCache(cache_name: str = 'default', allow_unsafe_cache: bool | None = None)[source]#
Uses Django sync cache framework for storing the rate limiting state.
Unsafe cache backends (
LocMemCache,DummyCache) do not share the throttling state between processes. Useallow_unsafe_cacheto control what happens when such a backend is detected:None(default) emitsUnsafeCacheBackendWarningwhensettings.DEBUGisFalseand stays silent otherwise,Falsealways raisesEndpointMetadataError, andTruedisables the check.- get(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle, *, cache_key: str) CachedRateLimit | None[source]#
Sync get the cached rate limit state.
- incr(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle, *, cache_key: str, algorithm: BaseThrottleAlgorithm) CachedRateLimit[source]#
Sync increment cached rate limit state.
Can be atomic, can be non atomic. Atomicity needs to be documented.
- class dmr.throttling.backends.AsyncDjangoCache(cache_name: str = 'default', allow_unsafe_cache: bool | None = None)[source]#
Uses Django async cache framework for storing the rate limiting state.
Unsafe cache backends (
LocMemCache,DummyCache) do not share the throttling state between processes. Useallow_unsafe_cacheto control what happens when such a backend is detected:None(default) emitsUnsafeCacheBackendWarningwhensettings.DEBUGisFalseand stays silent otherwise,Falsealways raisesEndpointMetadataError, andTruedisables the check.- async get(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: AsyncThrottle, *, cache_key: str) CachedRateLimit | None[source]#
Async get the cached rate limit state.
- async incr(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: AsyncThrottle, *, cache_key: str, algorithm: BaseThrottleAlgorithm) CachedRateLimit[source]#
Async increment cached rate limit state.
- final class dmr.throttling.backends.django_cache.UnsafeCacheBackendWarning[source]#
Warning emitted when an unsafe cache backend is used for throttling.
- class dmr.throttling.backends.redis.SyncRedis(client: redis.Redis[Any])[source]#
Uses sync Redis client for multiproccess safe rate-limiting.
This backend requires
redisclient library to be installed. We don’t ship it with thedjango-modern-rest.You would have to install it separately:
pip install redisSee also
- get(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle, *, cache_key: str) CachedRateLimit | None[source]#
Sync get the cached rate limit state.
- incr(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle, *, cache_key: str, algorithm: BaseThrottleAlgorithm) CachedRateLimit[source]#
Atomic sync increment via Lua script.
- initialize_algorithm(algorithm: BaseThrottleAlgorithm) None[source]#
Initialize and prepare backend for the algorithm.
- lock(lock: AbstractContextManager[Any, Any]) AbstractContextManager[Any, Any][source]#
Skip the in-process lock: the incr is atomic.
- class dmr.throttling.backends.redis.AsyncRedis(client: aioredis.Redis[Any])[source]#
Uses async Redis client for multiproccess safe rate-limiting.
This backend requires
redisclient library to be installed. We don’t ship it with thedjango-modern-rest.You would have to install it separately:
pip install redisSee also
- async get(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: AsyncThrottle, *, cache_key: str) CachedRateLimit | None[source]#
Async get the cached rate limit state.
- async incr(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: AsyncThrottle, *, cache_key: str, algorithm: BaseThrottleAlgorithm) CachedRateLimit[source]#
Atomic async increment via Lua script.
- initialize_algorithm(algorithm: BaseThrottleAlgorithm) None[source]#
Initialize and prepare backend for the algorithm.
- lock(lock: AbstractAsyncContextManager[Any, Any]) AbstractAsyncContextManager[Any, Any][source]#
Skip the in-process lock: the incr is atomic.
Algorithms#
- class dmr.throttling.algorithms.BaseThrottleAlgorithm[source]#
Base class for all throttling algorithms.
- abstractmethod access(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle | AsyncThrottle, cache_object: CachedRateLimit | None) CachedRateLimit[source]#
Called when new access attempt is made.
- Returns:
Cached rate limiting state.
- Raises:
dmr.exceptions.TooManyRequestsError – when the limit is overused.
- abstractmethod report_usage(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle | AsyncThrottle, cache_object: CachedRateLimit | None) dict[str, str][source]#
Reports the throttling usage, but does not additionally increment.
- class dmr.throttling.algorithms.SimpleRate[source]#
Simple rate algorithm.
Defines a fixed window with a fixed amount of requests possible. When window is expired, resets the count of requests.
- access(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle | AsyncThrottle, cache_object: CachedRateLimit | None) CachedRateLimit[source]#
Check access.
- report_usage(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle | AsyncThrottle, cache_object: CachedRateLimit | None) dict[str, str][source]#
Reports the throttling usage, but does not additionally increment.
- class dmr.throttling.algorithms.LeakyBucket[source]#
Leaky bucket algorithm.
Requests fill the bucket; tokens leak at a steady rate. Unlike
dmr.throttling.algorithms.SimpleRate, which resets after a fixed window,LeakyBucketdrains continuously providing smoother rate-limiting without allowing bursts at window boundaries.Internally, the bucket request level is stored in scaled units as
level * durationso all arithmetic stays integer-only. Each request addsdurationscaled units to the level. Every elapsed secondmax_requestsscaled units leak out.- access(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle | AsyncThrottle, cache_object: CachedRateLimit | None) CachedRateLimit[source]#
Check access; raise when the bucket is full.
- report_usage(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: SyncThrottle | AsyncThrottle, cache_object: CachedRateLimit | None) dict[str, str][source]#
Report throttling usage without incrementing.
Cache keys#
- class dmr.throttling.cache_keys.BaseThrottleCacheKey(*, runs_before_auth: bool, name: str)[source]#
Base class for all cache keys.
- abstractmethod __call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) str | None[source]#
Returns the cache key.
If string is returned, we use this as a cache key. If
Noneis returned, this request will be skipped from this exact throttling check. However, other keys may still be applied.
- class dmr.throttling.cache_keys.RemoteAddr(*, runs_before_auth: bool = True, name: str = 'RemoteAddr')[source]#
Uses
REMOTE_ADDRfromrequest.METAas a cache key.Warning
Be sure to correctly configure your HTTP Proxy! Otherwise,
REMOTE_ADDRmight be set incorrectly.See also
See
django.http.HttpRequest.METAdocs.- __call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) str | None[source]#
Return
REMOTE_ADDRwhich is a user’s IP address, if it exists.
- class dmr.throttling.cache_keys.UserPk(*, runs_before_auth: Literal[False] = False, name: str = 'UserPk', exclude_superuser: bool = True, exclude_stuff: bool = True)[source]#
Uses
request.user.pkas a cache key.Returns
Nonefor users that should be excluded from throttling checks or whenpkis not set.- __call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) str | None[source]#
Return
request.user.pkwhen user should be throttled.
- class dmr.throttling.cache_keys.JwtToken(*, runs_before_auth: Literal[False] = False, name: str = 'JwtToken')[source]#
Uses a hash of JWT claims from
request.__dmr_jwt__as a cache key.Requires JWT extra to be installed with:
pip install 'django-modern-rest[jwt]'Never use a full token string for cache key generation.
Prefer
jticlaim, fallback tosubclaim.Store only SHA-256 hash, never raw claim values.
Returns
Nonewhen jwt token is not set, or when bothjtiandsubare missing.- __call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) str | None[source]#
Return a hash of JWT
jti/subclaims as a cache key.
Headers#
- class dmr.throttling.headers.BaseResponseHeadersProvider[source]#
Base class for all header providers.
- abstractmethod provide_headers_specs() dict[str, HeaderSpec][source]#
Provide a spec for headers for the OpenAPI.
- class dmr.throttling.headers.XRateLimit[source]#
Provides
X-RateLimitheaders.There headers inside:
X-RateLimit-LimitX-RateLimit-RemainingX-RateLimit-Reset
It is based on popular convention and does not have a formal spec.
See also
- provide_headers_specs() dict[str, HeaderSpec][source]#
Provides headers specification.
- class dmr.throttling.headers.RetryAfter[source]#
Provides
Retry-Afterheader.It is based on the existing spec.
- provide_headers_specs() dict[str, HeaderSpec][source]#
Provides headers specification.