Skip to content

RateLimit

runtoolkit edited this page Apr 13, 2026 · 1 revision

RateLimit

Sliding window rate limiter. Supports global keys, per-entity keys, and template key expansion.

Constructor

import { RateLimit } from './src/rate-limit.js';

const rl = new RateLimit();

Defining rules

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 player

Throws RangeError if maxHits < 1 or windowMs < 1.


Checking and recording hits

// 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
}

Template key resolution

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 / remaining

// 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');

Reset and cleanup

rl.reset('global:shoot');  // clear all recorded hits for this key

rl.cleanup();              // remove expired hits across all keys
                           // call periodically to prevent memory growth

Introspection

rl.hasRule('global:shoot'); // → true if a rule is configured for this key

Clone this wiki locally