Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

02 blocks

Rate limiter

Validated

Fixed-window request limits with memory and Redis stores for Express, Fastify, and Hono.

The rate limiter counts requests per key in a fixed time window. When a key passes the limit, the adapter returns 429 and stops the request before it reaches your route.

The block has no root index.ts. Import adapters from adapters/, stores from variants/, and shared types from core/core.

Quick start

pnpm dlx blockend-cli init
pnpm dlx blockend-cli add rate-limiter
import express from "express";
import { expressRateLimit } from "@/blocks/rate-limiter/adapters/express";
import { MemoryStore } from "@/blocks/rate-limiter/variants/memory-store";

const app = express();
const store = new MemoryStore();

app.use(
  expressRateLimit({
    windowMs: 60_000,
    max: 100,
    store
  })
);

app.get("/", (_req, res) => {
  res.json({ ok: true });
});

Files

rate-limiter/
├── adapters/
│   ├── express.ts
│   ├── fastify.ts
│   └── hono.ts
├── core/
│   └── core.ts
├── utils/
│   └── ip.ts
└── variants/
    ├── memory-store.ts
    └── redis-store.ts

The CLI copies the core, the IP helper, one adapter, and one store. There is no barrel file.

Installation

pnpm dlx blockend-cli add rate-limiter

The CLI uses your configured framework and asks for a store. Choose Redis if you run more than one app instance. The Redis variant installs ioredis.

Copy core/core.ts, utils/ip.ts, one adapter, and one store into blocks/rate-limiter. Keep the relative layout. Install your framework package, plus ioredis if you use RedisStore.

Core

// --- Core Interfaces ---
export interface RateLimitRecord {
  hits: number;
  resetTime: number; // Unix timestamp in ms
}

export interface RateLimitStore {
  increment(key: string, windowMs: number): Promise<RateLimitRecord> | RateLimitRecord;
}

export interface RateLimitConfig {
  windowMs: number;
  max: number;
  statusCode: number;
  message: string | Record<string, unknown>;
  standardHeaders: boolean;
  legacyHeaders: boolean; // <-- Added flag for backwards compatibility
}
export interface RateLimitResult {
  isBlocked: boolean;
  statusCode: number;
  message: string | Record<string, unknown>;
  headers: Record<string, string>;
}

// --- The Core Engine ---
export async function evaluateRateLimit(
  key: string,
  store: RateLimitStore,
  config: RateLimitConfig
): Promise<RateLimitResult> {
  const { hits, resetTime } = await store.increment(key, config.windowMs);
  const remaining = Math.max(0, config.max - hits);
  const now = Date.now();

  const retryAfterSeconds = Math.ceil(Math.max(0, resetTime - now) / 1000);
  const headers: Record<string, string> = {};
  const isBlocked = hits > config.max;

  // 1. Modern Standard Headers (RFC 9421 Draft Compliant)
  if (config.standardHeaders) {
    headers["RateLimit-Limit"] = `${config.max}, window=${Math.ceil(config.windowMs / 1000)}`;
    headers["RateLimit-Remaining"] = String(remaining);
    headers["RateLimit-Reset"] = String(retryAfterSeconds); // Remaining seconds
  }

  // 2. Legacy Headers (De facto Industry Standard - GitHub, Twitter, etc.)
  if (config.legacyHeaders) {
    headers["X-RateLimit-Limit"] = String(config.max);
    headers["X-RateLimit-Remaining"] = String(remaining);
    headers["X-RateLimit-Reset"] = String(Math.ceil(resetTime / 1000)); // Absolute Unix Epoch timestamp in seconds
  }

  if (isBlocked) {
    headers["Retry-After"] = String(retryAfterSeconds);
    return {
      isBlocked: true,
      statusCode: config.statusCode,
      message: config.message,
      headers
    };
  }

  return {
    isBlocked: false,
    statusCode: 200,
    message: "",
    headers
  };
}

