Getting Started
-
Install the package
pnpm add pg-ratelimit pgnpm install pg-ratelimit pgyarn add pg-ratelimit pg -
Create a rate limiter
import { Pool } from "pg";import { Ratelimit } from "pg-ratelimit";const pool = new Pool({connectionString: process.env.DATABASE_URL,});const ratelimit = new Ratelimit({pool,limiter: Ratelimit.slidingWindow(10, "1m"),prefix: "api",});Tables are auto-created via
CREATE TABLE IF NOT EXISTSon first use. No migrations needed. -
Check a rate limit
const result = await ratelimit.limit("user:123");if (!result.success) {console.log(`Rate limited. Retry after ${result.reset}`);}
Choosing an algorithm
Section titled “Choosing an algorithm”pg-ratelimit ships three algorithms as static methods on the Ratelimit class.
// 10 requests per minuteRatelimit.fixedWindow(10, '1m')Simplest and fastest. Counts requests in a fixed time bucket. Has a known boundary problem - bursts at the window edge can effectively double the rate.
// 50 requests per 30 secondsRatelimit.slidingWindow(50, '30s')Weights the previous window against the current one based on time position. Fixes the boundary problem. Slightly more overhead than fixed window.
// Refill 5 tokens every 10s, max 20Ratelimit.tokenBucket(5, '10s', 20)Allows short bursts while enforcing an average rate. Great for quota-style rate limiting where you want to allow occasional spikes.
Duration format
Section titled “Duration format”Windows and intervals accept a Duration string or raw milliseconds:
"30s"; // 30 seconds"30 s"; // also 30 seconds (space is optional)"5m"; // 5 minutes"1h"; // 1 hour"1d"; // 1 day60000; // raw millisecondsWhat’s next?
Section titled “What’s next?”- Learn about each algorithm in detail: Fixed Window, Sliding Window, Token Bucket
- See the full API Reference
- Understand the Database Design