Skip to main content
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:
Both methods receive a 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.
  • remaining is always >= 0 — clamp the value to zero before returning it so the Quota-Remaining header is never negative.
  • success reflects the post-decrement state — set success: true when remaining >= 0 after subtracting weight, and success: false otherwise. 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 - weight and 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, increment should be a no-op. Refunding quota for a key that has never been used or has already expired makes no sense.
  • Add weight to the current counter — the weight parameter may be any positive integer. Add it to the current remaining value.

Using your driver with createQuotaLimiter

Pass an instance of your custom driver to the storage option exactly as you would any built-in driver:

Manual increment via the driver

You can call driver.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.