IP helper

export function getClientIp(
  headers: Record<string, string | string[] | undefined>,
  remoteAddress?: string
): string {
  // 1. Check standard proxy headers (if you trust your upstream proxy environment)
  const xForwardedFor = headers["x-forwarded-for"];
  if (xForwardedFor) {
    const ips =
      typeof xForwardedFor === "string" ? xForwardedFor.split(",") : xForwardedFor[0]!.split(",");

    return ips[0]!.trim(); // The first IP is the actual client
  }
  const xRealIp = headers["x-real-ip"];
  if (typeof xRealIp === "string") return xRealIp;
  // 2. Fall back to raw socket address
  return remoteAddress || "unknown-ip";
}

Memory store

import type { RateLimitRecord, RateLimitStore } from "../core/core";

interface QueueEntry {
  key: string;
  resetTime: number;
}

export class MemoryStore implements RateLimitStore {
  private readonly store = new Map<string, RateLimitRecord>();
  // High-Performance Addition: A chronological queue tracking when keys expire
  private readonly expirationQueue: QueueEntry[] = [];
  private queueIndex = 0;

  public constructor() {
    // Periodically run a bounded incremental purge instead of a full loop
    setInterval(() => this.purge(), 60 * 1000).unref();
  }

  public increment(key: string, windowMs: number): RateLimitRecord {
    const now = Date.now();
    const existing = this.store.get(key);

    // 80/20 Optimization: Inline eviction if the key is already expired
    if (existing && now > existing.resetTime) {
      this.store.delete(key);
    }

    let record: RateLimitRecord;

    if (existing && now <= existing.resetTime) {
      record = {
        hits: existing.hits + 1,
        resetTime: existing.resetTime
      };
    } else {
      record = {
        hits: 1,
        resetTime: now + windowMs
      };
      // Track this key's expiration chronologically
      this.expirationQueue.push({ key, resetTime: record.resetTime });
    }

    this.store.set(key, record);

    return { ...record };
  }

  private purge(): void {
    const now = Date.now();

    // Chronological Sweep: Since items are appended in order of expiration time,
    // we only look at the oldest items at the front of our queue.
    // The moment we hit an item that hasn't expired yet, we can STOP instantly.
    while (this.queueIndex < this.expirationQueue.length) {
      const entry = this.expirationQueue[this.queueIndex]!;

      if (entry.resetTime > now) {
        break; // Stop immediately. Everything after this is still valid.
      }

      // Evict from map if the current record matches this expiration mark
      const currentRecord = this.store.get(entry.key);
      if (currentRecord && currentRecord.resetTime <= now) {
        this.store.delete(entry.key);
      }

      this.queueIndex++;
    }

    // Memory clean up for the queue array itself once it grows large
    if (this.queueIndex > 10000) {
      this.expirationQueue.splice(0, this.queueIndex);
      this.queueIndex = 0;
    }
  }
}

Redis store

import type { Redis } from "ioredis";
import type { RateLimitStore, RateLimitRecord } from "../core/core";

type RateLimitIncrementResult = [hits: number, pttl: number];

export interface RedisWithRateLimit extends Redis {
  performRateLimitIncrement(key: string, windowMs: number): Promise<RateLimitIncrementResult>;
}

export class RedisStore implements RateLimitStore {
  private readonly redisClient: RedisWithRateLimit;
  private readonly keyPrefix: string;

  constructor(redisClient: Redis, keyPrefix = "rl:") {
    redisClient.defineCommand("performRateLimitIncrement", {
      numberOfKeys: 1,
      lua: `
        local key = KEYS[1]
        local windowMs = tonumber(ARGV[1])

        local hits = redis.call('INCR', key)

        if hits == 1 then
          redis.call('PEXPIRE', key, windowMs)
        end

        local pttl = redis.call('PTTL', key)

        return { hits, pttl }
      `
    });

    // The command exists from this point onward.
    this.redisClient = redisClient as RedisWithRateLimit;
    this.keyPrefix = keyPrefix;
  }

