Open MercatoDocsSearch docsAPI reference

Framework

Rate Limiting

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.

Quick Start

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

How It Works

Enforcement Paths

Open Mercato supports three complementary ways to enforce rate limits:

1. Metadata-Driven (Automatic)

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.

2. Admission Before Authentication

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.

3. Handler-Level (Manual)

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.

When to Use Which

ApproachKey StrategyUse Case
Metadata-drivenClient IP onlyGeneral API endpoints, simple abuse prevention
Handler-levelCustom (IP+email, token, etc.)Auth endpoints, credential stuffing protection

Protected Endpoints

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):

EndpointKeyPointsWindowBlock
POST /api/loginIP2060s60s
POST /api/resetIP1060s60s
POST /api/reset/confirmIP5300s –
POST /api/auth/reset/validateIP10300s –

Layer 2 – Compound caps attempts per IP + account pair (email is SHA-256 hashed):

EndpointKeyPointsWindowBlock
POST /api/loginIP:emailHash560s60s
POST /api/resetIP:emailHash360s60s

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):

EndpointKeyPointsWindowBlock
POST /api/attachmentstenantId:principal3060s –

AI agent tools (one bucket for every agent tool, per tenant + API key, or per user for session-token callers):

EndpointKeyPointsWindowBlock
MCP tools/call and POST /api/ai_assistant/tools/executetenant:key:<apiKeyId> / tenant:user:<userId>3060s –

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).

429 Response Format

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.

HeaderDescription
Retry-AfterSeconds until the client can retry
X-RateLimit-LimitMaximum points allowed in the window
X-RateLimit-RemainingPoints remaining (always 0 on 429)
X-RateLimit-ResetSeconds until the window resets

503 Response Format (fail-closed endpoints)

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.

Configuration

Global Settings

VariableDefaultDescription
RATE_LIMIT_ENABLEDtrueMaster switch. Set to false to disable all rate limiting.
RATE_LIMIT_STRATEGYmemoryBackend: memory (single instance) or redis (distributed).
RATE_LIMIT_KEY_PREFIXrlKey prefix in storage. Prevents collisions with other Redis data.
RATE_LIMIT_TRUST_PROXY_DEPTH0Number 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).

Per-Endpoint Overrides

Compound layer (IP + hashed email):

VariableDefaultDescription
RATE_LIMIT_LOGIN_POINTS5Max login attempts per IP+account per window
RATE_LIMIT_LOGIN_DURATION60Window in seconds
RATE_LIMIT_LOGIN_BLOCK_DURATION60Block duration after exceeding limit
RATE_LIMIT_RESET_POINTS3Max password reset requests per IP+account per window
RATE_LIMIT_RESET_DURATION60Window in seconds
RATE_LIMIT_RESET_BLOCK_DURATION60Block duration after exceeding limit

IP-only layer:

VariableDefaultDescription
RATE_LIMIT_LOGIN_IP_POINTS20Max total login attempts per IP per window
RATE_LIMIT_LOGIN_IP_DURATION60Window in seconds
RATE_LIMIT_LOGIN_IP_BLOCK_DURATION60Block duration after exceeding IP limit
RATE_LIMIT_RESET_IP_POINTS10Max total reset requests per IP per window
RATE_LIMIT_RESET_IP_DURATION60Window in seconds
RATE_LIMIT_RESET_IP_BLOCK_DURATION60Block duration after exceeding IP limit
RATE_LIMIT_RESET_CONFIRM_POINTS5Max reset confirm attempts per IP per window
RATE_LIMIT_RESET_CONFIRM_DURATION300Window in seconds
RATE_LIMIT_RESET_VALIDATE_POINTS10Max reset-token checks per IP per window
RATE_LIMIT_RESET_VALIDATE_DURATION300Window in seconds

Attachment uploads:

VariableDefaultDescription
RATE_LIMIT_ATTACHMENTS_UPLOAD_POINTS100Max uploads per tenant+user per window
RATE_LIMIT_ATTACHMENTS_UPLOAD_DURATION60Window in seconds
RATE_LIMIT_ATTACHMENTS_UPLOAD_BLOCK_DURATION – Optional block duration after exceeding limit

AI agent tools:

VariableDefaultDescription
RATE_LIMIT_AI_AGENT_TOOL_POINTS30Max agent-tool calls per tenant+key (or user) per window
RATE_LIMIT_AI_AGENT_TOOL_DURATION60Window 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:

VariableDefaultDescription
RATE_LIMIT_2FA_VERIFY_POINTS5Max 2FA verification attempts
RATE_LIMIT_2FA_VERIFY_DURATION300Window in seconds

Attachment OCR resource bounds

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.

VariableDefaultDescription
OM_ATTACHMENT_OCR_MAX_PAGES50Max PDF pages processed for OCR / text extraction
OM_ATTACHMENT_OCR_PAGE_TIMEOUT_MS60000Per-page LLM OCR call timeout
OM_ATTACHMENT_OCR_MAX_OUTPUT_TOKENS4096Max output tokens per OCR generateText call
OM_ATTACHMENT_OCR_MAX_CONCURRENCY2Concurrency of the attachments-ocr queue worker (capped at 20) and of the in-process fallback
OM_ATTACHMENT_OCR_MAX_WAIT_QUEUE50Max 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.

Strategies

Memory (Default)

Uses process memory. Suitable for development and single-instance deployments. Counters are lost on app restart.

Redis

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

Advanced Usage

Direct Service Access

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:

MethodDescription
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.

Reset Counter on Success

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.

Adding Rate Limiting to a New Endpoint

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
}

Choosing a Failure Posture

checkRateLimit takes an optional fifth argument, CheckRateLimitOptions:

OptionEffect
failClosedReturn 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.
unavailableMessageBody 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.

Testing

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:

VariableEffect
OM_TEST_MODE=1 + OM_TEST_AUTH_RATE_LIMIT_MODE=opt-incheckAuthRateLimit becomes inert by default
Request header x-om-test-rate-limit: onRe-enables enforcement for that single request

This lets you assert both 200 and 429 paths deterministically without tearing the global limiter down.

Security Notes

File Layout

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.

Previous: Cross-Site Login Protection · Next: Webhooks