Framework
Decide what consumes a request budget, where counters live, and how the endpoint responds if the counter service is unavailable. A single-process development setup and several production replicas can require different backend choices.
Open Mercato ships with a built-in rate limiting utility powered by rate-limiter-flexible. It supports in-memory and Redis backends, is globally configurable via environment variables, and integrates with the API dispatcher and route handlers.
Rate limiting is enabled by default with an in-memory backend. No configuration is required for development. Authentication endpoints (login, password reset) are protected out of the box.
To switch to Redis for production (distributed, multi-instance):
RATE_LIMIT_STRATEGY=redis
REDIS_URL=redis://localhost:6379
Open Mercato supports three complementary ways to enforce rate limits:
Declare rateLimit in your route's metadata export. The API dispatcher enforces it automatically using the client IP as the key:
// packages/core/src/modules/my_module/api/some-endpoint/route.ts
export const metadata = {
POST: {
requireAuth: true,
rateLimit: {
points: 10, // max requests per window
duration: 60, // window in seconds
keyPrefix: 'my-endpoint',
},
},
}
export async function POST(req: Request) {
// Rate limiting happens before this code runs.
// If the client exceeds the limit, the dispatcher returns 429 automatically.
}
This follows the same pattern as requireAuth and requireFeatures – zero boilerplate in the handler.
Routes that must limit work before generic credential lookup can export an optional beforeAuth function, typed as ApiRouteBeforeAuth from @open-mercato/shared/modules/registry. After matching a supported route and method, the dispatcher calls this function before resolving staff JWTs, API keys, authorization guards, or metadata-driven limits.
The hook receives the original Request and { method, params }. Return null to continue through normal authentication and authorization, or return a Response to stop immediately with its body, status, and headers intact. A thrown error stops the request without resolving credentials. The hook does not authenticate a principal or bypass any later permission checks. It runs for every supported method in that route file, including legacy routes; routes without it keep their existing behavior.
Public SCIM provisioning routes use this hook before generic credential resolution. Discovery has a separate budget. A full-bearer SHA-256 lookup fingerprint is persisted alongside the existing bcrypt verifier. On a cache miss, an indexed exact match against active tokens selects the private tenant/organization/token-ID budget without running bcrypt. Newly generated tokens are enrolled at creation, so their first request remains admitted when anonymous traffic exhausts the unverified budget, including after cache expiry or restart. A short-lived DI cache accelerates repeated requests. A guessed active prefix with a wrong suffix receives the same unverified trusted-IP or fixed fallback budget as any unknown bearer; the short prefix never selects a private bucket. Private quotas take precedence over trusted IdP egress IPs.
Lookup fingerprints are internal metadata and never appear in token-management responses or limiter keys. No raw bearer or bcrypt hash is cached or logged. Every admitted request still verifies the active token with bcrypt and checks organization/configuration scope. Revocation persists first, then invalidates its cache tag best-effort; cache or telemetry failures cannot turn a committed revocation into an API failure, and stale hints cannot authenticate revoked tokens. Admission-cache reads, fingerprint lookups, and limiter decisions fail closed with SCIM 503 when unavailable.
Legacy tokens keep working with a nullable fingerprint. After a successful bcrypt comparison, backfill checks the token ID, tenant, organization, configuration, active state, compared bcrypt hash, and an absent or identical fingerprint before writing. Until enrollment, legacy tokens still use the bounded unverified budget on a cache miss. The full cold-start protection guarantee requires zero active unenrolled legacy tokens. Follow the SCIM fingerprint rollout and cutover procedure to enroll them through existing SCIM requests or rotate them through existing token APIs; a schema migration cannot reconstruct fingerprints from bcrypt hashes. No token is silently invalidated by the migration.
Forwarding headers remain ignored until the actual proxy depth is configured. Size RATE_LIMIT_SCIM_POINTS for legitimate provisioning bursts and have IdPs honor Retry-After; raising this limit is not a mitigation for unenrolled legacy tokens. Redis shares cache entries and invalidation across replicas, while the database fingerprint preserves enrolled-token admission independently of cache warmth.
The handler-level fallback reuses the same request's admission promise, so dispatch and handler checks consume one point altogether. When adopting this pattern, avoid charging the same request again in the handler and avoid consuming its body before the handler reads it.
For advanced key strategies (e.g., compound IP:emailHash keys), use the checkAuthRateLimit centralizer. This is how the authentication endpoints work – it handles two-layer checks (IP-only + compound), email hashing, fail-open semantics, and i18n in a single call:
import { checkAuthRateLimit, resetAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'
import { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'
const myRateLimitConfig = readEndpointRateLimitConfig('LOGIN', {
points: 5, duration: 60, blockDuration: 60, keyPrefix: 'login',
})
const myIpRateLimitConfig = readEndpointRateLimitConfig('LOGIN_IP', {
points: 20, duration: 60, blockDuration: 60, keyPrefix: 'login-ip',
})
export async function POST(req: Request) {
const form = await req.formData()
const email = String(form.get('email') ?? '')
// Two-layer rate limit — checked before validation and DB work
const { error: rateLimitError, compoundKey } = await checkAuthRateLimit({
req,
ipConfig: myIpRateLimitConfig,
compoundConfig: myRateLimitConfig,
compoundIdentifier: email,
})
if (rateLimitError) return rateLimitError
// ... auth logic ...
// Reset compound counter on successful auth
if (compoundKey) {
await resetAuthRateLimit(compoundKey, myRateLimitConfig)
}
}
The centralizer internally resolves the rate limiter service, extracts the client IP, hashes the email via computeEmailHash() (SHA-256), and wraps everything in a fail-open try/catch. If the service is unavailable or the IP cannot be determined, it allows the request through.
| Approach | Key Strategy | Use Case |
|---|---|---|
| Metadata-driven | Client IP only | General API endpoints, simple abuse prevention |
| Handler-level | Custom (IP+email, token, etc.) | Auth endpoints, credential stuffing protection |
The following authentication endpoints have two-layer rate limiting built in:
Layer 1 – IP-only caps total attempts from a single IP (regardless of email):
| Endpoint | Key | Points | Window | Block |
|---|---|---|---|---|
POST /api/login | IP | 20 | 60s | 60s |
POST /api/reset | IP | 10 | 60s | 60s |
POST /api/reset/confirm | IP | 5 | 300s | – |
POST /api/auth/reset/validate | IP | 10 | 300s | – |
Layer 2 – Compound caps attempts per IP + account pair (email is SHA-256 hashed):
| Endpoint | Key | Points | Window | Block |
|---|---|---|---|---|
POST /api/login | IP:emailHash | 5 | 60s | 60s |
POST /api/reset | IP:emailHash | 3 | 60s | 60s |
The reset-confirm and reset-validate endpoints use IP-only limiting because no email is available at that point – both are reached with a token alone. Reset-validate is the read-only check the reset page makes on load to decide whether to render the password form or a terminal "link is no longer valid" state; it never consumes the token, so it gets a slightly larger budget than reset-confirm.
On successful login, the compound counter is automatically reset so legitimate users aren't penalized for prior typos. The IP-only counter is not reset.
Attachment uploads (handler-level, per tenant + authenticated user):
| Endpoint | Key | Points | Window | Block |
|---|---|---|---|---|
POST /api/attachments | tenantId:principal | 30 | 60s | – |
AI agent tools (one bucket for every agent tool, per tenant + API key, or per user for session-token callers):
| Endpoint | Key | Points | Window | Block |
|---|---|---|---|---|
MCP tools/call and POST /api/ai_assistant/tools/execute | tenant:key:<apiKeyId> / tenant:user:<userId> | 30 | 60s | – |
Plain (non-agent) tools and agent tools called inside an agent's own loop are not counted. Details: MCP → Rate limit.
All limits can be overridden via environment variables (see Configuration).
When a client exceeds the rate limit, the API returns:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 47
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 47
{
"error": "Too many requests. Please try again later."
}
The error message is translated according to the user's locale. Rate limit headers are only included on 429 responses.
| Header | Description |
|---|---|
Retry-After | Seconds until the client can retry |
X-RateLimit-Limit | Maximum points allowed in the window |
X-RateLimit-Remaining | Points remaining (always 0 on 429) |
X-RateLimit-Reset | Seconds until the window resets |
An endpoint that opted into failClosed answers 503 while the limiter cannot decide, instead of
serving the request uncounted. No rate-limit headers are sent – there is no window to report:
HTTP/1.1 503 Service Unavailable
Content-Type: application/json
{
"error": "Service temporarily unavailable. Please try again later."
}
The message deliberately reveals nothing about the limiter or its backing store; the cause is
logged instead. POST /api/checkout/pay/[slug]/submit and
POST /api/checkout/pay/[slug]/verify-password return it, so a client of those routes should
treat 503 as retryable rather than as a submission failure.
AI agent tools also fail closed. POST /api/ai_assistant/tools/execute answers 503 with
{ "success": false, "error": "...", "code": "RATE_LIMIT_UNAVAILABLE" }; over MCP the call returns
the RATE_LIMIT_UNAVAILABLE error code. The agent is not started; retry later.
| Variable | Default | Description |
|---|---|---|
RATE_LIMIT_ENABLED | true | Master switch. Set to false to disable all rate limiting. |
RATE_LIMIT_STRATEGY | memory | Backend: memory (single instance) or redis (distributed). |
RATE_LIMIT_KEY_PREFIX | rl | Key prefix in storage. Prevents collisions with other Redis data. |
RATE_LIMIT_TRUST_PROXY_DEPTH | 0 | Number of trusted reverse proxies for X-Forwarded-For IP extraction. 0 is safe direct mode: forwarding headers are ignored and rate limiters use endpoint-scoped global fallback buckets. Positive values must match the trusted proxy chain exactly. Invalid values warn and fall back to 0. |
When using redis strategy, the service reads REDIS_URL (already used by cache, events, and queue modules).
Compound layer (IP + hashed email):
| Variable | Default | Description |
|---|---|---|
RATE_LIMIT_LOGIN_POINTS | 5 | Max login attempts per IP+account per window |
RATE_LIMIT_LOGIN_DURATION | 60 | Window in seconds |
RATE_LIMIT_LOGIN_BLOCK_DURATION | 60 | Block duration after exceeding limit |
RATE_LIMIT_RESET_POINTS | 3 | Max password reset requests per IP+account per window |
RATE_LIMIT_RESET_DURATION | 60 | Window in seconds |
RATE_LIMIT_RESET_BLOCK_DURATION | 60 | Block duration after exceeding limit |
IP-only layer:
| Variable | Default | Description |
|---|---|---|
RATE_LIMIT_LOGIN_IP_POINTS | 20 | Max total login attempts per IP per window |
RATE_LIMIT_LOGIN_IP_DURATION | 60 | Window in seconds |
RATE_LIMIT_LOGIN_IP_BLOCK_DURATION | 60 | Block duration after exceeding IP limit |
RATE_LIMIT_RESET_IP_POINTS | 10 | Max total reset requests per IP per window |
RATE_LIMIT_RESET_IP_DURATION | 60 | Window in seconds |
RATE_LIMIT_RESET_IP_BLOCK_DURATION | 60 | Block duration after exceeding IP limit |
RATE_LIMIT_RESET_CONFIRM_POINTS | 5 | Max reset confirm attempts per IP per window |
RATE_LIMIT_RESET_CONFIRM_DURATION | 300 | Window in seconds |
RATE_LIMIT_RESET_VALIDATE_POINTS | 10 | Max reset-token checks per IP per window |
RATE_LIMIT_RESET_VALIDATE_DURATION | 300 | Window in seconds |
Attachment uploads:
| Variable | Default | Description |
|---|---|---|
RATE_LIMIT_ATTACHMENTS_UPLOAD_POINTS | 100 | Max uploads per tenant+user per window |
RATE_LIMIT_ATTACHMENTS_UPLOAD_DURATION | 60 | Window in seconds |
RATE_LIMIT_ATTACHMENTS_UPLOAD_BLOCK_DURATION | – | Optional block duration after exceeding limit |
AI agent tools:
| Variable | Default | Description |
|---|---|---|
RATE_LIMIT_AI_AGENT_TOOL_POINTS | 30 | Max agent-tool calls per tenant+key (or user) per window |
RATE_LIMIT_AI_AGENT_TOOL_DURATION | 60 | Window in seconds |
RATE_LIMIT_AI_AGENT_TOOL_BLOCK_DURATION | – | Optional block duration after exceeding limit |
Warranty portal attachment uploads and replacements (POST/PUT /api/warranty_claims/portal/attachments) also use RATE_LIMIT_ATTACHMENTS_UPLOAD_{POINTS,DURATION,BLOCK_DURATION}. Their buckets are scoped to the authenticated tenant and customer-user principal, with a separate portal: namespace from staff uploads. The check runs before multipart parsing and OCR; exhausted buckets return HTTP 429 with Retry-After. The existing attachment limiter availability policy applies.
Future:
| Variable | Default | Description |
|---|---|---|
RATE_LIMIT_2FA_VERIFY_POINTS | 5 | Max 2FA verification attempts |
RATE_LIMIT_2FA_VERIFY_DURATION | 300 | Window in seconds |
These variables bound LLM OCR cost amplification in the attachments module. They are not rate-limit keys – they cap page iteration, per-call timeouts, in-process concurrency, and the OCR wait queue.
| Variable | Default | Description |
|---|---|---|
OM_ATTACHMENT_OCR_MAX_PAGES | 50 | Max PDF pages processed for OCR / text extraction |
OM_ATTACHMENT_OCR_PAGE_TIMEOUT_MS | 60000 | Per-page LLM OCR call timeout |
OM_ATTACHMENT_OCR_MAX_OUTPUT_TOKENS | 4096 | Max output tokens per OCR generateText call |
OM_ATTACHMENT_OCR_MAX_CONCURRENCY | 2 | Concurrency of the attachments-ocr queue worker (capped at 20) and of the in-process fallback |
OM_ATTACHMENT_OCR_MAX_WAIT_QUEUE | 50 | Max waiters blocked on the in-process fallback concurrency slot |
LLM OCR runs as a durable job on the attachments-ocr queue (packages/queue), so it survives restarts and is bounded per worker process. Only when the queue cannot accept a job does the upload fall back to the in-process scheduler, whose counters are per replica.
Uses process memory. Suitable for development and single-instance deployments. Counters are lost on app restart.
Uses Redis for distributed rate limiting across multiple application instances. When Redis becomes unavailable, the library automatically falls back to an in-memory insurance limiter (per-instance) to maintain protection.
RATE_LIMIT_STRATEGY=redis
REDIS_URL=redis://localhost:6379
For advanced use cases (resetting counters, adding penalties, custom blocking), resolve the service from DI or use the global singleton:
import { getCachedRateLimiterService } from '@open-mercato/core/bootstrap'
// Or via DI:
const rateLimiterService = container.resolve('rateLimiterService')
Available methods:
| Method | Description |
|---|---|
consume(key, config) | Consume 1 point. Returns { allowed, remainingPoints, msBeforeNext }. |
get(key, config) | Check current state without consuming a point. |
delete(key, config) | Reset the counter for a key (e.g., after successful login). |
penalty(key, points, config) | Add extra penalty points. |
reward(key, points, config) | Return points (reduce consumed count). |
block(key, durationSec, config) | Manually block a key for a duration. |
After a successful login, you may want to reset the rate limit counter so legitimate users aren't locked out after a few typos. The checkAuthRateLimit centralizer returns the compoundKey for this purpose:
import { resetAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'
// After successful auth:
if (compoundKey) {
await resetAuthRateLimit(compoundKey, loginRateLimitConfig)
}
This is a best-effort operation – it never throws and won't fail the request if the counter reset fails.
Option A: Metadata (recommended for IP-based limits)
export const metadata = {
POST: {
rateLimit: {
points: 10,
duration: 60,
keyPrefix: 'my-endpoint',
},
},
}
Option B: Handler-level (for custom keys)
import { getCachedRateLimiterService } from '@open-mercato/core/bootstrap'
import { checkRateLimit, getClientIp, RATE_LIMIT_FALLBACK_KEY } from '@open-mercato/shared/lib/ratelimit/helpers'
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
const myRateLimitConfig = { points: 5, duration: 300, keyPrefix: 'my-action' }
export async function POST(req: Request) {
try {
const rateLimiterService = getCachedRateLimiterService()
if (rateLimiterService) {
const clientIp = getClientIp(req, rateLimiterService.trustProxyDepth)
const { translate } = await resolveTranslations()
const rateLimitError = await checkRateLimit(
rateLimiterService,
myRateLimitConfig,
clientIp ?? RATE_LIMIT_FALLBACK_KEY,
translate('api.errors.rateLimit', 'Too many requests. Please try again later.'),
)
if (rateLimitError) return rateLimitError
}
} catch {
// Fail-open: the request is served when the guard itself fails. Pick the
// posture deliberately — see Choosing a failure posture below.
}
// ... handler logic
}
checkRateLimit takes an optional fifth argument, CheckRateLimitOptions:
| Option | Effect |
|---|---|
failClosed | Return 503 when the limiter could not decide (RateLimitResult.degraded) instead of letting the request through uncounted. Omit it and the call behaves exactly as before – fail-open. |
unavailableMessage | Body message for that 503. Defaults to RATE_LIMIT_UNAVAILABLE_FALLBACK; RATE_LIMIT_UNAVAILABLE_KEY is the matching translation key. |
const rateLimitError = await checkRateLimit(
rateLimiterService,
myRateLimitConfig,
clientIp ?? RATE_LIMIT_FALLBACK_KEY,
translate('api.errors.rateLimit', 'Too many requests. Please try again later.'),
{ failClosed: true },
)
Choose failClosed for state-mutating endpoints where an unenforced limit is worse than a
rejected request – creating payment sessions, verifying a password, anything that costs money or
can be brute-forced. Keep the fail-open default for read-only endpoints, where a limiter
outage must not take the page down.
degraded marks a result whose allowed value is a fallback rather than a real decision. It is
set when an error escapes the limiter itself; it is not set when rate limiting is switched
off by configuration, and under the redis strategy a plain store outage is normally absorbed
one level lower by the in-memory insurance limiter, which keeps counting per process.
Two conditions that look alike are worth keeping apart at the call site: a limiter that is
registered but cannot decide is a transient outage and is what failClosed is for, while a
rateLimiterService that is not registered at all means readRateLimitConfig() rejected the
environment and lasts until an operator fixes it. Reporting the second as "temporarily
unavailable" would take the endpoint down indefinitely, so resolve the service outside the
fail-closed guard and skip the check when it is absent – as
packages/core/src/modules/sales/api/quotes/accept/route.ts and
packages/checkout/src/modules/checkout/lib/rateLimiter.ts both do – logging the
misconfiguration for what it is.
Rate limiting is automatically disabled when OM_INTEGRATION_TEST=true is set in the environment. The ephemeral integration-test runtime (yarn test:integration, yarn test:integration:ephemeral) sets this for you, so test suites do not have to disable limits by hand or flush counters between cases.
When running tests against a long-lived dev server (e.g. yarn dev + npx playwright test), set the flag yourself:
OM_INTEGRATION_TEST=true yarn dev
For suites that deliberately exercise rate-limit behavior, keep the integration flag off and opt in per-request with the targeted auth-endpoint escape hatch:
| Variable | Effect |
|---|---|
OM_TEST_MODE=1 + OM_TEST_AUTH_RATE_LIMIT_MODE=opt-in | checkAuthRateLimit becomes inert by default |
Request header x-om-test-rate-limit: on | Re-enables enforcement for that single request |
This lets you assert both 200 and 429 paths deterministically without tearing the global limiter down.
IP:emailHash layer (caps attempts per account). The email is SHA-256 hashed – raw emails never appear in rate limit storage keys.checkAuthRateLimit centralizer wraps all checks in try/catch and the service allows requests through on unexpected storage errors. State-mutating public endpoints may opt into the opposite posture with checkRateLimit(..., { failClosed: true }), which answers 503 while the limiter cannot decide; POST /api/checkout/pay/[slug]/submit and POST /api/checkout/pay/[slug]/verify-password do, because an unmetered payment-session or password-verification endpoint is worse than a rejected request. The read-only checkout endpoints stay fail-open. AI agent tools (MCP tools/call, POST /api/ai_assistant/tools/execute) fail closed as well: every call runs a paid agent loop, callers are mostly API keys, and in OM_MCP_MUTATION_MODE=approval the agent can queue writes. The AI chat routes stay fail-open. See Choosing a Failure Posture. Missing trusted client IP data is not an infrastructure failure and still consumes a fallback bucket.X-Forwarded-For spoofing prevention: RATE_LIMIT_TRUST_PROXY_DEPTH=0 is the safe default for direct deployments and ignores both X-Forwarded-For and X-Real-IP; the standard route-handler Request does not expose a trustworthy peer socket address. Auth, metadata-driven, and checkout rate limiters therefore use endpoint-scoped global fallback keys, and compound auth keys use global:<identifierHash>. With a positive depth, getClientIp reads the Nth-from-last X-Forwarded-For entry. The configured depth must match the exact trusted proxy chain; a missing or shorter chain falls back globally instead of trusting an attacker-controlled entry. Direct-mode fallback traffic shares each endpoint's configured limit, so deployments behind a trusted proxy should set the exact depth to preserve per-client buckets and avoid unnecessary shared-bucket contention.packages/shared/src/lib/ratelimit/
├── index.ts # Public exports
├── types.ts # TypeScript types (RateLimitConfig, RateLimitResult, etc.)
├── service.ts # RateLimiterService class
├── config.ts # Environment variable reader
├── helpers.ts # checkRateLimit, getClientIp, error constants
└── __tests__/
├── service.test.ts # Service unit tests
└── helpers.test.ts # Helper + config unit tests
packages/core/src/modules/auth/lib/
├── rateLimitCheck.ts # checkAuthRateLimit / resetAuthRateLimit centralizer
├── emailHash.ts # computeEmailHash (SHA-256)
└── __tests__/
└── rateLimitCheck.test.ts # Centralizer unit tests
The service singleton and DI registration live in packages/core/src/bootstrap.ts.
For isolated integration tests that verify real counters, set OM_TEST_MODE=1 and OM_TEST_RATE_LIMIT_MODE=enabled. Integration runs otherwise keep rate limiting disabled. This switch has no effect outside OM_INTEGRATION_TEST; production continues to use RATE_LIMIT_ENABLED.