  async increment(key: string, windowMs: number): Promise<RateLimitRecord> {
    const fullKey = `${this.keyPrefix}${key}`;
    const now = Date.now();

    const [hits, pttl] = await this.redisClient.performRateLimitIncrement(fullKey, windowMs);

    const actualRemainingMs = pttl > 0 ? pttl : windowMs;

    return {
      hits,
      resetTime: now + actualRemainingMs
    };
  }
}

Express adapter

import type { Request, Response, NextFunction } from "express";
import { evaluateRateLimit } from "../core/core";
import type { RateLimitStore, RateLimitConfig } from "../core/core";
import { getClientIp } from "../utils/ip";

export interface ExpressOptions extends Partial<RateLimitConfig> {
  store: RateLimitStore;
  keyGenerator?: (req: Request) => string;
}

export const expressRateLimit = (options: ExpressOptions) => {
  const config: RateLimitConfig = {
    windowMs: 60 * 1000,
    max: 100,
    statusCode: 429,
    message: { error: "Too many requests, please try again later." },
    standardHeaders: true,
    legacyHeaders: true,
    ...options
  };

  const keyGen =
    options.keyGenerator || ((req: Request) => getClientIp(req.headers, req.socket.remoteAddress));

  return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const key = keyGen(req);
      const result = await evaluateRateLimit(key, options.store, config);

      // Set computed rate limit headers dynamically
      for (const [name, value] of Object.entries(result.headers)) {
        res.setHeader(name, value);
      }

      if (result.isBlocked) {
        res.status(result.statusCode).send(result.message);
        return;
      }

      next();
    } catch (error) {
      // oxlint-disable-next-line no-console
      console.error("Rate limiter failure (Fail-Open):", error);
      next(); // Fail-open pattern intact
    }
  };
};

Fastify adapter

import type { FastifyRequest, FastifyReply } from "fastify";
import { evaluateRateLimit } from "../core/core";
import type { RateLimitStore, RateLimitConfig } from "../core/core";
import { getClientIp } from "../utils/ip";

export interface FastifyOptions extends Partial<RateLimitConfig> {
  store: RateLimitStore;
  keyGenerator?: (req: FastifyRequest) => string;
}

export const fastifyRateLimit = (options: FastifyOptions) => {
  const config: RateLimitConfig = {
    windowMs: 60 * 1000,
    max: 100,
    statusCode: 429,
    message: { error: "Too many requests, please try again later." },
    standardHeaders: true,
    legacyHeaders: true,
    ...options
  };

  const keyGen =
    options.keyGenerator ||
    ((req: FastifyRequest) => getClientIp(req.headers, req.socket.remoteAddress));

  return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {
    try {
      const key = keyGen(request);
      const result = await evaluateRateLimit(key, options.store, config);

      reply.headers(result.headers);

      if (result.isBlocked) {
        reply.code(result.statusCode).send(result.message);
        return; // Halts request lifecycle execution in Fastify hooks
      }
    } catch (error) {
      request.log.error(error, "Rate limiter failure (Fail-Open)");
      // Async hook implicit return continues execution automatically (Fail-Open)
    }
  };
};

Hono adapter

import { evaluateRateLimit } from "../core/core";
import type { RateLimitStore, RateLimitConfig } from "../core/core";
import { getClientIp } from "../utils/ip";
import type { ContentfulStatusCode } from "hono/utils/http-status";
import type { Context, MiddlewareHandler } from "hono";

export interface HonoOptions extends Partial<RateLimitConfig> {
  store: RateLimitStore;
  keyGenerator?: (c: Context) => string;
}

