Skip to main content

Module rate_limit

Module rate_limit 

Source
Expand description

Token-bucket rate limiter for authenticated-user create endpoints, persisted in the rate_buckets table.

Each (category, user) pair has its own bucket. A bucket has a per-category capacity and a per-category refill interval (one token per seconds_per_token seconds). On each acquisition the bucket is refilled based on elapsed wall-clock time (clamped to capacity) and one token is deducted; if fewer than one token is available the acquisition returns Error::TooManyRequests with a conservative Retry-After value equal to one refill interval.

The refill and deduction happen in a single SQLite UPSERT so two concurrent acquisitions for the same key cannot both pass — SQLite serialises the write and the ON CONFLICT DO UPDATE … WHERE clause re-checks the post-refill token count on the second arrival.

Enums§

RateCategory
Categories of rate-limited create endpoints. The string form maps directly to the rate_buckets.category column; the CHECK constraint in migration 0004_rate_buckets.sql lists the same three values.

Functions§

try_acquire
Try to acquire one token from category’s bucket for user_id. Returns Ok(()) on success and Error::TooManyRequests with a retry_after_secs equal to the per-category refill interval on failure.