@beignet/provider-rate-limit-upstash

中文文档
0.0.65发布于 2026/11/08MITTypeScriptES Module近 30 天下载 1981

Upstash-based rate limit provider for Beignet - adds rate limit port using Upstash Redis

原始使用文档
文档目录19 节
  1. Features
  2. Install
  3. Configuration
  4. Choosing an algorithm
  5. Getting Upstash credentials
  6. Setup
  7. Direct adapter
  8. Direct use
  9. Different rate limits for different endpoints
  10. Using with contract metadata
  11. Rate limit result
  12. Implementation details
  13. Devtools
  14. Escape hatch
  15. Failure behavior
  16. Local and tests
  17. Deployment notes
  18. Testing
  19. License

@beignet/provider-rate-limit-upstash

Runtime: Beignet requires Node.js 22.12 or newer. Bun is optional.

[!CAUTION] Beignet is experimental alpha software. The 0.0.x package line is for early evaluation, and APIs may change between releases while the framework settles.

Upstash-backed RateLimitPort provider for Beignet applications.

The provider installs ctx.ports.rateLimit using Upstash Redis and @upstash/ratelimit.

createUpstashRateLimitProvider(...) returns the stable UpstashRateLimitProvider type. UpstashRateLimitConfig describes its validated config; the Zod schema remains internal.

Features

  • Implements the standard RateLimitPort interface.
  • Uses the Upstash Redis REST API, so it is serverless-friendly.
  • Supports dynamic limits per request with a configurable key prefix.
  • Supports fixed window and sliding window algorithms via UPSTASH_ALGORITHM.
  • Bounds dependency decisions and fails closed after five seconds by default.
  • Exposes a read-only readiness check through ctx.ports.upstash.
  • Emits devtools events for allowed, blocked, and failed hits.

Install

bun add @beignet/provider-rate-limit-upstash @beignet/core @upstash/redis @upstash/ratelimit

Configuration

Set these environment variables:

VariableRequiredDescriptionExample
UPSTASH_REDIS_REST_URLYesYour Upstash Redis REST URLhttps://us1-properly-ancient-12345.upstash.io
UPSTASH_REDIS_REST_TOKENYesYour Upstash Redis REST tokenAXXXeyJpZCI6IjEy...
UPSTASH_PREFIXNoKey prefix for rate limit keys (default: beignet:ratelimit)myapp:ratelimit
UPSTASH_ALGORITHMNoRate limit algorithm, fixed-window or sliding-window (default: fixed-window)sliding-window
UPSTASH_TIMEOUT_MSNoMaximum wait for a rate-limit decision, from 1 through 2147483647 milliseconds (default: 5000)2500
UPSTASH_TIMEOUT_POLICYNofail-closed rejects timed-out checks; fail-open allows them and records degraded enforcement (default: fail-closed)fail-closed

Choosing an algorithm

  • fixed-window (default) is the cheapest option: one counter per window. It can allow short bursts at window boundaries, since a client can spend a full limit at the end of one window and again at the start of the next.
  • sliding-window smooths those boundary bursts by weighting the previous window into the current one, at the cost of slightly more Redis work per hit.

Switching algorithms changes how counters are keyed in Redis, so in-flight windows effectively reset when you change UPSTASH_ALGORITHM.

Getting Upstash credentials

  1. Sign up at Upstash
  2. Create a new Redis database
  3. Navigate to the database details page
  4. Copy the REST URL and REST token from the "REST API" section

Setup

In a Beignet starter app, install and wire the port with:

bun beignet provider add rate-limit-upstash
bun install

Set the Upstash environment variables above. The preset extends the existing provider registry and app port wiring. Add createRateLimitHooks<AppContext>() from @beignet/core/server to the existing hooks list in server/index.ts to enforce contract metadata. Preserve the starter's authentication, context, other hooks, and providers.

For manual provider registration, import createUpstashRateLimitProvider from this package and add createUpstashRateLimitProvider() to your provider list. Follow the rate limiting guide for the server patch and verification steps.

The bare createRateLimitHooks<AppContext>() call covers global and user scoped limits. Contracts that declare rateLimit: { scope: "ip" } require an explicit server-level trustedProxy.clientIp, hook-local trustedProxy.clientIp, ipSource, or earlyKey option — createServer(...) fails at startup otherwise instead of silently assigning all unidentified traffic to a contract-scoped bucket. Prefer a server-level trustedProxy: { clientIp: "x-forwarded-for-last" } behind a trusted reverse proxy or trustedProxy: { clientIp: "cf-connecting-ip" } for platform headers. Use a hook-local option only for an intentional override, or ipSource: "none" to opt in to one unknown-client bucket per contract.

