> ## Documentation Index
> Fetch the complete documentation index at: https://express-quota-limiter.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a custom storage driver for any database backend

> Implement the QuotaStorage interface to back express-quota-limiter with any database or cache — MySQL, PostgreSQL, DynamoDB, or any custom store.

`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:

```typescript theme={null}
interface QuotaStorage {
  decrement(key: string, limit?: number, weight?: number): Promise<QuotaResult>;
  increment(key: string, weight: number): Promise<void>;
}
```

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`:

```typescript theme={null}
interface QuotaResult {
  /** true if the request was within quota, false if it should be blocked */
  success: boolean;
  /** remaining operations in the current window; always >= 0 */
  remaining: number;
}
```

## Implementing a custom driver

```typescript theme={null}
import { QuotaStorage, QuotaResult } from "express-quota-limiter";

class MySQLDriver implements QuotaStorage {
  async decrement(key: string, limit: number = 100, weight: number = 1): Promise<QuotaResult> {
    // your implementation
  }

  async increment(key: string, weight: number = 1): Promise<void> {
    // your implementation
  }
}
```

## 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:

```typescript theme={null}
import express from "express";
import { createQuotaLimiter } from "express-quota-limiter";
import { MySQLDriver } from "./drivers/mysql-driver";

const app = express();
const driver = new MySQLDriver();

const apiQuota = createQuotaLimiter({
  storage: driver,
  limit: 1000,
  keyGenerator: (req) => `quota:api:${req.userId}`,
});

app.use("/api", apiQuota);
```

## 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:

```typescript theme={null}
// refund 10 operations for a user after a failed bulk action
await driver.increment("quota:emails:user123", 10);
```

> [!NOTE]
>
> 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`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.