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 None if throttle check passed. Raise dmr.exceptions.TooManyRequestsError if throttle check failed. Raise dmr.response.APIError if 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 None keeps this throttle’s current value, so replace(max_requests=2) changes just the limit. Also backs copy.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_headers classes.

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 None keeps this throttle’s current value, so replace(max_requests=2) changes just the limit. Also backs copy.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 None if throttle check passed. Raise dmr.exceptions.TooManyRequestsError if throttle check failed. Raise dmr.response.APIError if 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 None keeps this throttle’s current value, so replace(max_requests=2) changes just the limit. Also backs copy.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_headers classes.

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 None keeps this throttle’s current value, so replace(max_requests=2) changes just the limit. Also backs copy.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.

async areport() → dict[str, str][source]#

Report throttling all headers for a async controller and endpoint.

Unlike sync version it makes parallel requests to cache by utilizing asyncio.gather() function inside.

report() → dict[str, str][source]#

Report throttling all headers for a sync controller and endpoint.

Note that it will make N consecutive requests to cache. It might be rather long. Use the sync version with care.

Backends#

class dmr.throttling.backends.CachedRateLimit[source]#

Bases: TypedDict

Representation 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. Use allow_unsafe_cache to control what happens when such a backend is detected: None (default) emits UnsafeCacheBackendWarning when settings.DEBUG is False and stays silent otherwise, False always raises EndpointMetadataError, and True disables 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. Use allow_unsafe_cache to control what happens when such a backend is detected: None (default) emits UnsafeCacheBackendWarning when settings.DEBUG is False and stays silent otherwise, False always raises EndpointMetadataError, and True disables 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 redis client library to be installed. We don’t ship it with the django-modern-rest.

You would have to install it separately:

pip install redis
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.

needs_transaction_script: ClassVar[str] = 'lua'#

Format name that the backend needs:

class dmr.throttling.backends.redis.AsyncRedis(client: aioredis.Redis[Any])[source]#

Uses async Redis client for multiproccess safe rate-limiting.

This backend requires redis client library to be installed. We don’t ship it with the django-modern-rest.

You would have to install it separately:

pip install redis
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.

needs_transaction_script: ClassVar[str] = 'lua'#

Format name that the backend needs:

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.

transaction_script(script_format: str) → str | None[source]#

Optionally dump the transaction script for backends that support it.

It can be .lua or .sql.

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.

transaction_script(script_format: str) → str | None[source]#

Optionally dump the transaction script for backends that support it.

It can be .lua or .sql.

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, LeakyBucket drains continuously providing smoother rate-limiting without allowing bursts at window boundaries.

Internally, the bucket request level is stored in scaled units as level * duration so all arithmetic stays integer-only. Each request adds duration scaled units to the level. Every elapsed second max_requests scaled 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.

transaction_script(script_format: str) → str | None[source]#

Optionally dump the transaction script for backends that support it.

It can be .lua or .sql.

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 None is 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_ADDR from request.META as a cache key.

Warning

Be sure to correctly configure your HTTP Proxy! Otherwise, REMOTE_ADDR might be set incorrectly.

See also

See django.http.HttpRequest.META docs.

__call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) → str | None[source]#

Return REMOTE_ADDR which 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.pk as a cache key.

Returns None for users that should be excluded from throttling checks or when pk is not set.

__call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) → str | None[source]#

Return request.user.pk when 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]'
  1. Never use a full token string for cache key generation.

  2. Prefer jti claim, fallback to sub claim.

  3. Store only SHA-256 hash, never raw claim values.

Returns None when jwt token is not set, or when both jti and sub are missing.

__call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) → str | None[source]#

Return a hash of JWT jti / sub claims 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.

abstractmethod response_headers(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: _BaseThrottle[Any], remaining: int, reset: int, *, report_all: bool = True) → dict[str, str][source]#

Return a dict of rendered headers to be added to the response.

class dmr.throttling.headers.XRateLimit[source]#

Provides X-RateLimit headers.

There headers inside:

  • X-RateLimit-Limit

  • X-RateLimit-Remaining

  • X-RateLimit-Reset

It is based on popular convention and does not have a formal spec.

provide_headers_specs() → dict[str, HeaderSpec][source]#

Provides headers specification.

response_headers(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: _BaseThrottle[Any], remaining: int, reset: int, *, report_all: bool = True) → dict[str, str][source]#

Returns the formatted response headers.

class dmr.throttling.headers.RetryAfter[source]#

Provides Retry-After header.

It is based on the existing spec.

See also

RFC-6585 and RFC-7231

provide_headers_specs() → dict[str, HeaderSpec][source]#

Provides headers specification.

response_headers(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: _BaseThrottle[Any], remaining: int, reset: int, *, report_all: bool = True) → dict[str, str][source]#

Returns the formatted response headers.

class dmr.throttling.headers.RateLimitIETFDraft[source]#

Provides RateLimit and RateLimit-Policy headers.

It is based on the latest draft of the ratelmiting headers spec.

provide_headers_specs() → dict[str, HeaderSpec][source]#

Provides headers specification.

response_headers(endpoint: Endpoint, controller: Controller[BaseSerializer], throttle: _BaseThrottle[Any], remaining: int, reset: int, *, report_all: bool = True) → dict[str, str][source]#

Returns the formatted response headers.