WebsockexAdapter.RateLimiter (WebsockexAdapter v0.1.1)

View Source

Token bucket rate limiter for WebSocket API calls.

Prevents rate limit violations with configurable cost functions supporting credit-based (Deribit), weight-based (Binance), and simple rate limit (Coinbase) patterns through single algorithm.

Summary

Functions

Binance weight-based cost function.

Attempts to consume tokens for a request.

Deribit credit-based cost function.

Initializes rate limiter with configuration.

Refills tokens at configured rate.

Simple cost function for fixed-rate exchanges.

Returns current token count and queue size.

Types

config()

@type config() :: %{
  tokens: pos_integer(),
  refill_rate: pos_integer(),
  refill_interval: pos_integer(),
  request_cost: (term() -> pos_integer())
}

state()

@type state() :: %{
  tokens: non_neg_integer(),
  last_refill: integer(),
  queue: :queue.queue()
}

Functions

binance_cost(map)

@spec binance_cost(map()) :: pos_integer()

Binance weight-based cost function.

consume(name, request)

@spec consume(atom(), term()) :: :ok | {:error, :rate_limited | :queue_full}

Attempts to consume tokens for a request.

Returns :ok if tokens available, queues request if not.

deribit_cost(map)

@spec deribit_cost(map()) :: pos_integer()

Deribit credit-based cost function.

init(name, config)

@spec init(atom(), config()) :: {:ok, atom()} | {:error, term()}

Initializes rate limiter with configuration.

Creates ETS table for state storage and schedules refill timer.

refill(name)

@spec refill(atom()) :: :ok

Refills tokens at configured rate.

Called by timer process at refill intervals.

simple_cost(request)

@spec simple_cost(term()) :: pos_integer()

Simple cost function for fixed-rate exchanges.

status(name)

@spec status(atom()) ::
  {:ok, %{tokens: non_neg_integer(), queue_size: non_neg_integer()}}

Returns current token count and queue size.