API reference¶
Everything most code needs is importable from paceapi itself: Limiter,
Rate, the unit constants, the keys, Decision, the three algorithms,
MemoryStore and the errors. The sections below document those names where
they are defined, along with the extension points.
Limiter¶
paceapi.ratelimit.limiter ¶
The limiter: turns keys and rates into one decision.
RateLimitDependency ¶
RateLimitDependency = Callable[..., Awaitable[Decision]]
What Limiter.limit() returns: something to wrap in FastAPI's Depends.
RateSource ¶
RateSource = Callable[..., RateLike | Sequence[RateLike]] | Callable[..., Awaitable[RateLike | Sequence[RateLike]]]
A dependency that returns the rate, or rates, for the request at hand.
CostSource ¶
A dependency that returns what the request at hand costs.
MissingKeyPolicy ¶
What a limit does when its key returns None: fail loudly, or not apply.
Limiter ¶
Limiter(store: LimiterStore | None = None, *, algorithm: Algorithm | None = None, clock: Clock | None = None, prefix: str = 'pace', enabled: bool = True, on_store_error: StoreErrorPolicy = 'allow', observers: Sequence[Observer] = (), headers: HeaderStyle | None = X_RATE_LIMIT, store_timeout: float | None = 1.0, store_cooldown: float | None = 1.0, fallback: LimiterStore | None = None)
Decide whether something may happen, given how often it already has.
A limiter counts costs against rates. Each combination of scope, key and rate is its own bucket:
limiter = Limiter()
decision = await limiter.hit("user:42", "100/minute")
if not decision.allowed:
... # turn the request away for decision.retry_after seconds
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
LimiterStore | None
|
Where counts are kept. Defaults to a new
|
None
|
algorithm
|
Algorithm | None
|
How counts turn into decisions. Defaults to
|
None
|
clock
|
Clock | None
|
Where the time comes from. By default the store uses its own. |
None
|
prefix
|
str
|
The first part of every storage key, to keep this limiter's keys apart from anything else in the same store. |
'pace'
|
enabled
|
bool
|
Whether to limit at all. When false every call is allowed and the store is never touched. |
True
|
on_store_error
|
StoreErrorPolicy
|
What to do when no store can count: |
'allow'
|
store_timeout
|
float | None
|
The longest one call to the store may take, in
seconds. A call that takes longer is given up on and counts as
a failure. Time spent waiting in line for the store, or with
the event loop held up, does not count. Opening a connection
does. |
1.0
|
store_cooldown
|
float | None
|
The longest a store that keeps failing is left
alone between two attempts, in seconds. After three failures
in a row, one request at a time finds out whether the store is
back, and the others do not wait on it. |
1.0
|
fallback
|
LimiterStore | None
|
A second store to count in while the first is failing,
such as a |
None
|
observers
|
Sequence[Observer]
|
Told about every decision and every store failure. Their methods are called synchronously. An observer that raises is logged, at most once a minute, and otherwise ignored. |
()
|
headers
|
HeaderStyle | None
|
How web integrations describe a decision in response
headers. |
X_RATE_LIMIT
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
bool
|
Whether the limiter is limiting. It can be changed at any time. |
headers |
Final[HeaderStyle | None]
|
The header style web integrations use, or |
hit
async
¶
Count a cost against one or more rates and say whether it fits.
The cost has to fit every rate. If it does not fit one of them it is counted against none.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Who is being limited, such as a user id or an IP address. |
required |
*rates
|
RateLike
|
The rates to enforce, as |
()
|
cost
|
int
|
How much this counts for. Zero looks without counting. |
1
|
scope
|
str
|
What is being limited, such as a route. Each scope keeps its own counts for the same key. |
''
|
force
|
bool
|
Count the cost even if it does not fit. Use it for costs that are only known after the work is done. |
False
|
Returns:
| Type | Description |
|---|---|
Decision
|
The decision. With several rates it is the one that denied with |
Decision
|
the longest wait, or else the one with the least remaining. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If no rate is given, the key or scope is not a string, or the cost is not a whole number. |
ValueError
|
If the cost is negative. |
InvalidRateError
|
If a rate given as text cannot be read. |
limit ¶
limit(*rates: RateLike | RateSource, key: Key | None = None, cost: int | CostSource = 1, scope: str | None = None, on_missing_key: MissingKeyPolicy = 'error') -> RateLimitDependency
Make a rate limit to attach to FastAPI routes with Depends.
@app.get("/search", dependencies=[Depends(limiter.limit("10/second"))])
async def search(q: str) -> list[str]: ...
The same limit can go on a router or on the whole app through their
dependencies. A request over the limit gets a 429 with Retry-After;
the rest carry headers saying how much is left.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*rates
|
RateLike | RateSource
|
The rates to enforce, as |
()
|
key
|
Key | None
|
Who each request is counted against. It is resolved as a
FastAPI dependency, so it can depend on your own, such as the
current user. Write it with |
None
|
cost
|
int | CostSource
|
How much each request counts for, or a dependency that returns it. |
1
|
scope
|
str | None
|
By default each route is a scope of its own and keeps its own bucket. Give a scope to share one bucket across every route the limit is attached to. |
None
|
on_missing_key
|
MissingKeyPolicy
|
What to do when the key returns |
'error'
|
Returns:
| Type | Description |
|---|---|
RateLimitDependency
|
A dependency. It resolves to the |
RateLimitDependency
|
|
RateLimitDependency
|
wants to read it. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If no rate is given, an argument is of the wrong kind, a rate dependency is mixed with other rates, or a dependency takes a parameter that has no type. |
ValueError
|
If the cost is negative or could never fit the
rates, the scope is empty, or |
InvalidRateError
|
If a rate given as text cannot be read. |
ImportError
|
If FastAPI is not installed. |
disabled ¶
Switch limiting off for the length of a with block.
Meant for tests that are not about rate limits. The earlier setting is restored afterwards, even if the block raises.
FastAPI¶
paceapi.integrations.fastapi ¶
FastAPI integration: rate limits as dependencies.
This module needs FastAPI. It is imported when Limiter.limit() is first
called, so the rest of paceapi works without FastAPI installed.
rate_limit ¶
rate_limit(limiter: Limiter, rates: Sequence[RateLike | RateSource], *, key: Key | None, cost: int | CostSource, scope: str | None, on_missing_key: MissingKeyPolicy) -> RateLimitDependency
Build the dependency behind Limiter.limit().
Everything that can be checked without a request is checked here, so a mistake in a limit fails when the app is defined.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limiter
|
Limiter
|
The limiter that counts. |
required |
rates
|
Sequence[RateLike | RateSource]
|
The rates to enforce, or one dependency that returns them. |
required |
key
|
Key | None
|
Who each request is counted against. |
required |
cost
|
int | CostSource
|
How much each request counts for, or a dependency that returns it. |
required |
scope
|
str | None
|
A name for one bucket shared by every route this limit is
attached to, or |
required |
on_missing_key
|
MissingKeyPolicy
|
What to do when the key returns |
required |
Returns:
| Type | Description |
|---|---|
RateLimitDependency
|
A callable for |
Raises:
| Type | Description |
|---|---|
TypeError
|
If no rate is given, an argument is of the wrong kind, a rate dependency is mixed with other rates, or a dependency takes a parameter that has no type. |
ValueError
|
If the cost is negative or could never fit the rates,
the scope is empty, or |
InvalidRateError
|
If a rate given as text cannot be read. |
keys_signature ¶
keys_signature(keys: Sequence[Key]) -> Signature
Describe several keys to FastAPI as dependencies to resolve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Sequence[Key]
|
The keys, in order. |
required |
Returns:
| Type | Description |
|---|---|
Signature
|
A signature with one keyword-only parameter per key, named |
Signature
|
|
Starlette¶
paceapi.integrations.starlette ¶
Starlette integration: a limit for the whole app as middleware, or for one endpoint.
This module needs nothing but Starlette, so it works in an app with no FastAPI in it. The middleware is for FastAPI apps as well.
PaceMiddleware ¶
PaceMiddleware(app: ASGIApp, *, limiter: Limiter, limit: RateLike | Sequence[RateLike] | None = None, key: Key | None = None, cost: int = 1, scope: str = 'app', on_missing_key: MissingKeyPolicy = 'error')
Apply one rate limit to every HTTP request of an app, before routing.
app = Starlette(
routes=routes,
middleware=[Middleware(PaceMiddleware, limiter=limiter, limit="100/minute")],
)
The limit is one allowance for each caller across the whole app, because
the middleware runs before any route is chosen. A request over it gets a
429 with a JSON body, Retry-After, and the limiter's rate limit headers.
WebSockets pass straight through.
The middleware also puts the rate limit headers on every response the
app sends, including one an endpoint built itself, a streamed one and an
error. They describe the limit the caller is closest to, whether it is
this one or a limit on the route. A response that already carries rate
limit headers keeps its own. With no limit that is all the middleware
does:
Starlette makes its middleware when the server first calls the app, so
a mistake in the arguments is raised then. A server that waits for the
app to start, such as uvicorn --lifespan on, refuses to start. With
most servers' defaults the app starts and every request fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
ASGIApp
|
The app to wrap. Starlette passes this itself. |
required |
limiter
|
Limiter
|
The limiter that counts. |
required |
limit
|
RateLike | Sequence[RateLike] | None
|
The rate to enforce, or several, as |
None
|
key
|
Key | None
|
Who each request is counted against. It is called with the
connection and nothing else, so it cannot be a key that depends
on FastAPI's injection. |
None
|
cost
|
int
|
How much each request counts for. |
1
|
scope
|
str
|
The name of the bucket. Two limits on one app with the same rate and key need different scopes, or each request is counted twice against one allowance. |
'app'
|
on_missing_key
|
MissingKeyPolicy
|
What to do when the key returns |
'error'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the cost is negative or could never fit the rates,
the scope is empty, or |
InvalidRateError
|
If a rate given as text cannot be read. |
__call__
async
¶
Handle one ASGI connection.
limited ¶
limited(limiter: Limiter, *rates: RateLike, key: Key | None = None, cost: int = 1, scope: str | None = None, on_missing_key: MissingKeyPolicy = 'error') -> Callable[[Callable[P, Response | Awaitable[Response]]], Callable[P, Awaitable[Response]]]
Limit one Starlette endpoint.
It works on a function that takes the request, async or not, and on a
method of an HTTPEndpoint class. A request over the limit raises
RateLimitExceeded, which
Starlette sends as a 429 and which your app can handle its own way. The
others carry the limiter's rate limit headers.
In a FastAPI app, use Limiter.limit
instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limiter
|
Limiter
|
The limiter that counts. |
required |
*rates
|
RateLike
|
The rates to enforce, as |
()
|
key
|
Key | None
|
Who each request is counted against. It is called with the
request and nothing else. |
None
|
cost
|
int
|
How much each request counts for. |
1
|
scope
|
str | None
|
By default each endpoint keeps a bucket of its own, named after the function. Give a scope to share one bucket between endpoints, or to keep apart endpoints that share a name because one function made them all. |
None
|
on_missing_key
|
MissingKeyPolicy
|
What to do when the key returns |
'error'
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[P, Response | Awaitable[Response]]], Callable[P, Awaitable[Response]]]
|
A decorator. The endpoint it returns is always |
Callable[[Callable[P, Response | Awaitable[Response]]], Callable[P, Awaitable[Response]]]
|
not is still run on a worker thread. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If no rate is given, an argument is of the wrong kind, or the key needs more than the request. |
ValueError
|
If the cost is negative or could never fit the rates,
the scope is empty, or |
InvalidRateError
|
If a rate given as text cannot be read. |
Keys¶
paceapi.keys ¶
Keys: who a request is counted against.
A key is a callable that returns a string naming the caller, or None when
it cannot tell who that is. What a limit does with None is the limit's
decision: by default it fails the request loudly, so that a key which names
nobody cannot switch a limit off unnoticed.
The keys in this module are async. FastAPI runs a dependency written with a
plain def on a worker thread, which is far more than reading an address
needs, so write your own keys with async def too unless they block.
client_ip
module-attribute
¶
client_ip: Final = ClientIP()
The caller's address as seen by the server, trusting no proxy.
Key ¶
Something that names the caller of a request, or returns None.
In a FastAPI route a key is resolved as a dependency, so it may be async
and may declare dependencies of its own, such as the current user. Anywhere
else a key is called with the connection and nothing more.
ConnectionKey ¶
A key that needs nothing but the connection: its address or its headers.
Await it to use it in a key of your own: await client_ip(request).
ClientIP ¶
ClientIP(*, trusted_proxies: Iterable[str] = (), ipv6_prefix: int = 64, trust_unix_socket: bool = False)
Name the caller by network address.
By default this is the address of whoever connected. That is only the real
caller when nothing sits in between. Behind a load balancer or reverse
proxy, name the proxies in trusted_proxies; the caller is then read from
X-Forwarded-For, taking the last address that is not one of the proxies.
The header is ignored unless the connection itself comes from a trusted
proxy, because anyone can send it.
A proxy that reaches the app through a Unix socket has no address to
name. Say trust_unix_socket=True for that.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trusted_proxies
|
Iterable[str]
|
The addresses or CIDR ranges of your own proxies. |
()
|
ipv6_prefix
|
int
|
IPv6 callers are grouped by a prefix of this many bits, since one subscriber controls a whole /64. Use 128 for exact addresses. |
64
|
trust_unix_socket
|
bool
|
Treat a connection that has no address for the other end, as one over a Unix socket has not, as coming from a trusted proxy. Only a process on the same machine can open such a connection. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a trusted proxy is not an address or range, or the prefix is not between 1 and 128. |
__call__
async
¶
Return "ip:<address>" for the caller, or None if it cannot be told.
RequestHeader
dataclass
¶
Name the caller by the value of a request header.
Use this only for a header whose value the caller cannot choose, such as one your own gateway sets. If any value is accepted, each new one is a new caller with a fresh allowance. For credentials, key on what your authentication found instead.
The key holds a digest of the value exactly as it was sent, never the
value itself, so it does not end up in the store or in logs. It gives
"<name>:<digest>", or None when the header is missing or blank.
Two of these for the same header are equal, so a test can override one without holding the object the app made.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The header's name, in lower case. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
__call__
async
¶
Return "<name>:<digest>", or None if the header is missing or blank.
authenticated_user
async
¶
Name the caller as the user Starlette's authentication found.
With Starlette's AuthenticationMiddleware in the app, this counts a
signed-in caller as that user. It returns None for anyone else, and
when there is no authentication at all, so pair it with another key:
first_of(authenticated_user, client_ip).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
HTTPConnection
|
The request or WebSocket being counted. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
|
str | None
|
where the user class has no identity. |
str | None
|
Counting by |
str | None
|
user cannot change it, so give your user class an |
resolve
async
¶
resolve(key: Key, connection: HTTPConnection) -> str | None
Ask a key who is calling, with only the connection to go on.
This is how a key is resolved where FastAPI is not doing it: in the
Starlette middleware and decorator, and inside
first_of and combine
there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Key
|
A key that takes the connection. |
required |
connection
|
HTTPConnection
|
The request or WebSocket being counted. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
What the key returned, awaited if it was awaitable. |
takes_connection ¶
takes_connection(key: Key) -> bool
Whether a key can be called with the connection and nothing more.
The keys in this module can, and so can a function of your own that takes
the request. A key written for FastAPI to fill in, with a parameter such
as user: User = Depends(current_user) or x_tenant: str = Header(),
cannot: called with the connection alone it would see the marker, not
the value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Key
|
The key to look at. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
first_of ¶
Use the first of several keys that names the caller.
first_of(user_key, client_ip) counts a signed-in caller as that user
and everyone else by address.
Every key is resolved on each request, so one that refuses the request
outright (an auth dependency that answers 401, say) still does. Give
first_of keys that return None when they have nothing to say.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*keys
|
Key
|
The keys to try, in order. At least two. |
()
|
Returns:
| Type | Description |
|---|---|
Key
|
A key that gives the first value that is not |
Raises:
| Type | Description |
|---|---|
TypeError
|
If fewer than two keys are given. |
combine ¶
Count each combination of several keys separately.
combine(user_key, client_ip) keeps one bucket per user per address.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*keys
|
Key
|
The keys to join. At least two. |
()
|
Returns:
| Type | Description |
|---|---|
Key
|
A key that joins the values with |
Key
|
them is |
Key
|
different combinations never make the same key. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If fewer than two keys are given. |
Headers and the 429 error¶
paceapi.ratelimit.headers ¶
The response headers that tell a caller where they stand against a limit.
HeaderStyle ¶
XRateLimitHeaders
dataclass
¶
The widely used X-RateLimit-* headers.
X-RateLimit-Limit: how much the rate allows per period.X-RateLimit-Remaining: how much is left right now.X-RateLimit-Reset: whole seconds from now until the full allowance is back. It is a duration, not a clock time, so it does not depend on the caller's clock agreeing with the server's.
paceapi.ratelimit.exceeded ¶
The error a web integration raises when a request is over its limit.
RateLimitExceeded ¶
RateLimitExceeded(decision: Decision, *, headers: Mapping[str, str] | None = None)
Bases: HTTPException, PaceError
A request was turned away because it is over a rate limit.
It is an HTTP 429 that Starlette and FastAPI already know how to send,
with a Retry-After header saying how many seconds to wait. To change
the response, register your own exception handler for this class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decision
|
Decision
|
The decision that denied the request. |
required |
headers
|
Mapping[str, str] | None
|
Extra headers for the response, such as the rate limit headers. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
decision |
The decision that denied the request. |
Rates¶
paceapi.rates ¶
Rates: how much is allowed, over how long.
Rate
dataclass
¶
At most limit units of cost every period seconds.
Write the period with the unit constants, for example Rate(100, MINUTE)
or Rate(10, 30 * SECOND).
Attributes:
| Name | Type | Description |
|---|---|---|
limit |
int
|
How much is allowed in one period. A whole number, at least 1. |
period |
float
|
The length of the period in seconds. Positive and finite. |
Raises:
| Type | Description |
|---|---|
InvalidRateError
|
If the limit or the period is out of range. |
parse
classmethod
¶
parse(text: str) -> Rate
Read a rate from text.
The accepted forms are "100/minute", "100 per minute" and, with a
count before the unit, "10/30 seconds". The units are second,
minute, hour and day, with or without a trailing s, in
any case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The rate as text. |
required |
Returns:
| Type | Description |
|---|---|
Rate
|
The rate the text describes. |
Raises:
| Type | Description |
|---|---|
InvalidRateError
|
If the text is not in one of the accepted forms. |
Algorithms¶
paceapi.ratelimit.algorithms ¶
The rate-limiting algorithms.
Each one is a small, pure state machine that follows the rules set out on
Algorithm.
FixedWindow
dataclass
¶
Count what is used in fixed windows that all callers share.
Time is cut into windows one period long, aligned to the clock, and each window allows the limit. It is exact per window and needs two numbers of state, but a burst at the end of one window and the start of the next can add up to twice the limit in a short time.
TokenBucket
dataclass
¶
Allow a burst up to the limit, then refill at a steady rate.
The bucket starts full with limit tokens and gains limit / period
tokens a second. Each unit of cost takes one token. It smooths traffic to
the rate and needs two numbers of state. A forced cost can take the bucket
below zero, and that debt is repaid by the refill before anything else fits.
SlidingWindow
dataclass
¶
Approximate a window that ends now with two counters.
It keeps the count for the current fixed window and for the one before, and weighs the earlier one by how much of it still overlaps a window ending now. That removes most of the fixed window's burst at the boundary for three numbers of state. It is exact per aligned window. Because it assumes the earlier window's requests were evenly spread, it can admit up to twice the limit across a boundary when they were not.
Stores¶
paceapi.stores.limiting ¶
The contract between rate-limiting algorithms and the stores that run them.
State ¶
What an algorithm remembers about one bucket: a short tuple of numbers.
Decision
dataclass
¶
Decision(allowed: bool, rate: Rate, remaining: int, reset_after: float, retry_after: float)
The outcome of asking whether a cost fits within a rate.
Attributes:
| Name | Type | Description |
|---|---|---|
allowed |
bool
|
Whether the cost fitted. |
rate |
Rate
|
The rate this decision is about. |
remaining |
int
|
Whole units still available right now. Never negative. |
reset_after |
float
|
Seconds until the bucket is as good as new. |
retry_after |
float
|
Seconds until the same cost would fit. Zero when allowed. |
Algorithm ¶
Bases: Protocol
A rate-limiting algorithm: a pure function from one state to the next.
An algorithm keeps nothing itself. A store hands it the state for one bucket and saves what comes back, so the same algorithm works with every store. Each implementation obeys these rules:
- Whether the cost fits, and
retry_after, are worked out from the state before this step's cost is applied. - The cost is applied when it fits or when
forceis true.allowedreports whether it fitted, even when forced. remainingandreset_afterdescribe the state after the step.retry_afteris zero when the cost fits. When the cost is larger than the whole limit it can never fit, andretry_afteris the rate's period.reset_afteris the time until the returned state is equivalent to no state at all. Stores use it as the state's time to live.- If
nowis earlier than the state's own time, the step behaves as if no time had passed. State more than one period ahead ofnowis discarded, so a clock that was set back cannot freeze a bucket for long.
step ¶
step(state: State | None, rate: Rate, now: float, cost: int, *, force: bool) -> tuple[State, Decision]
Apply a cost at a point in time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
State | None
|
What an earlier step returned for this bucket, or |
required |
rate
|
Rate
|
The rate to enforce. |
required |
now
|
float
|
The current time in seconds. |
required |
cost
|
int
|
How much to consume. Zero inspects without consuming. It is never negative; stores refuse that before calling this. |
required |
force
|
bool
|
Apply the cost even if it does not fit. |
required |
Returns:
| Type | Description |
|---|---|
tuple[State, Decision]
|
The state to store, and the decision. |
Bucket
dataclass
¶
LimiterStore ¶
Bases: Protocol
Where bucket state is kept, and where algorithms are run against it.
A store obeys these rules:
applyis atomic across all its buckets: either every bucket's new state is stored, or none is.- New states are stored only when every bucket fits, or when
forceis true. - A stored state expires
decision.reset_afterseconds afternow. Areset_afterof zero stores nothing and removes whatever was stored under that key. now=Nonemeans the store's own clock.applymay be cancelled at anyawait, as a limiter does when a call takes longer than its timeout. A cancelled call must leave the store usable, and may or may not have been counted.- A negative
costraisesValueError. Nothing hands quota back.
Callers pass each bucket key at most once per call.
apply
async
¶
Apply one cost to several buckets as a single atomic step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buckets
|
Sequence[Bucket]
|
The buckets the cost counts against. |
required |
cost
|
int
|
How much to consume from each bucket. |
required |
force
|
bool
|
Store the result even if a bucket cannot fit the cost. |
required |
now
|
float | None
|
The current time in seconds, or |
required |
Returns:
| Type | Description |
|---|---|
list[Decision]
|
One decision per bucket, in the order the buckets were given. |
QueueingStore ¶
Bases: LimiterStore, Protocol
A store whose calls wait in line, and that lets a limiter see the line.
A store that runs only so many calls at once makes the rest wait, as
RedisStore does to stay inside its
connection pool. A limiter that timed a call from the moment it joined
the line could not tell a long line from a slow server, and a burst would
look like an outage. So where a store has turn, a limiter waits there
first, and starts its timeout only once the wait is over.
A store with nothing to wait in line for has no need of this. One that
wraps a store which has turn should pass it on.
turn ¶
turn(buckets: Sequence[Bucket]) -> AbstractAsyncContextManager[LimiterStore]
Wait in line for one step on some buckets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buckets
|
Sequence[Bucket]
|
The buckets the step is going to be applied to. |
required |
Returns:
| Type | Description |
|---|---|
AbstractAsyncContextManager[LimiterStore]
|
An async context manager. Entering it waits for as long as the |
AbstractAsyncContextManager[LimiterStore]
|
line takes, and gives a store whose |
AbstractAsyncContextManager[LimiterStore]
|
buckets without waiting in line again. Leaving it gives the |
AbstractAsyncContextManager[LimiterStore]
|
place in line up. |
evaluate ¶
evaluate(buckets: Sequence[Bucket], states: Sequence[State | None], *, cost: int, force: bool, now: float) -> tuple[list[State] | None, list[Decision]]
Step every bucket, and say whether the results may be stored.
This is the all-or-nothing rule in one place, for stores that run algorithms in the same process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buckets
|
Sequence[Bucket]
|
The buckets the cost counts against. |
required |
states
|
Sequence[State | None]
|
The stored state for each bucket, or |
required |
cost
|
int
|
How much to consume from each bucket. |
required |
force
|
bool
|
Store the result even if a bucket cannot fit the cost. |
required |
now
|
float
|
The current time in seconds. |
required |
Returns:
| Type | Description |
|---|---|
list[State] | None
|
The new state for each bucket, or |
list[Decision]
|
because a bucket was denied; and one decision per bucket. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
paceapi.stores.memory ¶
A store that keeps everything in this process's memory.
MemoryStore ¶
Keep bucket state in a dictionary in this process.
It needs no setup, which makes it the default and the natural choice for tests and single-process apps. State is not shared: with several worker processes each one keeps its own counts, so a limit applies per worker. Use a shared store when that matters.
Memory is bounded. Entries are removed as they expire. If max_entries
live keys are held all the same, the key written longest ago is dropped to
make room, so a flood of distinct keys cannot grow the store without
limit. Keep max_entries well above the number of rates used in one call,
or a call can drop its own buckets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_entries
|
int
|
The most keys to hold at once. At least 1. |
100000
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
apply
async
¶
apply(buckets: Sequence[Bucket], *, cost: int, force: bool, now: float | None = None) -> list[Decision]
Apply one cost to several buckets as a single atomic step.
The rules are set out on
LimiterStore. There is no
await in here, so on one event loop nothing else can run between
reading the state and writing it back.
paceapi.stores.redis ¶
A store that keeps bucket state in Redis, so every process shares one count.
This module needs redis-py, which comes with the redis extra:
pip install "paceapi[redis]". Nothing else in paceapi imports it.
RedisStore ¶
Keep bucket state in Redis, where every process sees the same counts.
from redis.asyncio import from_url
limiter = Limiter(RedisStore(from_url("redis://localhost:6379")))
A step is atomic across all its buckets, as every store's is. State is kept only for as long as it means something, so idle buckets leave nothing behind. Without an explicit time the server's clock is used, which is the same for every process.
The built-in algorithms run inside Redis as one script, so a call is one
round trip however many rates it has. An algorithm of your own works too:
its step runs in your process between a read and a write that only goes
through if nothing changed. That costs two round trips, callers in one
process take turns at a key, and a call that keeps losing to other
processes is in the end answered as over the limit, never let through.
A forced cost is the exception: it keeps being tried for as long as its
caller waits.
The store has at most half of the client's connection pool in use at
once, and no more than 64 calls. A burst waits in line, where the pool
on its own would raise once it ran out. A limiter does not count that
wait against its store_timeout. Each store takes half of its client's
pool, so limiters that share a client should share the store as well.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Redis | RedisCluster
|
A redis-py asyncio client, standalone or cluster, that your app created. The store uses it as it is and never closes it. |
required |
apply
async
¶
apply(buckets: Sequence[Bucket], *, cost: int, force: bool, now: float | None = None) -> list[Decision]
Apply one cost to several buckets as a single atomic step.
The rules are set out on
LimiterStore.
turn
async
¶
turn(buckets: Sequence[Bucket]) -> AsyncGenerator[LimiterStore]
Wait in line for one step on some buckets.
apply does this for you. A limiter does it separately, so that it
can tell the wait in line from the wait for the server. See
QueueingStore.
async with store.turn(buckets) as ready:
decisions = await ready.apply(buckets, cost=1, force=False, now=None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buckets
|
Sequence[Bucket]
|
The buckets the step is going to be applied to. |
required |
Yields:
| Type | Description |
|---|---|
AsyncGenerator[LimiterStore]
|
The store without its line. Its |
AsyncGenerator[LimiterStore]
|
and goes straight to the server. |
Observing¶
paceapi.observe ¶
Hooks for watching what paceapi does.
An observer is told about each decision and each store failure. That is the single place metrics, logs and traces attach, so the core stays free of them.
StoreErrorPolicy ¶
What a limiter does when its store fails: let the request through, turn it away, or raise the store's error.
StoreErrorOutcome ¶
What happened to the request whose store failed: one of the policies, or it was counted in the fallback store instead.
DecisionEvent
dataclass
¶
DecisionEvent(key: str, scope: str, cost: int, decision: Decision)
A limiter decided whether a request may go ahead.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
Who the request was counted against. |
scope |
str
|
What the request was counted for. |
cost |
int
|
How much the request cost. |
decision |
Decision
|
The decision the caller received. |
StoreErrorEvent
dataclass
¶
StoreErrorEvent(error: Exception, outcome: StoreErrorOutcome)
A store failed while a limiter was using it.
Attributes:
| Name | Type | Description |
|---|---|---|
error |
Exception
|
What the store raised. |
outcome |
StoreErrorOutcome
|
What happened to the request. |
Observer ¶
Bases: Protocol
Something that wants to know what a limiter is doing.
The methods are called inline on the request path, so they should return quickly and must not raise.
Clocks and testing¶
paceapi.clock ¶
Clocks: where the limiter gets the time from.
Clock ¶
Bases: Protocol
Something that knows what time it is.
Give a limiter a clock to control time yourself, as tests do with
FrozenClock. Without one, each store uses its own
clock, which for a shared store is the same for every process.
paceapi.testing ¶
Helpers for testing code that uses paceapi.
FrozenClock ¶
A clock that stands still until it is moved.
Pass it to a limiter to make time-dependent behaviour deterministic:
clock = FrozenClock()
limiter = Limiter(clock=clock)
...
clock.advance(60) # a minute later, as far as the limiter can tell
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
float
|
The time the clock shows at first, in seconds. |
0.0
|
advance ¶
Move the clock forward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seconds
|
float
|
How far to move it. Must not be negative. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Errors¶
paceapi.errors ¶
The errors paceapi raises.
PaceError ¶
Bases: Exception
Base class for every error paceapi raises.
InvalidRateError ¶
Bases: PaceError, ValueError
A rate has a limit or period that cannot work, or its text is not a rate.
MissingKeyError ¶
Bases: PaceError
A limit's key returned nothing, so there was no one to count the request against.
This usually means a key that depends on the signed-in user ran for an
anonymous request. Cover that case with first_of(...), or pass
on_missing_key="skip" to the limit if such requests should not be limited.
StoreUnavailableError ¶
Bases: PaceError
A request was not counted because its store keeps failing and is being left alone.
Raised only by a limiter with on_store_error="raise", for a request that
did not try the store at all. Its cause is what the store last failed with.
A request that did try the store gets the store's own error.