express-quota-limiter ships with RedisDriver and MemoryDriver, but it is not tied to either. Any class that implements the QuotaStorage interface can serve as the storage backend. This means you can store quota counters in PostgreSQL, MySQL, DynamoDB, or any other system that suits your infrastructure.
The QuotaStorage interface
Your driver must implement two methods:key string that uniquely identifies the quota counter (generated by your keyGenerator function). The decrement method also receives the configured limit and the request’s weight.
QuotaResult
decrement must return a QuotaResult:
Implementing a custom driver
Rules for implementing decrement
A correct decrement implementation must follow these rules:
- Atomicity — the read-modify-write cycle must be atomic. Use database transactions, row-level locks, or atomic operations (e.g.
UPDATE ... RETURNING) to prevent race conditions under concurrent load. remainingis always>= 0— clamp the value to zero before returning it so theQuota-Remainingheader is never negative.successreflects the post-decrement state — setsuccess: truewhenremaining >= 0after subtractingweight, andsuccess: falseotherwise. Do not block the request before decrementing; decrement first, then decide.- Initialize missing keys — if the key does not yet exist, create it with
remaining = limit - weightand start the TTL window. Never return an error for a missing key.
Rules for implementing increment
The increment method is used to refund quota — for example, when an action fails after the middleware has already charged for it, or when an administrator manually adjusts a tenant’s allowance.
- Do not create new keys — if the key does not exist in the store,
incrementshould be a no-op. Refunding quota for a key that has never been used or has already expired makes no sense. - Add
weightto the current counter — theweightparameter may be any positive integer. Add it to the currentremainingvalue.
Using your driver with createQuotaLimiter
Pass an instance of your custom driver to thestorage option exactly as you would any built-in driver:
Manual increment via the driver
You can calldriver.increment directly at any point in your application — for example, to refund quota when a downstream service call fails, or to make an admin adjustment:
The
increment method on all built-in drivers will silently do nothing if the key does not exist. Match this behavior in your custom driver so callers do not need to check whether a key is present before calling increment.