glimit
This module provides a rate limiter that can be used to limit the number of requests or function calls per second, minute or hour for a given identifier.
By default, rate limit state is stored in an ETS table with lock-free atomic operations. A periodic sweep removes buckets that have refilled to full to reduce memory usage.
For distributed rate limiting, you can provide a custom Store that
persists bucket state externally (Redis, Postgres, etc.).
The rate limiter fails open — if the store is unavailable, requests are allowed through. With multiple rates, a rate that cannot be checked is skipped and the other rates still apply.
The rate limits are configured using the following two options:
per_second,per_minuteorper_hour: The rate of new available tokens per second, minute or hour. Think of this as the steady state rate limit. Rates of different periods can be combined; a request must then pass all of them.burst_limit: The maximum number of available tokens. Think of this as the burst rate limit. The default value is the number of tokens per second, minute or hour set by the rate limit.
The rate limiter can be applied to a function or handler using the apply
function, which returns a new function that checks the rate limit before
calling the original function.
Example
import glimit
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.burst_limit(100)
|> glimit.identifier(fn(request) { request.ip })
|> glimit.on_limit_exceeded(fn(_request) { "Rate limit reached" })
let handler =
fn(_request) { "Hello, world!" }
|> glimit.apply(limiter)
Combining rates
Rates of different periods apply together, in any order. Setting a rate for a period that already has one replaces it. Each period has its own bucket, and a request only spends tokens if every bucket has one available.
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.per_hour(1000)
|> glimit.identifier(fn(request) { request.ip })
|> glimit.on_limit_exceeded(fn(_request) { "Rate limit reached" })
burst_limit is always the maximum number of requests in a single burst: it
sets the bucket size of the shortest period. Buckets of longer periods hold
at least their own rate, so a small burst limit does not shrink them.
Multi-argument functions
apply wraps a single-argument function fn(a) -> b. To rate-limit a
function with multiple arguments, use apply2, apply3, or apply4:
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.identifier(fn(args: #(String, String)) { args.0 })
|> glimit.on_limit_exceeded(fn(_args) { too_many_requests() })
let limited_handle =
handle
|> glimit.apply2(limiter)
limited_handle("user_123", "upload")
Pluggable store backend
By default, rate limit state is stored in-memory using ETS. For
distributed rate limiting (e.g. across multiple nodes), you can provide a
custom Store that persists bucket state externally (Redis, Postgres, etc.).
All token bucket logic stays in glimit — adapters only implement
lock_and_get / set_and_unlock / unlock operations. The glimit/bucket
module is public and provides to_pairs/from_pairs helpers for
serialization.
See examples/redis/ for a complete Redis adapter using
valkyrie.
Types
Error type returned when a rate limit check fails.
pub type HitError {
RateLimited
Unavailable
StoreLockFailed
}
Constructors
-
RateLimitedThe rate limit has been exceeded.
-
UnavailableThe rate limiter is unavailable, for example because no rate could be checked or a bucket could not be saved (fails open).
-
StoreLockFailedThe store lock could not be acquired (fails open).
A number of tokens generated per refill period.
pub type Rate(id) {
Rate(token_rate: fn(id) -> Int, refill_period_ms: Int)
}
Constructors
-
Rate(token_rate: fn(id) -> Int, refill_period_ms: Int)
A rate limiter.
pub type RateLimiter(a, b, id) {
RateLimiter(
on_limit_exceeded: fn(a) -> b,
identifier: fn(a) -> id,
rates: List(Rate(id)),
burst_limit: option.Option(fn(id) -> Int),
key_prefix: option.Option(String),
store: bucket.Store,
ets_store: option.Option(ets_store.EtsStore),
now: fn() -> Int,
)
}
Constructors
-
RateLimiter( on_limit_exceeded: fn(a) -> b, identifier: fn(a) -> id, rates: List(Rate(id)), burst_limit: option.Option(fn(id) -> Int), key_prefix: option.Option(String), store: bucket.Store, ets_store: option.Option(ets_store.EtsStore), now: fn() -> Int, )Arguments
- rates
-
The rates to enforce, shortest period first.
A builder for configuring the rate limiter.
pub type RateLimiterBuilder(a, b, id) {
RateLimiterBuilder(
rates: List(Rate(id)),
burst_limit: option.Option(fn(id) -> Int),
identifier: option.Option(fn(a) -> id),
on_limit_exceeded: option.Option(fn(a) -> b),
max_idle_ms: option.Option(Int),
store: option.Option(bucket.Store),
key_prefix: option.Option(String),
)
}
Constructors
-
RateLimiterBuilder( rates: List(Rate(id)), burst_limit: option.Option(fn(id) -> Int), identifier: option.Option(fn(a) -> id), on_limit_exceeded: option.Option(fn(a) -> b), max_idle_ms: option.Option(Int), store: option.Option(bucket.Store), key_prefix: option.Option(String), )
A pluggable storage backend for distributed rate limiting.
See glimit/bucket.Store for full documentation.
pub type Store =
bucket.Store
Values
pub fn apply(
func: fn(a) -> b,
config: RateLimiterBuilder(a, b, id),
) -> fn(a) -> b
Apply the rate limiter to a request handler or function.
Panics if the rate limiter cannot be started or if the identifier
function or on_limit_exceeded function is missing.
pub fn apply2(
func: fn(a, b) -> c,
config: RateLimiterBuilder(#(a, b), c, id),
) -> fn(a, b) -> c
Apply the rate limiter to a 2-argument function.
The config’s identifier and on_limit_exceeded receive a #(a, b) tuple.
Example
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.identifier(fn(args: #(String, String)) { args.0 })
|> glimit.on_limit_exceeded(fn(_) { "Rate limited" })
let limited =
handle
|> glimit.apply2(limiter)
limited("user_123", "upload")
pub fn apply3(
func: fn(a, b, c) -> d,
config: RateLimiterBuilder(#(a, b, c), d, id),
) -> fn(a, b, c) -> d
Apply the rate limiter to a 3-argument function.
The config’s identifier and on_limit_exceeded receive a #(a, b, c) tuple.
Example
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.identifier(fn(args: #(String, String, Int)) { args.0 })
|> glimit.on_limit_exceeded(fn(_) { "Rate limited" })
let limited =
handle
|> glimit.apply3(limiter)
limited("user_123", "upload", 42)
pub fn apply4(
func: fn(a, b, c, d) -> e,
config: RateLimiterBuilder(#(a, b, c, d), e, id),
) -> fn(a, b, c, d) -> e
Apply the rate limiter to a 4-argument function.
The config’s identifier and on_limit_exceeded receive a #(a, b, c, d) tuple.
Example
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.identifier(fn(args: #(String, String, Int, Bool)) { args.0 })
|> glimit.on_limit_exceeded(fn(_) { "Rate limited" })
let limited =
handle
|> glimit.apply4(limiter)
limited("user_123", "upload", 42, True)
pub fn apply_built(
func: fn(a) -> b,
limiter: RateLimiter(a, b, id),
) -> fn(a) -> b
Apply the rate limiter to a request handler or function.
This function is useful if you want to build the rate limiter manually using the
build function.
pub fn build(
config: RateLimiterBuilder(a, b, id),
) -> Result(RateLimiter(a, b, id), String)
Build the rate limiter.
Note that using apply will already build the rate limiter, so this function is
only useful if you want to build the rate limiter manually and apply it to multiple
functions.
To apply the resulting rate limiter to a function or handler, use the apply_built
function.
pub fn burst_limit(
limiter: RateLimiterBuilder(a, b, id),
burst_limit: Int,
) -> RateLimiterBuilder(a, b, id)
Set the maximum number of available tokens.
The maximum number of available tokens is the maximum number of requests that can be made in a single burst when the bucket is full. The default value is the same as the rate limit per second, minute or hour.
With multiple rates, this sets the bucket size of the shortest period, so it is still the maximum number of requests in a single burst. Buckets of longer periods hold at least their own rate, so a small burst limit does not shrink them. Without a burst limit, each bucket holds its own rate.
Example
import glimit
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.burst_limit(100)
pub fn burst_limit_fn(
limiter: RateLimiterBuilder(a, b, id),
burst_limit_fn: fn(id) -> Int,
) -> RateLimiterBuilder(a, b, id)
Set the maximum number of available tokens, based on the identifier.
Note: this function is evaluated once when a bucket is first created for an identifier. If the function returns a different value later, existing buckets are not affected until they are swept (once they have refilled to full) and re-created on the next hit. With an external store it runs while the bucket is locked. Concurrent requests for this identifier wait for it, and fail open if they stop waiting, so keep it fast.
Example
import glimit
let limiter =
glimit.new()
|> glimit.identifier(fn(request) { request.user_id })
|> glimit.per_second(10)
|> glimit.burst_limit_fn(fn(user_id) {
db.get_burst_limit(user_id)
})
pub fn get_count(limiter: RateLimiter(a, b, id)) -> Int
Return the number of tracked buckets in the ETS store.
An identifier has one bucket per rate, until a bucket is swept. Returns 0 if the rate limiter uses an external store.
pub fn hit(
limiter: RateLimiter(a, b, id),
identifier: id,
) -> Result(Nil, HitError)
Hit the rate limiter for the given identifier directly.
pub fn identifier(
limiter: RateLimiterBuilder(a, b, id),
identifier: fn(a) -> id,
) -> RateLimiterBuilder(a, b, id)
Set the identifier function to be used to identify the rate limit.
Example
import glimit
let limiter =
glimit.new()
|> glimit.identifier(fn(request) { request.ip })
pub fn key_prefix(
limiter: RateLimiterBuilder(a, b, id),
key_prefix: String,
) -> RateLimiterBuilder(a, b, id)
Set a prefix for the store keys of this rate limiter.
Bucket keys are built from the identifier and the refill period. Rate limiters that share an external store, identifier and period therefore share a bucket, unless they have different key prefixes. This has no effect on the default ETS store, where each rate limiter has its own table.
Example
import glimit
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.store(my_redis_store)
|> glimit.key_prefix("uploads")
|> glimit.identifier(fn(request) { request.ip })
|> glimit.on_limit_exceeded(fn(_request) { "Rate limit reached" })
pub fn max_idle(
limiter: RateLimiterBuilder(a, b, id),
seconds: Int,
) -> RateLimiterBuilder(a, b, id)
Deprecated: Buckets are kept until they have refilled; this setting has no effect
This setting has no effect.
It used to remove buckets that had not been hit for this many seconds. Removing a bucket before it has refilled gives the client a full burst back, so buckets are now kept until they have refilled and are then removed by the periodic sweep.
pub fn on_limit_exceeded(
limiter: RateLimiterBuilder(a, b, id),
on_limit_exceeded: fn(a) -> b,
) -> RateLimiterBuilder(a, b, id)
Set the handler to be called when the rate limit is reached.
Example
import glimit
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.on_limit_exceeded(fn(_request) { "Rate limit reached" })
pub fn per_hour(
limiter: RateLimiterBuilder(a, b, id),
limit: Int,
) -> RateLimiterBuilder(a, b, id)
Set the rate of new available tokens per hour.
Tokens are added continuously: per_hour(20) adds one token every three
minutes. This value is also used as the default value for the
burst_limit function. Setting per_hour again replaces the earlier
per-hour rate. A per_second or per_minute rate is kept, and a request
must pass all of them.
Example
import glimit
let limiter =
glimit.new()
|> glimit.per_hour(20)
pub fn per_hour_fn(
limiter: RateLimiterBuilder(a, b, id),
limit_fn: fn(id) -> Int,
) -> RateLimiterBuilder(a, b, id)
Set the rate limit per hour, based on the identifier.
This replaces an earlier per-hour rate. A per_second or per_minute rate is
kept, and a request must pass all of them.
Note: this function is evaluated once when a bucket is first created for an identifier. If the function returns a different value later, existing buckets are not affected until they are swept (once they have refilled to full) and re-created on the next hit. With an external store it runs while the bucket is locked. Concurrent requests for this identifier wait for it, and fail open if they stop waiting, so keep it fast.
Example
import glimit
let limiter =
glimit.new()
|> glimit.identifier(fn(request) { request.user_id })
|> glimit.per_hour_fn(fn(user_id) {
db.get_hourly_rate_limit(user_id)
})
pub fn per_minute(
limiter: RateLimiterBuilder(a, b, id),
limit: Int,
) -> RateLimiterBuilder(a, b, id)
Set the rate of new available tokens per minute.
Tokens are added continuously: per_minute(30) adds one token every two
seconds. This value is also used as the default value for the
burst_limit function. Setting per_minute again replaces the earlier
per-minute rate. A per_second or per_hour rate is kept, and a request
must pass all of them.
Example
import glimit
let limiter =
glimit.new()
|> glimit.per_minute(30)
pub fn per_minute_fn(
limiter: RateLimiterBuilder(a, b, id),
limit_fn: fn(id) -> Int,
) -> RateLimiterBuilder(a, b, id)
Set the rate limit per minute, based on the identifier.
This replaces an earlier per-minute rate. A per_second or per_hour rate is
kept, and a request must pass all of them.
Note: this function is evaluated once when a bucket is first created for an identifier. If the function returns a different value later, existing buckets are not affected until they are swept (once they have refilled to full) and re-created on the next hit. With an external store it runs while the bucket is locked. Concurrent requests for this identifier wait for it, and fail open if they stop waiting, so keep it fast.
Example
import glimit
let limiter =
glimit.new()
|> glimit.identifier(fn(request) { request.user_id })
|> glimit.per_minute_fn(fn(user_id) {
db.get_rate_limit(user_id)
})
pub fn per_second(
limiter: RateLimiterBuilder(a, b, id),
limit: Int,
) -> RateLimiterBuilder(a, b, id)
Set the rate of new available tokens per second.
Note that this is not the maximum number of requests that can be made in a single
second, but the rate at which tokens are added to the bucket. Think of this as the
steady state rate limit, while the burst_limit function sets the maximum number of
available tokens (or the burst rate limit).
This value is also used as the default value for the burst_limit function.
Setting per_second again replaces the earlier per-second rate. A per_minute
or per_hour rate is kept, and a request must pass all of them.
Example
import glimit
let limiter =
glimit.new()
|> glimit.per_second(10)
pub fn per_second_fn(
limiter: RateLimiterBuilder(a, b, id),
limit_fn: fn(id) -> Int,
) -> RateLimiterBuilder(a, b, id)
Set the rate limit per second, based on the identifier.
This replaces an earlier per-second rate. A per_minute or per_hour rate is
kept, and a request must pass all of them.
Note: this function is evaluated once when a bucket is first created for an identifier. If the function returns a different value later, existing buckets are not affected until they are swept (once they have refilled to full) and re-created on the next hit. With an external store it runs while the bucket is locked. Concurrent requests for this identifier wait for it, and fail open if they stop waiting, so keep it fast.
Example
import glimit
let limiter =
glimit.new()
|> glimit.identifier(fn(request) { request.user_id })
|> glimit.per_second_fn(fn(user_id) {
db.get_rate_limit(user_id)
})
pub fn remove(
limiter: RateLimiter(a, b, id),
identifier: id,
) -> Nil
Remove an identifier from the ETS store.
No-op if the rate limiter uses an external store.
pub fn store(
limiter: RateLimiterBuilder(a, b, id),
store: bucket.Store,
) -> RateLimiterBuilder(a, b, id)
Set a pluggable store backend for distributed rate limiting.
When a store is configured, bucket state is read from and written to the store on each hit instead of using the default ETS backend. External stores handle expiry via TTL.
Example
import glimit
let limiter =
glimit.new()
|> glimit.per_second(10)
|> glimit.store(my_redis_store)
|> glimit.identifier(fn(request) { request.ip })
|> glimit.on_limit_exceeded(fn(_request) { "Rate limit reached" })