duck.http.middlewares.security.requestslimit

High-performance rate-limiting middleware using InMemoryCache expiry-based counters.

This implementation uses a fixed window algorithm:

  • Each client/IP has a single counter stored in the cache.

  • The key expires automatically after requests_delay seconds.

  • On each request, the counter increments.

  • If it exceeds max_requests, the request is rejected.

This design provides:

  • O(1) operations

  • Zero list allocations

  • Zero timestamp storage

  • Minimal memory footprint

  • Very high request throughput

Module Contents

Classes

RequestsLimitMiddleware

High-speed request limiter using expiry-based counters.

API

class duck.http.middlewares.security.requestslimit.RequestsLimitMiddleware

Bases: duck.http.middlewares.BaseMiddleware

High-speed request limiter using expiry-based counters.

Variables:
  • _clients – Cache storing counters per client IP. Keys automatically expire after the configured window duration.

  • requests_delay – Duration (in seconds) forming the rate-limit window.

  • max_requests – Maximum number of requests allowed within the window.

_clients

‘InMemoryCache(…)’

classmethod _process_request(request)

Core request-processing logic.

Flow:

  1. Extract client IP.

  2. Fetch current request count from cache.

  3. If count is missing -> this is first request in the window. Create count=1 with expiry.

  4. If count >= max_requests -> reject.

  5. Otherwise increment counter and update expiry.

This implementation does not store timestamps and does not scan arrays. It relies fully on cache expiry to define the time window.

debug_message: str

‘RequestsLimitMiddleware: Too many requests’

classmethod get_error_response(request)

Creates a 429 Too Many Requests HTTP response.

Includes additional debugging information when DEBUG is enabled.

classmethod get_readable_limit() str

Returns a user-friendly description of the rate limit.

… rubric:: Example

“200 requests per 60 seconds”

max_requests: int

200

Maximum number of allowed requests within the requests_delay window.

classmethod process_request(request)

Framework entry point.

Wraps the internal handler and ensures the server always fails open instead of blocking requests due to middleware errors.

requests_delay: float

60

Duration in seconds defining the time window for request counting.