MySQL
MySQL-backed fixed window and token bucket rate limiting.
Overview
- MySQL-backed rate limit store supporting fixed windows and a rolling token bucket.
- Creates the required tables and indexes if they do not exist.
Usage
import mysql from "mysql2/promise";
import { MysqlRateLimitStore, usefulkey } from "betterkey";
const pool = mysql.createPool({ uri: process.env.DATABASE_URL! });
const rateLimitStore = new MysqlRateLimitStore(
{ query: (sql, values) => pool.query(sql, values) },
{ tableName: "usefulkey_rate_limits" },
);
const uk = usefulkey({ adapters: { rateLimitStore } });
Client compatibility
- Any MySQL client exposing
query(sql, params?)
and returning either[rows, fields]
or an object withrows
.
Options
Option | Type | Default | Description |
---|---|---|---|
tableName | string | "usefulkey_rate_limits" | Base table name for fixed windows (bucket table is suffixed with _buckets ). |
Tables
CREATE TABLE IF NOT EXISTS usefulkey_rate_limits (
namespace VARCHAR(255) NOT NULL,
identifier VARCHAR(255) NOT NULL,
count INT NOT NULL,
reset BIGINT NOT NULL,
PRIMARY KEY(namespace, identifier),
KEY idx_usefulkey_rate_limits_reset (reset)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS usefulkey_rate_limits_buckets (
namespace VARCHAR(255) NOT NULL,
identifier VARCHAR(255) NOT NULL,
tokens DOUBLE NOT NULL,
lastRefill BIGINT NOT NULL,
capacity INT NOT NULL,
refillTokens DOUBLE NOT NULL,
refillIntervalMs BIGINT NOT NULL,
PRIMARY KEY(namespace, identifier),
KEY idx_usefulkey_rate_limits_buckets_lastRefill (lastRefill)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;