@absolutejs/rate-limit

中文文档
0.8.0发布于 2026/10/22BSL-1.1TypeScriptES Module构建来源已验证近 30 天下载 2131

First-class 2026 rate limit for Bun + Elysia. GCRA by default (exact, O(1) memory per key, no boundary effect — the algorithm Stripe uses), IETF draft-09 RateLimit-* headers, IPv6 /64 grouping, X-Forwarded-For trust modes, BigInt nanosecond TAT, pluggable

原始使用文档
文档目录7 节
  1. Why not just use the existing libraries
  2. Surface
  3. Elysia plugin ( @absolutejs/rate-limit )
  4. Algorithms ( @absolutejs/rate-limit/core )
  5. Store interface
  6. Algorithm picker
  7. License

@absolutejs/rate-limit

First-class, from-scratch, 2026 rate limit for Bun + Elysia. GCRA by default (the algorithm Stripe uses — exact, O(1) memory per key, no boundary effects), IETF draft-09 RateLimit-* headers, IPv6 /64 grouping, X-Forwarded-For trust modes, BigInt nanosecond TAT (no float drift), pluggable store (LRU in-memory bundled).

import { Elysia } from 'elysia';
import { rateLimit, gcra } from '@absolutejs/rate-limit';

new Elysia()
  .use(rateLimit({
    algorithm: gcra({ requestsPerPeriod: 100, periodMs: 60_000, burst: 20 }),
    key: 'ip',
    trustedProxies: 1, // single CDN/LB hop trusted
  }))
  .get('/', () => 'ok')
  .listen(3000);

Why not just use the existing libraries

The leader in the Elysia ecosystem is rayriffy/elysia-rate-limit. It uses a token bucket over a Map with a setInterval cleanup. That's fine, but every choice in it is from 2020. The 2026 from-scratch answers:

ConcernWhat others doWhat we do
AlgorithmToken bucket (allows brief bursts at refill boundaries)GCRA by default. Exact, no boundary effect, one BigInt of state per key. Token bucket and sliding window also bundled when you want them.
Time precisionDate.now() ms (float drift over long-lived keys)BigInt nanoseconds for GCRA TAT. Drift-free over any horizon.
IPv6Per-/128 (one cap per device — a /64 user with N devices gets N× their cap)Per-/64 group by default (RIR allocation = one user). Configurable.
Proxy trustTrust X-Forwarded-For blindly OR ignore ittrustedProxies: N — honor only the last N hops; spoof-resistant by default (N=0).
HeadersX-RateLimit-* (legacy GitHub-style)IETF draft-09 RateLimit-* + RateLimit-Policy by default. Legacy + both modes also available.
Store cleanupsetInterval sweeper (timer per process; lock contention on iteration)Lazy TTL at lookup time. No background timer.
Hot pathAsync even on memory storeSync when the store is sync, async only when it has to be.
CDN headersXFF onlyXFF + cf-connecting-ip + fly-client-ip + true-client-ip + x-real-ip.

Surface

Elysia plugin (@absolutejs/rate-limit)

rateLimit({
  algorithm: gcra({ requestsPerPeriod: 100, periodMs: 60_000, burst: 20 }),
  store: memoryStore({ maxKeys: 100_000 }),

  // key — defaults to 'ip' (uses extractIp).
  key: 'ip',                                                   // built-in
  // key: 'authorization',                                       // built-in
  // key: (ctx) => ctx.request.headers.get('x-user') ?? null,    // custom

  trustedProxies: 1,         // honor only the last hop of XFF (typical: 1)
  ipv6Prefix: 64,            // group IPv6 by /64

  skip: (ctx) => ctx.request.headers.get('authorization') === ADMIN_TOKEN,

  headers: 'standard',       // 'standard' | 'legacy' | 'both' | false

  onLimit: (ctx, info) => new Response(JSON.stringify({
    ok: false,
    retryAfterSec: info.decision.retryAfterSec,
  }), { status: 429, headers: { 'Content-Type': 'application/json' } }),
})

Algorithms (@absolutejs/rate-limit/core)

import { gcra, tokenBucket, slidingWindow, memoryStore } from '@absolutejs/rate-limit/core';

const limiter = gcra({ requestsPerPeriod: 100, periodMs: 60_000, burst: 20 });
const store = memoryStore();
const decision = limiter.check(store, 'user-42', Date.now());
// → { allowed, limit, remaining, retryAfterSec, resetSec, policy }

Use the core directly for non-HTTP rate-limiting — WebSocket-message rate limiting, queue-consumer throttling, AI-call quotas.

Store interface

type Store = {
  update<T>(key: string, ttlMs: number, fn: (prev: T | null) => T): T | Promise<T>;
  delete?(key: string): void | Promise<void>;
  clear?(): void | Promise<void>;
};

Implement update atomically (read-modify-write); the rest is optional. For Bun in-process use memoryStore(). Multi-replica Bun services backed by PostgreSQL can use the bundled durable adapter:

import { SQL } from 'bun';
import { postgresStore } from '@absolutejs/rate-limit/postgres';

const store = postgresStore({
  sql: new SQL(process.env.DATABASE_URL),
  table: 'absolute_rate_limit_entries',
});

The application owns the table migration. It requires key text PRIMARY KEY, value jsonb NOT NULL, expires_at timestamp NOT NULL, and updated_at timestamp NOT NULL. Per-key PostgreSQL transaction advisory locks linearize updates across replicas, including the first update before a row exists. Expired rows are replaced lazily on their next update; activeEntries() reports current cardinality and pruneExpired() provides a bounded operator cleanup primitive for abandoned keys.

Algorithm picker

  • GCRA — pick this unless you have a reason not to. Exact, O(1) memory, no boundary effects, BigInt math = no drift. Burst is configurable; set burst: 0 for strict pacing.
  • Token bucket — pick this when you specifically WANT the "fill the bucket and let the user fire it all at once" behavior. Cleaner mental model for end-users.
  • Sliding window — pick this when the customer-facing story is "you have N requests in the last M seconds." It's an approximation that can under-count by ~1 slot at heavy clustering, but it's the most intuitive to explain on a status page.

License

BSL 1.1 with a named carveout for the hosted rate-limit / WAF / API gateway throttling category (Cloudflare WAF + Rate Limiting, AWS WAF + API Gateway throttling, Kong, Tyk, Imperva, Akamai, GCP Cloud Armor, Azure Front Door rate-limiting, Upstash Ratelimit, Stripe's API gateway throttling). See LICENSE. Change Date: 4 years from first release; Change License: Apache 2.0.

sqlStore(client, table?) from @absolutejs/rate-limit/postgres supports host-managed PostgreSQL transactions without requiring Bun SQL. Supply query(text, params) -> { rows } and transaction(callback). Its journaled host-owned table has key text primary key, value jsonb, expires_at timestamptz, and updated_at timestamptz. Updates and deletes share a PostgreSQL advisory lock. Existing postgresStore({ sql }) remains available.

版本与发布记录

@absolutejs/rate-limit 共发布 18 个版本,首次发布于 2026/05/30;过去 12 个月发布了 18 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.8.0latest2026/10/2216 天前
0.7.12026/10/1325 天前
0.7.02026/09/241 个月前
0.6.12026/08/232 个月前
0.6.02026/08/202 个月前
0.5.22026/08/073 个月前

关于 @absolutejs/rate-limit 的常见问题

@absolutejs/rate-limit 是什么?

First-class 2026 rate limit for Bun + Elysia. GCRA by default (exact, O(1) memory per key, no boundary effect — the algorithm Stripe uses), IETF draft-09 RateLimit-* headers, IPv6 /64 grouping, X-Forwarded-For trust modes, BigInt nanosecond TAT, pluggable

如何安装 @absolutejs/rate-limit?

在项目目录运行 npm install @absolutejs/rate-limit,或使用 pnpm add / yarn add / bun add。

@absolutejs/rate-limit 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@absolutejs/rate-limit 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@absolutejs/rate-limit 可以商用吗?

@absolutejs/rate-limit 使用 BSL-1.1 许可。声明的许可为 BSL-1.1,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@absolutejs/rate-limit 的下载量有多少?

根据 npm 官方下载统计,@absolutejs/rate-limit 在 2026/10/05 – 2026/11/03 这 30 天内被下载 2,131 次,日均约 71 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@absolutejs/rate-limit 还在维护吗?

最新版本 0.8.0 发布于 2026/10/22(16 天前);至今共发布 18 个版本,其中过去 12 个月发布了 18 个;首次发布于 2026/05/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。