Karta.RateLimiter (Karta v1.0.0)

Per-node rate limits in memory: at most limit events per window milliseconds for a key (a tracking event of a recipient, an MTA-STS policy fetch).

Limits that must hold across nodes are counted in the database (Karta.Limits): a credential's requests or messages, login attempts, TOTP codes and API key verifications. This module keeps the counters whose keys are this node's own work — an event it records, a policy it fetches — where a database round trip would be paid for every event.

The window slides: events are counted in fixed windows, and the previous window counts for the part of it that still lies inside the sliding window (previous * (1 - elapsed / window) + current). A refused event is not counted. Counters live in one ETS table and are updated without going through a process, so checks are cheap and concurrent.

Bounded. The table keeps at most max_entries counters (default 100,000) and removes the windows closest to their end first, as Karta.DNS.Cache removes the entries closest to expiry. Windows that have ended are swept every cleanup_interval milliseconds (default 60,000).

A restarting limiter refuses. While the table does not exist (its owner is restarting), hit/5 answers {:error, window}: a limit that cannot be read is not bypassed.

Summary

Functions

Returns a specification to start this module under a supervisor.

Removes the counters whose window and the one after it have ended.

Counts an event for key: :ok, or {:error, retry_after_ms} when the limit is reached or the counter cannot be read. now: (milliseconds) replaces the clock in tests.

Options: name (also the ETS table; default this module), cleanup_interval (ms), max_entries.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

cleanup(name, now \\ now())

@spec cleanup(atom(), non_neg_integer()) :: non_neg_integer()

Removes the counters whose window and the one after it have ended.

hit(name, key, limit, window, opts \\ [])

@spec hit(atom(), term(), pos_integer(), pos_integer(), keyword()) ::
  :ok | {:error, pos_integer()}

Counts an event for key: :ok, or {:error, retry_after_ms} when the limit is reached or the counter cannot be read. now: (milliseconds) replaces the clock in tests.

start_link(opts)

Options: name (also the ETS table; default this module), cleanup_interval (ms), max_entries.