export const honoRateLimit = (options: HonoOptions): MiddlewareHandler => {
  const config: RateLimitConfig = {
    windowMs: 60 * 1000,
    max: 100,
    statusCode: 429,
    message: { error: "Too many requests, please try again later." },
    standardHeaders: true,
    legacyHeaders: true,
    ...options
  };

  const keyGen =
    options.keyGenerator ||
    ((c: Context) => getClientIp(Object.fromEntries(c.req.raw.headers.entries()), undefined));

  return async (c, next) => {
    try {
      const key = keyGen(c);
      const result = await evaluateRateLimit(key, options.store, config);

      // Set computed rate limit headers dynamically
      for (const [name, value] of Object.entries(result.headers)) {
        c.header(name, value);
      }

      if (result.isBlocked) {
        return c.json(result.message, result.statusCode as ContentfulStatusCode);
      }

      await next();
    } catch (error) {
      //oxlint-disable-next-line no-console
      console.error("Rate limiter failure (Fail-Open):", error);
      await next(); // Fail-open pattern intact
    }
  };
};

Configuration

Every adapter accepts the same options:

{
  store: RateLimitStore;
  windowMs?: number;
  max?: number;
  statusCode?: number;
  message?: string | Record<string, unknown>;
  standardHeaders?: boolean;
  legacyHeaders?: boolean;
  keyGenerator?: (request) => string;
}
OptionDefaultDescription
storeRequiredMemoryStore or RedisStore.
windowMs60000Window length in milliseconds.
max100Requests allowed per key per window.
statusCode429Status returned when the limit is exceeded.
message{ error: "Too many requests, please try again later." }Response body.
standardHeaderstrueAdds RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset.
legacyHeaderstrueAdds X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset.
keyGeneratorClient IPReturns the key to count.

max is the number of allowed requests. Request max + 1 is blocked.

Usage

Express

import express from "express";
import { expressRateLimit } from "@/blocks/rate-limiter/adapters/express";
import { MemoryStore } from "@/blocks/rate-limiter/variants/memory-store";

const app = express();
const store = new MemoryStore();

app.use(
  expressRateLimit({
    windowMs: 60_000,
    max: 100,
    store
  })
);

For a limit per authenticated user, mount the limiter after your auth middleware and use the user ID. The example assumes your auth middleware declares req.user on Express's request type:

app.use(
  "/api",
  expressRateLimit({
    windowMs: 60_000,
    max: 300,
    store,
    keyGenerator: (req) => req.user.id
  })
);

Fastify

import Fastify from "fastify";
import { fastifyRateLimit } from "@/blocks/rate-limiter/adapters/fastify";
import { MemoryStore } from "@/blocks/rate-limiter/variants/memory-store";

const app = Fastify();
const store = new MemoryStore();

app.addHook(
  "onRequest",
  fastifyRateLimit({
    windowMs: 60_000,
    max: 100,
    store
  })
);

await app.listen({ port: 3000 });

Hono

import { Hono } from "hono";
import { honoRateLimit } from "@/blocks/rate-limiter/adapters/hono";
import { MemoryStore } from "@/blocks/rate-limiter/variants/memory-store";

const app = new Hono();
const store = new MemoryStore();

app.use(
  "*",
  honoRateLimit({
    windowMs: 60_000,
    max: 100,
    store
  })
);

export default app;

Stores

MemoryStore

MemoryStore keeps counters in a Map in the current process. It cleans expired keys on a one-minute interval. Use it for a single process, local development, or tests.

It does not share state between app instances. Each instance gets its own limit, so a two-instance deployment effectively doubles the allowed request count.

RedisStore

RedisStore uses an ioredis client and a Lua script. The increment and expiry setup run atomically, so multiple instances share one counter.

import { Redis } from "ioredis";
import { RedisStore } from "@/blocks/rate-limiter/variants/redis-store";

const redis = new Redis(process.env.REDIS_URL!);

const store = new RedisStore(redis, "rl:");

The constructor signature is:

new RedisStore(redisClient, (keyPrefix = "rl:"));

keyPrefix separates rate limit keys from other data in the same Redis database. Use a different prefix per environment or application.

