A glowing gateway filters data packets bound for linked cloud servers.
Filtering requests before they reach cloud servers

How to Add API Rate Limiting to a SaaS API

To add API rate limiting, identify each caller, track requests against a defined allowance, and reject excess traffic with HTTP 429. When your API runs across multiple instances, use a shared store such as Redis so every server enforces the same limit.

For a SaaS product, the main decisions involve who shares the allowance and what happens when it runs out. Start with those rules, then implement the counter, response behavior, and tests.

Key Takeaways

  • Choose an algorithm based on acceptable bursts and enforcement accuracy.
  • Derive limits from authenticated API keys, users, or tenants, never an untrusted request field.
  • Share counters across instances and update them atomically.
  • Return useful retry guidance, then monitor rejected requests and limiter failures separately.

Choose Your API Rate Limiting Algorithm

A rate limiter needs a clear rule for counting requests over time. Different algorithms trade simplicity against burst control and storage overhead.

Use these differences to choose an approach.

AlgorithmHow it worksMain trade-off
Fixed windowCounts requests within a fixed-duration intervalSimple, but permits bursts near boundaries
Sliding-window logStores timestamps within a rolling intervalPrecise, with more per-request storage
Sliding-window counterCombines recent window countsLower storage, but approximate
Token bucketRefills tokens up to a defined capacitySupports controlled bursts and an average rate

Redis’s rate limiter documentation explains these approaches and their implementation patterns.

For customer-facing APIs, token buckets are useful when legitimate integrations send short batches. A sliding-window log fits requirements that need an exact rolling count.

A fixed window is easier to implement and explain, so we’ll use it below. Its limitation matters: a caller can consume one allowance immediately before a window ends and another immediately afterward.

A vector illustration showing a data flow diagram with request dots passing through a gateway.

The example starts each caller’s window with its first accepted request. It doesn’t align everyone to wall-clock minute boundaries.

Define Who Shares Each Allowance

Choose API-key, user, or tenant scope

Authenticate the request before selecting its customer-facing limiter identity. For API-key authentication, use the database record’s internal key ID rather than storing the secret itself.

For session-based access, use the authenticated user ID. However, per-user limits alone let a tenant increase throughput by creating more users.

Similarly, separate API keys shouldn’t multiply an account-wide allowance. Apply an additional tenant-level limiter when the organization must share capacity.

Use an identity structure such as tenantId:apiKeyId:policyId. All components should come from trusted server-side records.

Separate traffic protection from commercial quotas

A short-window request limit protects capacity. A monthly usage allowance determines what a customer may consume or pay for. Keep those decisions separate.

Resolve policy values centrally rather than scattering plan-name checks throughout route handlers. Stable identifiers such as api_requests survive pricing changes better than names tied to a subscription tier.

Define whether contract overrides take priority over plan defaults. Also record the winning policy source so support can explain unexpected limits.

Give expensive exports or AI operations separate protection when their resource costs differ substantially from ordinary reads.

Share Limits Across API Instances

An in-memory counter belongs to one process. Adding another API instance creates another independent allowance unless both instances consult shared state.

A vector diagram showing three application servers connected to a shared database.

Make the decision atomic

Store limiter state in Redis and perform the read, admission decision, and update in one Lua script.

Separate application-side commands create races. Two servers can both read the same remaining capacity and admit requests that collectively exceed it.

Redis executes a Lua script without interleaving other commands. Its distributed token bucket example demonstrates the same shared-state approach with Go.

Keep scripts short because their execution blocks other Redis commands. Also expire inactive limiter keys so abandoned credentials don’t leave counters behind.

Define dependency-failure behavior

Decide what happens if Redis becomes unavailable.

For expensive operations, rejecting work may be safer than admitting unlimited traffic. For less costly endpoints, temporary admission may be an acceptable availability trade-off.

Distinguish an unavailable limiter from an exhausted allowance. A dependency failure should follow your service-unavailable path, not produce a misleading 429.

Set bounded Redis connection and command behavior. Atomic scripts also don’t eliminate persistence, failover, or regional network considerations.

Implement a Redis-Backed Express Limiter

Install the client with npm install redis. This example uses ES modules in an existing Express application.

Run authentication and server-side policy resolution first. Populate req.auth with internal identifiers and req.ratePolicy with a stable id, positive integer limit, and positive integer windowMs.

import { createClient } from "redis";


const redis = createClient({ url: process.env.REDIS_URL });
redis.on("error", console.error);
await redis.connect();


const script = `
local count = tonumber(redis.call("GET", KEYS[1]) or "0")
if count >= tonumber(ARGV[1]) then
  return {0, redis.call("PTTL", KEYS[1])}
end
count = redis.call("INCR", KEYS[1])
if count == 1 then
  redis.call("PEXPIRE", KEYS[1], ARGV[2])
end
return {1, redis.call("PTTL", KEYS[1])}
`;


