@rate-kit/storage-memory
v0.1.0
Published
In-process, dependency-free RateEngineStorage/LockStore implementation for @rate-kit/core.
Readme
@rate-kit/storage-memory
An in-process, dependency-free RateEngineStorage/LockStore
implementation for @rate-kit/core. Use it for local
development, testing, or single-process production deployments where a
distributed backend (Redis, PostgreSQL, ...) isn't needed.
Install
npm install @rate-kit/core @rate-kit/storage-memoryUsage
import { RateEngine } from "@rate-kit/core";
import { MemoryStorage } from "@rate-kit/storage-memory";
const engine = new RateEngine({
storage: new MemoryStorage(),
policy: { default: { limit: 100, windowMs: 60_000, key: "global" } }
});Options
new MemoryStorage({
clock?: () => number; // defaults to performance.now(); RateEngine.initialize() will
// adopt the engine's own clock automatically if you don't set one
cleanupIntervalMs?: number; // background sweep interval for expired entries; default 60_000, 0 disables it
});Design notes
- Per-key mutex, not a global lock. Every operation on a given key is
serialized through a promise chain scoped to that key, so unrelated keys
never contend with each other, while operations on the same key
(crucial for
RateEngine.consume()'s CAS loop) are strictly ordered. - Lazy expiration + a single background sweep. Expired entries are
removed on read; a single
setInterval(not one timer per key) also sweeps them periodically, bounding memory for keys nobody reads again. increment()'sttlMsonly applies on key creation, mirroring RedisINCR/INCRBYsemantics — it never resets an existing key's expiry.- Implements the optional
initialize({ context, clock })fromRateEngineStorage<C>: if you didn't pass your ownclockto the constructor,MemoryStorageadopts the engine's clock automatically so the two never drift.
See STORAGE_CONTRACT.md in @rate-kit/core
for the full behavioral spec this package implements — useful as the
reference when writing your own adapter (Redis, SQL, ...).
Development
pnpm install
pnpm --filter @rate-kit/storage-memory typecheck
pnpm --filter @rate-kit/storage-memory build
pnpm --filter @rate-kit/storage-memory test