Quota Configuration

Quota Configuration#

1) Quick Setup#

You can pass a readable quota string directly to Throttled.

from throttled import Throttled

throttle = Throttled(
    key="/api/ping",
    quota="100/s",
    # quota="100/s burst 200",
    # quota="100 per second",
    # quota="100 per second burst 200",
)


if __name__ == "__main__":
    print(throttle.limit())
import asyncio

from throttled.asyncio import Throttled

throttle = Throttled(
    key="/api/ping",
    quota="100/s",
    # quota="100/s burst 200",
    # quota="100 per second",
    # quota="100 per second burst 200",
)


async def main() -> None:
    print(await throttle.limit())


if __name__ == "__main__":
    asyncio.run(main())

Supported patterns:

  • n / unit

  • n / unit burst <burst>

  • n per unit

  • n per unit burst <burst>

Where burst means extra bucket capacity for short spikes. It is effective for:

  • TOKEN_BUCKET

  • LEAKING_BUCKET

  • GCRA

If burst is omitted in quota string mode, it defaults to n in the same rule. For example, 1/s is equivalent to 1/s burst 1.

Supported units and compatibility forms:

Canonical unit

Short form

Compatible forms

Example

second

s

s, sec, secs, second, seconds

100/s / 100 per sec

minute

m

m, min, mins, minute, minutes

60/m / 60 per min

hour

h

h, hr, hrs, hour, hours

10/h / 10 per hour

day

d

d, day, days

5/d / 5 per day

week

w

w, wk, wks, week, weeks

1/w / 1 per week

2) Custom Quota#

If quota string patterns are not enough for your scenario, you can still build Quota objects programmatically:

from datetime import timedelta

from throttled import rate_limiter

# Built-in constructors for common fixed periods.
rate_limiter.per_sec(60)  # 60 req/sec
rate_limiter.per_min(60)  # 60 req/min
rate_limiter.per_hour(60)  # 60 req/hour
rate_limiter.per_day(60)  # 60 req/day
rate_limiter.per_week(60)  # 60 req/week

# Allow up to 120 requests as burst capacity.
# If burst is omitted, it defaults to the same value as limit.
rate_limiter.per_min(60, burst=120)

# Custom period example:
# allow 120 requests per 2 minutes, with burst capacity of 150.
rate_limiter.per_duration(timedelta(minutes=2), limit=120, burst=150)