Skip to content

rule & Rules

fastlimit.rule

rule(default: str | None = None, *, ip: str | None = None, user: str | None = None, name: str | None = None, cost: int = 1) -> RateLimitRule

Create a :class:RateLimitRule from human-readable rate strings.

Parameters:

Name Type Description Default
default str | None

Shorthand for IP-only limiting. Equivalent to ip=.... Cannot be combined with ip.

None
ip str | None

Rate string for IP-based bucket. e.g. "10/min".

None
user str | None

Rate string for authenticated-user bucket. e.g. "50/min".

None
name str | None

Stable name for Redis key prefix. Auto-generated if omitted. Set this for predictable key names and easier Redis inspection.

None
cost int

Request cost per call. Useful for heavy endpoints. Default 1.

1

Returns:

Type Description
RateLimitRule

A frozen :class:RateLimitRule.

Raises:

Type Description
ValueError

If both default and ip are set, or neither bucket is provided, or any rate string is invalid.

Examples::

# IP-only (anonymous endpoints)
rule("10/min")
rule(ip="10/min")

# Separate limits per IP and authenticated user
rule(ip="10/min", user="50/min")

# Named rule for predictable Redis keys
rule(ip="20/min", user="100/hour", name="photo_download")

# Heavy endpoint — counts as 5 requests per call
rule("10/min", cost=5)

# Non-standard window
rule("3/5min")         # 3 requests per 5 minutes
rule("1000/day")       # 1000 requests per day

fastlimit.RateLimitRule dataclass

A fully resolved rate limit rule.

Prefer creating rules via :func:rule rather than directly.

Attributes:

Name Type Description
name str

Unique rule name. Used as part of the Redis/memory key.

ip_limit BucketConfig | None

Limit applied per IP address. None to disable.

user_limit BucketConfig | None

Limit applied per authenticated user. None to disable.

cost int

How many tokens/requests this rule costs per call. Default 1.


fastlimit.BucketConfig dataclass

Resolved rate limit for a single bucket (IP or user).

Attributes:

Name Type Description
window_sec int

Rolling window size in seconds.

limit int

Maximum requests allowed within the window.