Skip to content

Backends

fastlimit.backends.Backend

Bases: Protocol

Protocol all rate limit backends must satisfy.

Each backend implements a single method :meth:check_and_increment that atomically checks whether a request is within the limit and records it if so.

Backends are responsible for:

  • Atomically checking + recording requests (no race conditions).
  • Returning accurate remaining, reset_ms, and retry_after_ms values.
  • Cleaning up expired data (TTL management).

check_and_increment async

check_and_increment(key: str, bucket: BucketConfig, cost: int) -> BackendResult

Check the bucket and record the request if allowed.

Parameters:

Name Type Description Default
key str

Unique bucket key, e.g. "rl:login:ip:1.2.3.4".

required
bucket BucketConfig

The :class:~fastlimit.rules.BucketConfig for this bucket.

required
cost int

How many tokens/slots to consume.

required

Returns:

Name Type Description
A BackendResult

class:BackendResult with allowed status and window metadata.


fastlimit.backends.BackendResult

Result returned by :meth:Backend.check_and_increment.

Attributes:

Name Type Description
allowed

True if the request is within the limit.

limit

Total request limit for this bucket.

remaining

Requests remaining after this one.

reset_ms

Epoch milliseconds when the current window resets.

retry_after_ms

Milliseconds until retry is safe (only when blocked).


fastlimit.backends.memory.MemoryBackend

Sliding window rate limiter backed by in-process memory.

.. warning:: State is not shared across processes or workers. Use :class:~fastlimit.backends.redis.RedisBackend for multi-worker deployments.

Parameters:

Name Type Description Default
key_prefix str

Optional prefix for all keys. Useful when multiple limiter instances share one memory space.

'fastlimit'

clear_all async

clear_all() -> None

Clear all state. Useful in tests.

reset async

reset(key: str) -> None

Clear all recorded requests for a key. Useful in tests.


fastlimit.backends.redis.RedisBackend

Redis-backed rate limiter using atomic Lua scripts.

Parameters:

Name Type Description Default
client Redis

An async redis.asyncio.Redis client instance.

required
algorithm Algorithm

Which algorithm to use. Defaults to :attr:~fastlimit.Algorithm.SLIDING_WINDOW.

SLIDING_WINDOW
key_prefix str

Prefix for all Redis keys.

'fastlimit'

Raises:

Type Description
ImportError

If the redis package is not installed.

clear_all async

clear_all(pattern: str | None = None) -> None

Delete all fastlimit keys matching a pattern.

reset async

reset(key: str) -> None

Delete a single bucket key from Redis.