Kantoor.RateLimiter (Kantoor v1.0.0)

A small fixed-window counter in Postgres, used to throttle failed logins and requests.

The counters are rows in rate_counters, so every replica of Kantoor counts into the same numbers: a client locked out through one replica is locked out on all of them. hit/3 is one atomic upsert (INSERT ... ON CONFLICT DO UPDATE ... RETURNING), so concurrent attempts, on one replica or many, cannot slip past a limit. The key is stored as a hash.

The clock is always passed in (now, unix seconds), which keeps tests deterministic. A counter belongs to the window that contains now; rows of windows that ended are removed by sweep/1, which the maintenance job :rate_limiter runs (under an advisory lock, so only one replica does it at a time).

Memory is bounded the same way as before, in rows: the table never grows past max_entries (config :kantoor, Kantoor.RateLimiter, max_entries: n, default 200_000) for longer than a sweep. sweep/1 also trims the oldest windows first when the table is over the cap, and a [:kantoor, :rate_limiter, :full] telemetry event fires. Counters of offenders keep counting meanwhile; the cap is enforced by the sweep, not by refusing to count, so a limit never fails open.

Summary

Functions

The count for key in the window containing now, without counting a hit.

Counts one hit for key in the window containing now; returns the new count.

The configured cap on the number of counters.

Forgets every counter.

The number of counters held (for tests and telemetry).

Removes the counters of windows that ended by now, then trims to max_entries.

Functions

count(key, window, now)

@spec count(term(), pos_integer(), integer()) :: non_neg_integer()

The count for key in the window containing now, without counting a hit.

hit(key, window, now)

@spec hit(term(), pos_integer(), integer()) :: pos_integer()

Counts one hit for key in the window containing now; returns the new count.

max_entries()

@spec max_entries() :: pos_integer()

The configured cap on the number of counters.

reset()

@spec reset() :: :ok

Forgets every counter.

size()

@spec size() :: non_neg_integer()

The number of counters held (for tests and telemetry).

sweep(now)

@spec sweep(integer()) :: :ok

Removes the counters of windows that ended by now, then trims to max_entries.