app.use(async (req, res, next) => {
  try {
    const { tenantId, apiKeyId } = req.auth;
    const { id, limit, windowMs } = req.ratePolicy;
    const [allowed, ttl] = await redis.eval(script, {
      keys: [`rl:${tenantId}:${apiKeyId}:${id}`],
      arguments: [String(limit), String(windowMs)]
    });


    if (allowed) return next();


    res.set("Retry-After", String(Math.max(1, Math.ceil(ttl / 1000))));
    res.set("Cache-Control", "no-store");
    return res.status(429).json({ error: "rate_limit_exceeded" });
  } catch (error) {
    next(error);
  }
});

limit controls admitted requests, while windowMs controls the interval’s duration. The script starts expiration on the first admitted request; rejected attempts don’t extend the window.

Mount this middleware before expensive business handlers, limited to the protected routes. Map Redis failures to HTTP 503 in your error handler.

Use a separate namespace for each policy. This implementation assumes limiter keys retain their expiration and aren’t written by unrelated code.

Return HTTP 429 With Useful Retry Guidance

Explain why the request stopped

RFC 6585 defines HTTP 429 for excessive requests within a period. Return a stable error code so integrations can distinguish throttling from authentication or validation errors.

Your documentation should identify the allowance’s scope and the behavior of rejected requests. In this implementation, rejected requests never reach business handlers and don’t increment the admitted-request counter.

For layered policies, identify which policy blocked the request without exposing credentials or another tenant’s usage.

Calculate Retry-After from actual state

The example converts Redis’s remaining expiration into whole seconds, rounding upward. That produces a non-negative delay clients can use.

As MDN’s 429 response reference explains, a response can include Retry-After; the header isn’t mandatory for every 429. Including it makes your API easier to integrate.

Clients should honor that delay, then use bounded retries with jitter. Otherwise, many integrations can resume simultaneously.

A retry delay is a minimum wait, not a reservation. Another request may consume the available allowance before the retry arrives.

For background integrations, persist the next attempt time rather than relying on a sleeping worker.

Test and Monitor the Implementation

Test boundaries, isolation, and concurrent requests

Use an isolated Redis database and a deliberately small test allowance. Exercise the middleware through HTTP so tests cover authentication, headers, and routing.

  1. Send requests up to the configured allowance, then assert the next request returns 429.
  2. Assert Retry-After reflects the remaining window and rejected requests don’t extend it.
  3. Wait for expiration and assert a request succeeds again.
  4. Send simultaneous requests through multiple API instances and assert their combined admissions respect the allowance.
  5. Use different tenant and key identities to test isolation, including tenant-wide limits shared by multiple keys.
  6. Interrupt Redis connectivity and assert the documented failure behavior.

Also test traffic immediately before and after expiration. This exposes the boundary burst inherent in fixed-window enforcement.

If writes can be retried after uncertain responses, test idempotency separately. A timeout can happen after a business operation commits.

Monitor customer impact and limiter health

Track admitted requests, 429 responses, limiter latency, and Redis errors. Separate those measurements by route group and policy where practical.

Keep tenant-level detail in access-controlled logs rather than creating an unbounded metrics label for every customer.

Record correlation IDs and internal tenant identifiers, but exclude API secrets and sensitive payloads. Support should be able to identify the blocking policy and explain its allowance.

Before enforcing a new policy, run it in observation mode. Record would-be rejections without blocking traffic, then compare them with legitimate integration workloads.

Alert on sudden changes in rejection rates and dependency failures. A spike after a connector deployment may indicate a retry loop rather than customer growth.

Frequently Asked Questions

Can rate limiting protect unauthenticated endpoints?

Yes. Apply a separate, coarse IP-based limiter before expensive authentication work. For login or recovery endpoints, combine network-level protection with endpoint-specific controls.

Configure trusted proxies carefully so clients can’t spoof their apparent address. Avoid treating an IP address as a customer identity because unrelated users can share one.

Does rate limiting control simultaneous requests?

A request-rate limit controls admissions over time. A concurrency limit controls work running at the same moment.

Slow exports can exhaust workers even when the request rate remains acceptable. Use a concurrency guard or bounded job queue for those operations alongside rate limiting.

Build a Limit Customers Can Understand

Reliable API rate limiting combines trusted identity, atomic enforcement, and predictable recovery. A counter only works when every API instance shares the same policy and state.

Start with one protected route group and test concurrent traffic before expanding enforcement. Keep retry behavior explicit so customers can recover without adding unnecessary load.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *