Quick answer
Rate-limit the resource an endpoint can exhaust: database work, external API quota, CPU, bandwidth, mail delivery, or job capacity. Choose a key that reflects the requester or tenant and enforce it atomically across serving instances. A per-process counter may demonstrate an algorithm, but cannot enforce a shared production limit across multiple workers or serverless invocations.
Combine request frequency with input bounds, concurrency limits, and cost-aware controls. Ten inexpensive reads and ten large exports are not equivalent. Return a clear 429 when a client quota is exceeded, provide a meaningful Retry-After when possible, and define what happens if the limiter store itself is unavailable.
Practical implementation steps
Identify expensive operations
List work before and after authentication: login attempts, file uploads, searches, exports, and calls to paid providers. Bound body size, page size, filter complexity, and execution time before expensive work. Use a route-specific cost model when one request can select many items. A global requests-per-minute number cannot express every workload's resource demand.
Design identity and scope
Use authenticated user or tenant keys for account quotas, while applying separate pre-authentication abuse controls where needed. IP limits can group users behind shared networks and can be unreliable behind proxies. Trust forwarding headers only from a known proxy path that overwrites attacker-supplied values. Do not let a client choose its own quota key or claim a different tenant.
Enforce atomically and share state
A check followed by a separate increment races under concurrency. Use a store operation or transaction that consumes capacity atomically. Define expiry and key cardinality to avoid unbounded limiter storage. If a database-backed limiter uses locks, evaluate contention and ensure the limiter does not become the very resource bottleneck it is meant to protect.
Specify outage and retry behavior
Fail-open preserves availability but can expose costly operations during an outage; fail-closed protects resources but can reject legitimate clients. Decide per operation and monitor the fallback. Keep client retries bounded with jitter, and avoid encouraging every rejected client to retry at the exact same instant. Concurrency limits need release in finally paths and a recovery mechanism for abandoned work.
Implementation example
This helper formats a rejection after a real limiter has made its decision. It does not implement a distributed limiter. Pass the next permitted time from the authoritative store rather than estimating from an unrelated local counter.
export function quotaExceeded(retryAtMs: number, nowMs = Date.now()): Response {
if (!Number.isFinite(retryAtMs)) throw new Error("Invalid retry time");
const seconds = Math.max(1, Math.ceil((retryAtMs - nowMs) / 1000));
return Response.json(
{ code: "RATE_LIMITED", message: "Please retry later" },
{
status: 429,
headers: {
"Retry-After": String(seconds),
"Cache-Control": "no-store",
},
},
);
}
Use 429 for request quota rejection rather than disguising it as a successful empty result. A service-wide outage may need a different status. Keep quota details free of other users' identifiers, and give the UI a useful disabled or retry state. Record rejected operation categories without logging credentials or full submitted payloads.
Tradeoffs and alternatives
Fixed windows are easy to explain but permit boundary bursts. Sliding approaches can smooth those bursts at greater storage or computation cost. Token-style capacity supports controlled bursts but needs careful atomic accounting. None replaces concurrency or payload limits. Pick the algorithm from the resource contract and verify it under simultaneous requests.
Common mistakes
- Using memory counters as a shared limit across instances.
- Trusting arbitrary X-Forwarded-For values.
- Applying one cheap-read quota to expensive exports.
- Separating capacity checks and increments.
- Leaving outage behavior and abandoned concurrency slots undefined.
Production checklist
- Expensive resources and operation costs are identified.
- Requester identity is derived from trusted state.
- Shared limits are consumed atomically.
- Payload, concurrency, and timeout bounds complement quotas.
- Limiter-store outage policy is documented and observable.
- 429 responses and bounded client retries are tested.
FAQ
Is rate limiting sufficient against abuse?
No. Authentication, ownership checks, input bounds, timeouts, and operation-specific abuse controls remain necessary. A permitted request can still be unauthorized or too expensive.
Should every rejected request receive the same delay?
Base the delay on the limiter contract. Distinguish a short burst limit from a daily quota or disabled account. Do not promise a retry time you cannot actually honor.
Conclusion
Protect the actual bottleneck with scoped, atomic accounting and complementary resource bounds. Verify concurrency and outage behavior, then make client rejection explicit and recoverable. A requests-per-minute counter is only one part of that design.
Primary sources
Related guides and examples
Need this implemented in a real product?
One connected implementation across the interface, application logic, APIs, and data layer.