Default keys include the contract name, so unrelated contracts do not consume one another's limits. User scope fails with AuthUnauthorizedError unless route hooks resolve a user actor. A custom key or earlyKey owns the complete bucket key and should include route identity unless cross-route aggregation is intentional.

beignet doctor --strict checks that installed Upstash rate-limit providers are registered in server/providers.ts and that UPSTASH_REDIS_REST_URL/UPSTASH_REDIS_REST_TOKEN are present in app env examples or config.

Use createUpstashRateLimitProvider(...) when you want to pass config directly instead of reading UPSTASH_* env vars. Options override env-derived values:

import { createUpstashRateLimitProvider } from "@beignet/provider-rate-limit-upstash";

export const providers = [
  createUpstashRateLimitProvider({
    redisRestUrl: secrets.upstashRedisRestUrl,
    redisRestToken: secrets.upstashRedisRestToken,
    prefix: "myapp:ratelimit",
    algorithm: "sliding-window",
    timeoutMs: 2500,
    timeoutPolicy: "fail-closed",
  }),
];

Calling createUpstashRateLimitProvider() with no options uses the env-backed configuration.

Direct adapter

Use createUpstashRateLimit(...) when the app already owns an Upstash Redis client:

import { Redis } from "@upstash/redis";
import { createUpstashRateLimit } from "@beignet/provider-rate-limit-upstash";

const client = Redis.fromEnv();
const rateLimit = createUpstashRateLimit({
  client,
  prefix: "myapp:ratelimit",
  algorithm: "sliding-window",
  timeoutMs: 2500,
  timeoutPolicy: "fail-closed",
});

The direct factory defaults to the same beignet:ratelimit prefix and fixed-window algorithm as the provider. It reads no environment variables and does not own the client lifecycle. Pass instrumentation to retain provider events in direct wiring.

Direct use

Once the provider is registered, you can use the rate limit port in hooks, policies, or use cases:

// Example app-specific policy that rate limits by IP address
async function checkIpRateLimit(ctx: AppContext) {
  const result = await ctx.ports.rateLimit.hit({
    key: `ip:${ctx.ip}`,
    limit: 100,
    windowSec: 60, // 100 requests per 60 seconds
  });

  if (!result.allowed) {
    return {
      status: 429,
      headers: {
        "X-RateLimit-Limit": "100",
        "X-RateLimit-Remaining": String(result.remaining ?? 0),
        "X-RateLimit-Reset": result.resetAt?.toISOString() ?? "",
        "Retry-After": String(result.retryAfterSeconds ?? 0),
      },
      body: {
        code: "TOO_MANY_REQUESTS",
        message: "Rate limit exceeded. Please try again later.",
      },
    };
  }

  // Request is allowed
  return undefined;
}

Different rate limits for different endpoints

You can apply different rate limits for different operations:

// Strict rate limit for auth endpoints
const loginResult = await ctx.ports.rateLimit.hit({
  key: `login:${ctx.ip}`,
  limit: 5,
  windowSec: 300, // 5 attempts per 5 minutes
});

// More relaxed rate limit for API endpoints
const apiResult = await ctx.ports.rateLimit.hit({
  key: `api:user:${userId}`,
  limit: 1000,
  windowSec: 3600, // 1000 requests per hour
});

Using with contract metadata

You can define rate limit metadata on your contracts:

const getTodos = api.get("/todos")
  .meta({
    rateLimit: { max: 60, windowSec: 60, scope: "user" },
  });

The built-in createRateLimitHooks(...) helper reads this metadata and applies the limit through ctx.ports.rateLimit. If your app needs custom behavior, keep the same metadata shape and call the port directly:

type RateLimitMetadata = {
  rateLimit?: {
    max: number;
    windowSec: number;
    scope?: "global" | "ip" | "user";
  };
};

async function rateLimitFromMeta(ctx: AppContext, meta?: RateLimitMetadata) {
  if (!meta?.rateLimit) return;

  const { max, windowSec, scope = "global" } = meta.rateLimit;
  const actorId =
    ctx.actor?.type === "user" && ctx.actor.id ? ctx.actor.id : undefined;
  const result = await ctx.ports.rateLimit.hit({
    key:
      scope === "user"
        ? `user:${actorId ?? "anonymous"}`
        : `${scope}:${ctx.ip ?? "global"}`,
    limit: max,
    windowSec,
  });

  if (!result.allowed) {
    return {
      status: 429,
      body: {
        code: "TOO_MANY_REQUESTS",
        message: "Too many requests",
      },
    };
  }
}

Rate limit result

The hit method returns a RateLimitResult with:

interface RateLimitResult {
  allowed: boolean;                 // true if the hit is within the limit
  remaining: number | null;         // requests remaining in the window
  resetAt: Date | null;             // when the window resets
  retryAfterSeconds: number | null; // retry delay when the hit is rejected
}

Implementation details

  • Algorithm: Uses Ratelimit.fixedWindow() by default, or Ratelimit.slidingWindow() when UPSTASH_ALGORITHM=sliding-window
  • Backend: Upstash Redis REST API (serverless-compatible)
  • Per-request configuration: Caches one Ratelimit instance per (limit, windowSec, algorithm) combination to support dynamic limits without reconstructing limiters on every hit() call
  • Key prefix: Configurable prefix to avoid key collisions

Devtools

When @beignet/devtools is installed before this provider, rate limit checks appear under the dashboard's Rate limits watcher.

The provider records rateLimit.hit events with the key, limit, window, configured prefix, algorithm, allowed/blocked result, remaining count, reset time, retry-after value, and duration. Provider failures are recorded as rateLimit.hit.failed. An intentional fail-open timeout is recorded as rateLimit.hit.degraded, not as an ordinary allowed decision.

Escape hatch

The provider contributes the standard rateLimit port plus ctx.ports.upstash with the raw Upstash Redis client for operations the stable rate limit port does not model:

// Access the Redis client for advanced operations.
await ctx.ports.upstash.client.get("some:key");
await ctx.ports.upstash.client.set("some:key", "value");

// Use the read-only PING check from readiness and connected preflight.
const health = await ctx.ports.upstash.checkHealth();

To get proper type inference for the contributed ports, extend your ports type with UpstashRateLimitProviderPorts:

import type { UpstashRateLimitProviderPorts } from "@beignet/provider-rate-limit-upstash";

type AppPorts = typeof basePorts & UpstashRateLimitProviderPorts;
// Adds rateLimit plus upstash.client and upstash.checkHealth() to AppPorts.

Use the stable RateLimitPort for normal application behavior. Use the raw client only when the Upstash-specific operation is intentional.

Failure behavior

The env-backed provider throws during startup when required Upstash env vars are missing. Network and Upstash errors are recorded and rethrown unchanged.

Upstash's SDK can return an allowed result when it cannot make a decision before its timeout. Beignet treats that condition as an error by default: after UPSTASH_TIMEOUT_MS (default 5000), fail-closed records rateLimit.hit.failed and throws so protected work does not continue without enforcement. Set UPSTASH_TIMEOUT_POLICY=fail-open only when availability is more important than enforcement during an Upstash outage. Fail-open timeouts return an allowed result with unknown remaining/reset values and emit rateLimit.hit.degraded.

Local and tests

Use a fake RateLimitPort in route and use-case tests. For local development, either point at an Upstash development database or wire an app-owned memory rate limiter before this provider is needed.

Deployment notes

Rate-limit keys are part of production behavior. Set UPSTASH_PREFIX per app and environment so deploy previews, staging, and production do not share counters accidentally.

The provider uses Upstash's REST client and starts no worker or persistent connection, so the same adapter works in serverless and long-lived HTTP runtimes. The configured request-scoped timeout bounds each rate-limit decision and readiness PING. Add ctx.ports.upstash.checkHealth() to an app-owned readiness route; beignet preflight --connect discovers the same check automatically.

Testing

The provider includes comprehensive tests. Run them with:

bun test

License

MIT

版本与发布记录

@beignet/provider-rate-limit-upstash 共发布 65 个版本,首次发布于 2026/05/27;过去 12 个月发布了 65 个版本。

版本发布日期距今
0.0.65latest2026/11/08今天
0.0.642026/11/034 天前
0.0.632026/11/026 天前
0.0.622026/11/017 天前
0.0.612026/11/017 天前
0.0.602026/11/017 天前

关于 @beignet/provider-rate-limit-upstash 的常见问题

@beignet/provider-rate-limit-upstash 是什么?

Upstash-based rate limit provider for Beignet - adds rate limit port using Upstash Redis

如何安装 @beignet/provider-rate-limit-upstash?

在项目目录运行 npm install @beignet/provider-rate-limit-upstash,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@beignet/core(>=0.0.3 <1.0.0)、@upstash/redis(^1.0.0)、@upstash/ratelimit(^2.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@beignet/provider-rate-limit-upstash 支持 TypeScript 吗?

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

@beignet/provider-rate-limit-upstash 支持 ESM 还是 CommonJS?

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

@beignet/provider-rate-limit-upstash 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@beignet/provider-rate-limit-upstash 可以商用吗?

@beignet/provider-rate-limit-upstash 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@beignet/provider-rate-limit-upstash 的下载量有多少?

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

@beignet/provider-rate-limit-upstash 还在维护吗?

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