-
Notifications
You must be signed in to change notification settings - Fork 1
RateLimit
runtoolkit edited this page Apr 13, 2026
·
1 revision
Sliding window rate limiter. Supports global keys, per-entity keys, and template key expansion.
import { RateLimit } from './src/rate-limit.js';
const rl = new RateLimit();rl.config(key, maxHits, windowMs);// Max 5 hits per second
rl.config('global:shoot', 5, 1000);
// Template rule — applies to any key matching 'player:shop:<anything>'
rl.config('player:shop', 3, 60_000); // 3 per minute per playerThrows RangeError if maxHits < 1 or windowMs < 1.
// check() records a hit if allowed, returns true; returns false if over limit
if (rl.check('global:shoot')) {
// allowed — hit recorded
}
// Per-entity: 'player:shop:alice' matches the 'player:shop' template
if (rl.check('player:shop:alice')) {
// allowed for alice
}If no exact rule exists for a key and the key contains at least 3 colon-separated segments, RateLimit strips the last segment and looks for a matching rule:
'player:shop:alice' → looks up 'player:shop'
Only one level of fallback is attempted.
// peek() checks without recording a hit
rl.peek('global:shoot'); // → true if a hit would be allowed
// remaining() returns ms until the oldest recorded hit expires
// returns 0 if under limit, Infinity if no rule
rl.remaining('global:shoot');rl.reset('global:shoot'); // clear all recorded hits for this key
rl.cleanup(); // remove expired hits across all keys
// call periodically to prevent memory growthrl.hasRule('global:shoot'); // → true if a rule is configured for this key