If Redis is unavailable, the adapter logs the error and lets the request continue. The route is unprotected during the outage. Decide whether that is acceptable for the endpoint.

Key generation

The default key is the client IP from x-forwarded-for, then x-real-ip, then the socket address. The Hono adapter has no socket address in Context, so it falls back to "unknown-ip" when both headers are missing. Behind a proxy that overwrites those headers, that is fine. Without one, every Hono client shares a single key.

getClientIp trusts x-forwarded-for and x-real-ip without checking whether the request came from a trusted proxy. If your app is reachable directly, a client can send its own header and choose a new key for every request. Run the app behind a proxy that overwrites these headers, or pass a keyGenerator that uses a value you control.

For authenticated routes, use the user or tenant ID. This example assumes your auth middleware sets req.user:

keyGenerator: (req) => `user:${req.user.id}`; // Express or Fastify

On Hono, read the user from context:

keyGenerator: (c) => `user:${c.get("user").id}`;

For unauthenticated routes, a normalized IP is reasonable:

keyGenerator: (req) => req.ip ?? req.socket.remoteAddress ?? "unknown"; // Express or Fastify

Behavior

The limiter uses a fixed window, not a sliding window or token bucket. A key gets max requests per window. Traffic can burst at a window boundary: 100 requests at the end of one window and 100 at the start of the next are both allowed.

When the store call succeeds, headers are set on both allowed and blocked responses:

HeaderMeaning
RateLimit-LimitMaximum requests and window length, such as 100, window=60.
RateLimit-RemainingRequests left after this one.
RateLimit-ResetSeconds until the window resets.
Retry-AfterSeconds until the client can retry. Only set when blocked.
X-RateLimit-ResetAbsolute Unix timestamp in seconds.

When the store throws, the adapter fails open. Express and Hono call next(), Fastify continues the request. Check your logs for Rate limiter failure.

API reference

expressRateLimit

function expressRateLimit(options: ExpressOptions): RequestHandler;

ExpressOptions extends Partial<RateLimitConfig> with store and keyGenerator.

fastifyRateLimit

function fastifyRateLimit(options: FastifyOptions): preHandlerHookHandler;

Register it as an onRequest hook or a route pre-handler.

honoRateLimit

function honoRateLimit(options: HonoOptions): MiddlewareHandler;

Register it with app.use.

evaluateRateLimit

function evaluateRateLimit(
  key: string,
  store: RateLimitStore,
  config: RateLimitConfig
): Promise<RateLimitResult>;

Runs one increment and returns isBlocked, statusCode, message, and headers. Use it if you need a custom adapter.

RateLimitStore

interface RateLimitStore {
  increment(key: string, windowMs: number): Promise<RateLimitRecord> | RateLimitRecord;
}

interface RateLimitRecord {
  hits: number;
  resetTime: number; // Unix timestamp in milliseconds
}

A custom store must increment atomically. A read-then-write implementation can let concurrent requests pass the limit.

Production notes

  • Use Redis when you run more than one process or container.
  • Put the limiter before expensive routes and before auth work you want to protect.
  • For per-user limits, put the limiter after auth so the user ID is available.
  • Set windowMs and max from your traffic profile. A global 100 requests per minute will block API clients that legitimately batch requests.
  • Alert on Redis errors. Fail-open behavior is intentional, but it means the limit is not enforced during an outage.
  • Add a separate limit for login, password reset, and other credential endpoints. A global limit is not a brute-force defense.

When not to use it

  • You need distributed coordination across regions with strict limits. A single Redis instance is still a single point of failure.
  • You need per-endpoint cost weighting. This block counts requests, not units of work.
  • You need a sliding window with no boundary burst. Use a different algorithm.
  • Idempotency deduplicates retries after the limiter lets them through.
  • Password hash handles credential storage. Rate limiting login attempts is still your app's job.
  • Logger records rate limit failures and store outages.

On this page