Skip to content

Getting Started

  1. Install the package

    pnpm add pg-ratelimit pg
  2. 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 EXISTS on first use. No migrations needed.

  3. Check a rate limit

    const result = await ratelimit.limit("user:123");
    if (!result.success) {
    console.log(`Rate limited. Retry after ${result.reset}`);
    }

pg-ratelimit ships three algorithms as static methods on the Ratelimit class.

// 10 requests per minute
Ratelimit.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.

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 day
60000; // raw milliseconds