# Multi-region rate limiting with MultiRegionRatelimit

## When you need it

Your API runs in several regions and a per-region limit is not
acceptable: an attacker could spend the full quota in every region.
MultiRegionRatelimit syncs state across your regional databases so
the limit is global.

## Setup

import { MultiRegionRatelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const ratelimit = new MultiRegionRatelimit({
  redis: [
    Redis.fromEnv(), // region 1 credentials
    // one client per regional database
  ],
  limiter: MultiRegionRatelimit.fixedWindow(10, "10 s"),
});

Use fixed window here. Sliding window multiplies command counts to
painful levels in multi-region, and token bucket is not supported
at all.

## The sync requirement

Cross-region sync happens in the background after limit() returns.
On serverless you must keep it alive:

const { success, pending } = await ratelimit.limit(id);
context.waitUntil(pending);

Without this, regions diverge and each enforces a local fiction of
the global limit.

## Cost math

Budget (1 + read region count) times write commands plus read
commands, per the docs. Two regions roughly doubles the
per-request command cost versus single-region.

## Alternative

One Global Upstash Redis database as the backend for a regular
Ratelimit gives you global state with server-side replication and
any algorithm, including token bucket. Compare the operational
simplicity before running N databases yourself.

## Verify

Spend quota from region A, then check getRemaining from region B:
it should reflect the spend. Burst-test across regions and confirm
the global verdict.