A Req plugin for rate limiting and throttling HTTP requests.
The plugin supports pluggable rate limiters that can be either:
- A module atom (e.g.,
MyApp.RateLimiter) that defines ahit/1function An anonymous function
(key) -> {:allow, count} | {:deny, retry_after_ms}
The rate limiter is responsible for managing scale, limit, and all rate limiting logic. This plugin only handles key generation and calling the rate limiter with the key.
Modes
:block(default) - Blocks and retries until a slot becomes available:error- Immediately returns an error tuple when the limit is reached
Configuration Options
rate_limiter(required) - Module atom or function that implements the rate limiting logickey_generator- Atom, function, or MFA tuple to generate the rate limit key from the request (default::host)- Atoms:
:host,:path,:host_and_path,:url - Functions:
&ReqThrottle.KeyGenerators.key_by_host/1, etc.
- Atoms:
mode-:blockor:error(default::block)max_retries- Maximum number of retries in block mode (default:3)
Examples
# Blocking mode with Hammer
Req.new()
|> ReqThrottle.attach(
rate_limiter: MyApp.RateLimiter,
key_generator: &ReqThrottle.KeyGenerators.key_by_host/1
)
# Error mode with custom function
Req.new()
|> ReqThrottle.attach(
rate_limiter: fn key ->
# Custom rate limiting logic
{:allow, 1}
end,
mode: :error
)
Summary
Functions
Attaches the ReqThrottle plugin to a request.
Functions
Attaches the ReqThrottle plugin to a request.
Options
rate_limiter(required) - Module atom or function that implements rate limitingkey_generator- Atom, function, or MFA tuple to generate the rate limit key (default::host)- Atoms:
:host,:path,:host_and_path,:url - Functions:
&ReqThrottle.KeyGenerators.key_by_host/1, etc. - MFA:
{Module, :function, [args]}
- Atoms:
mode-:blockor:error(default::block)max_retries- Maximum number of retries in block mode (default:3)
Examples
# Using atom shortcut
Req.new()
|> ReqThrottle.attach(
rate_limiter: MyApp.RateLimiter,
key_generator: :host
)
# Using function directly
Req.new()
|> ReqThrottle.attach(
rate_limiter: MyApp.RateLimiter,
key_generator: &ReqThrottle.KeyGenerators.key_by_host/1
)