Rate limits
import "std/concurrency" (included in import "std") · namespace std.concurrency
Rate limits kept in memory, safe to share between threads: TokenBucket (one limit: bursts up to a capacity, refilled steadily), TokenBuckets (a bucket per key) and SlidingWindow (at most n hits per window per key).
import "std"
fn main() {
let bucket = new TokenBucket(3, 10) // bursts of 3, then 10 a second
let sent = 0
for (i in 0..5) { if (bucket.tryTake()) { sent += 1 } }
print("sent ${sent} of 5 at once")
let api = new SlidingWindow(2, 60000) // 2 a minute per client
for (ip in ["10.0.0.1", "10.0.0.1", "10.0.0.1", "10.0.0.2"]) {
print(ip + (api.hit(ip) ? " allowed" : " refused, ${api.remaining(ip)} left"))
}
print(api.retryAfterMs("10.0.0.1") > 0)
let perUser = new TokenBuckets(1, 0.5) // one now, then one every 2 s, per user
print("${perUser.tryTake("ada")} ${perUser.tryTake("ada")} ${perUser.tryTake("bob")}")
}sent 3 of 5 at once
10.0.0.1 allowed
10.0.0.1 allowed
10.0.0.1 refused, 0 left
10.0.0.2 allowed
true
true false trueTokenBucket(capacity, perSecond)starts full.tryTake(n)takes tokens if they are there;take(n)waits for them;waitMs(n)says how long that would be (-1 when n is more than the capacity);available()counts them.SlidingWindow(limit, windowMs)counts each key's hits over a window that slides: the previous fixed window counts in proportion to how much of it is still covered, so a key cannot double its limit at a window's edge, and only two numbers are kept per key.hit(key, n),remaining(key),retryAfterMs(key)(for a Retry-After header),reset(key).- Keys (
TokenBuckets,SlidingWindow) are kept in 16 shards, each with its own lock, up tomaxKeys(100,000 by default) in all, forgetting the least recently used, so a flood of new clients cannot grow memory without bound. - Speed. About 90 ns for one
TokenBucket, 300 ns for a keyed check. - For limits shared by several servers, use the cache-backed
RateLimiterof grav-cache.
API
class BucketState
One token bucket's state (times in nanoseconds, monotonic).
Constructors
new BucketState(tokens: double, at: long)
Fields
tokens: doubleat: long
Methods
fn refill(capacity: double, perSecond: double, now: long)— Adds what accrued sinceat, up tocapacity.fn waitMs(n: double, capacity: double, perSecond: double) -> long— Milliseconds untilntokens are there (0: now; -1: never, n > capacity).
class TokenBucket
A token bucket: up to capacity tokens, refilled at perSecond; each action takes one (or n). Starts full.
Constructors
new TokenBucket(capacity: double, perSecond: double)
Fields
capacity: doubleperSecond: double
Methods
fn tryTake(n: double = 1.0) -> bool— Takesntokens if they are there; whether it did.fn take(n: double = 1.0)— Waits forntokens and takes them (ValueError when n is more than the capacity).fn available() -> double— The tokens there now.fn waitMs(n: double = 1.0) -> long— Milliseconds untilntokens are there (0: now; -1: never).
class TokenBuckets
A token bucket per key (a client, a user, an IP address).
Constructors
new TokenBuckets(capacity: double, perSecond: double, maxKeys: int = 100000)
Fields
capacity: doubleperSecond: double
Methods
fn tryTake(key: string, n: double = 1.0) -> bool— Takesnof the key's tokens if they are there; whether it did.fn available(key: string) -> doublefn waitMs(key: string, n: double = 1.0) -> long— Milliseconds until the key hasntokens (0: now; -1: never).fn reset(key: string)— Forgets a key (its bucket is full again).
class WindowCount
One key's counts for SlidingWindow: the current fixed window and the one before.
Constructors
new WindowCount(start: long)
Fields
start: longcurrent: long = 0previous: long = 0
class SlidingWindow
At most limit hits per windowMs per key, over a sliding window: the previous fixed window counts in proportion to how much of it the sliding window still covers (two numbers per key, not a log of every hit).
Constructors
new SlidingWindow(limit: long, windowMs: long, maxKeys: int = 100000)
Fields
limit: longwindowMs: long
Methods
fn hit(key: string, n: long = 1) -> bool— Countsnhits forkeyif they fit; whether they did.fn remaining(key: string) -> long— Hits the key has left in the sliding window now.fn retryAfterMs(key: string) -> long— Milliseconds until one more hit fits (0: now).fn reset(key: string)