← Blog

Rate Limiting · Redis · Distributed Systems

How Accurate Should a Distributed Rate Limiter Be When the Limiter Itself Can Fail?

Once an API runs on many servers, a rate limiter needs shared state, and that state can be slow, stale or unreachable. This article covers how to decide how accurate a limiter needs to be, and what it should do when its own backend fails.

Aashaya Aryal

December 2, 2023 · 15 min read

Updated November 17, 2026

Empty multi-lane roadway passing beneath a large canopy with concrete barriers positioned across the lanes.

A rate limiter sounds like arithmetic. Allow 100 requests a minute, count them, and when request 101 arrives, return 429 Too Many Requests.

That works well while the application is one process that owns the counter. Then the service scales out behind a load balancer:

Diagram

Client

Load Balancer

API Instance A

API Instance B

API Instance C

Now there's a real question: where does the counter live? If each instance keeps its own, a client with a 100-per-minute limit can get up to 100 × (number of instances) before anything notices. So the counter moves into Redis, which fixes that problem and introduces new ones. Redis gets slow, a replica is stale, a shard fails, one huge tenant turns into a hot key, or a network partition cuts part of the fleet off from the shared state.

That's what makes distributed rate limiting interesting. The code may be a single INCR, but the design is really a consistency and failure policy: how much accuracy you're willing to give up so the thing protecting your availability doesn't become the thing that takes it down.

Local counters stop being enough

Here's a per-tenant limit of 100 requests per second in a single Node.js process:

TS
const counters = new Map<string, { count: number; resetAt: number }>();

function allow(tenantId: string, now = Date.now()): boolean {
  const current = counters.get(tenantId);

  if (!current || now >= current.resetAt) {
    counters.set(tenantId, {
      count: 1,
      resetAt: now + 1_000,
    });

    return true;
  }

  if (current.count >= 100) {
    return false;
  }

  current.count++;
  return true;
}

With one process, the local state is the truth. With three instances behind a load balancer, each one sees only its share of the traffic:

Diagram

One Tenant

Load Balancer

Instance A
counter = 70

Instance B
counter = 62

Instance C
counter = 68

Each instance sees fewer than 100 and allows the request, but globally 200 requests have gone through. The limiter became approximate without anyone deciding that was acceptable. The thing being limited is global, while each observation is local. Shared state fixes that, at the cost of latency, availability and a new failure domain, and those costs are as much a part of the design as the quota.

Sharing the counter in Redis

With Redis, every instance increments the same key:

Diagram

Clients

Load Balancer

API A

API B

API C

Redis
Shared Counter

Redis is a natural fit because INCR is atomic and its documentation for INCR presents rate limiting as a standard pattern. A fixed-window key might be ratelimit:tenant_42:202610022343, expiring at the end of the minute. The obvious implementation is:

TS
const count = await redis.incr(key);

if (count === 1) {
  await redis.expire(key, 60);
}

return count <= limit;

The code is small; the edge cases aren't. If INCR succeeds and the process crashes before EXPIRE runs, the counter never expires, and that tenant is limited far longer than intended. The Redis docs describe this race, which is why the increment and first expiry are usually done together in a Lua script that runs atomically on the server:

LUA
local current = redis.call("INCR", KEYS[1])

if current == 1 then
    redis.call("EXPIRE", KEYS[1], ARGV[1])
end

return current

Newer Redis versions also have INCREX, which increments with optional bounds and expiry in one atomic command. Either way, that solves atomicity on one Redis node. It doesn't say anything about what happens when Redis is stale, unreachable, partitioned or overloaded, which is where most of the interesting decisions are.

Choosing an algorithm

Discussions often start with the algorithm: fixed window, sliding window, token bucket, leaky bucket. I find it more useful to start with what the limiter is protecting, then pick the algorithm that matches.

A fixed window counts requests per calendar interval. It's simple, but bursts around boundaries. With 100 requests a minute, a client can send 100 at 12:00:59 and another 100 at 12:01:00. Both windows are within limits, but the client sent 200 requests in about one second. For billing-plan fairness that's usually fine. If the limiter exists because a database can't absorb 200 requests in one burst, it isn't.

A token bucket separates the sustained rate from the burst size: tokens refill at, say, 100 per second up to a maximum of 150, and each request spends one.

Diagram

token available

empty

Refill Tokens

Token Bucket

Incoming Request

Allow

Reject

Stripe's article on scaling an API with rate limiters describes using token buckets in production, including bursts above the steady rate. That matters because real traffic is rarely smooth. A tenant that's quiet for a while and then sends 40 requests at once may be perfectly well-behaved, and rejecting every short burst hurts usability without protecting anything. The right algorithm is whichever one matches the resource or policy you're actually enforcing.

Rate, concurrency and load are different signals

Request rate is only one kind of pressure. Two endpoints might both get 10 requests per second, but if one takes 10 ms and the other 10 seconds, the first has about 0.1 requests in flight on average and the second has about 100. Same rate, completely different load. (This is Little's law: requests in flight = arrival rate × time each request takes.)

So it helps to keep two limits apart. A rate limit controls how quickly new work enters. A concurrency limit controls how much work is in progress at once. Stripe describes adding a concurrent-request limiter for exactly this reason: their most expensive endpoints suffered resource contention that a requests-per-second limit didn't catch.

Latency changes can make a rate limit unsafe without anyone noticing. Say an operation takes 5 seconds and the service can safely run 20 at once, so a cap of 4 requests per second looks right. If a dependency slows down and the operation now takes 10 seconds, 4 per second means about 40 in flight. The service overloads without the rate limit ever triggering. A concurrency limit of 20 would simply reject or queue request 21. When the protected resource fails because too much work is active at once, concurrency is usually the more direct signal.

There's a third control too. If every tenant stays under quota but database latency triples, the fleet can still be overloaded with nobody misbehaving. Quotas answer "how much may this caller send?" Load shedding answers "how much can the system accept right now?" Stripe uses all three together: request-rate limits, concurrent-request limits, and fleet-wide load shedding that keeps capacity for the most important API calls. A rate limiter is one kind of admission control, not the whole capacity strategy.

When the limiter's backend fails

Every request now depends on Redis. When Redis is unavailable, the limiter has two obvious options. It can fail closed (can't check, so reject) or fail open (can't check, so allow). Neither is right everywhere.

Failing closed preserves enforcement. On a login endpoint, the limiter exists to slow down credential stuffing and brute-force attempts. If Redis disappears and the endpoint allows unlimited attempts, the security protection vanishes exactly when part of the system is unhealthy. Rejecting requests, or falling back to a stricter local limit, may be the right choice, even though it means a Redis outage reduces login availability. What matters is that it's deliberate.

Failing open preserves availability. For a soft fairness quota on an ordinary endpoint, rejecting every request because the limiter is down for 20 seconds would cause a much bigger outage than letting a few clients briefly exceed their quota. Stripe's advice is to catch errors at every level of the limiter so that bugs or a Redis outage fail open and the API keeps working.

So fail-open versus fail-closed is a product and reliability decision, not a Redis setting, and different endpoints can reasonably answer differently:

OperationWhy it's limitedReasonable behaviour if the limiter is down
Login attemptsSecurity, abuseStricter local limit, or fail closed
Password resetSecurity, abuseRestrictive fallback
Public searchFairness, costFail open with a local cap
Report generationExpensive computeLocal concurrency cap, or reject
Health checkAvailabilityUsually skip the limiter
Payment creationProtecting a dependencyDepends on what's being protected
Static metadataFairnessOften fail open

A single catch { return true; } (or return false) in shared middleware throws all of that information away.

Falling back to a local limit

A practical middle ground is to use the shared Redis limiter when it's healthy and a coarse local limit when it isn't:

TS
async function allowRequest(key: string): Promise<boolean> {
  try {
    return await distributedLimiter.allow(key);
  } catch {
    return localEmergencyLimiter.allow(key);
  }
}

If ten instances each fall back to 20 requests per second, the fleet might briefly allow around 200 per second instead of the intended global limit. That's inaccurate, but far safer than unlimited traffic or no traffic. The system has consciously traded precision for availability.

The goal in degraded mode isn't to reproduce the exact quota. It's to protect the reason the quota exists. For fairness, a temporary 10–20% overshoot may be fine. If the limit protects a database from collapse, the local fallback has to stay conservative enough to protect it with no coordination at all. If it's a security boundary, approximation may not be acceptable.

Exact global limits need global coordination

Now spread the API across Virginia, Oregon, Frankfurt, Tokyo and Sydney, and give one tenant a global quota of 1,000 requests per second. To enforce that exactly, every region needs a fresh view of what every other region has admitted.

Diagram

US API

EU API

Asia API

Global Limiter State

That buys accuracy at the cost of extra latency on every request, a cross-region dependency, and a bigger blast radius: if the shared state is unreachable, regions that were otherwise independent fail together. The limiter has become a global failure domain. That can be justified for a hard security or correctness rule. For an ordinary fairness policy it's usually too high a price. The more global the truth has to be, the more coordination you have to pay for.

When approximate is good enough

Cloudflare ran into this building rate limiting for millions of domains. Purely local counters were too inaccurate, because requests from one client land on different machines. Centralising every counter globally would have added too much coordination and latency. They counted within each data centre instead, using an approximate sliding-window algorithm. Measured over 400 million requests from 270,000 sources, 0.003% of requests were wrongly allowed or wrongly limited.

That's a good illustration of a broader point: a limiter that's slightly approximate but fast, local and available can be better than an exact one that adds a fragile distributed dependency to every request. The useful questions aren't "is it exact?" but "how often is it wrong, in which direction, and what does that cost?"

An approximate limiter makes two kinds of mistakes. A false allow admits a request that should have been rejected. A false reject turns away a request that should have been admitted. For a soft fairness quota, false allows are nearly harmless and false rejects annoy customers. For brute-force protection it's the other way round.

The same 5% error can be irrelevant or serious. Allowing 105 requests a second against a free-tier limit of 100 probably doesn't matter. Allowing 105 concurrent operations against a dependency that becomes unstable above 100 might. That's why fairness quotas and hard capacity limits shouldn't automatically share the same consistency design. How accurate a limit needs to be is a product requirement, and they don't all need the same one.

Regional budgets

One way to avoid coordinating every request globally is to split the global budget into regional allocations. A 1,000 requests-per-second quota might become 400 for the US, 250 for Europe, 250 for Asia and 100 for everywhere else.

Diagram

Global Budget
1000/s

US
400/s

EU
250/s

Asia
250/s

Other
100/s

Each region decides locally, which improves latency, independence and tolerance of network partitions. The cost is utilisation: if US traffic needs 700 while Asia uses 20, capacity sits unused in a quiet region while another rejects useful traffic. You can rebalance budgets periodically, which reintroduces coordination, but on a slow control-plane timescale rather than on every request. That's usually a much better place to pay for coordination.

Replicas, shards and hot keys

A Redis-backed limiter can be atomic on each node and still inconsistent overall. GitHub's write-up on scaling its API rate limiter with sharded, replicated Redis has a good example. They sharded in the application, wrote to primaries, read from replicas, and used Lua for atomic updates. Then clients started reporting rejected requests with X-RateLimit-Remaining: 5000 in the response.

The cause: the first check read from a replica, which still held the previous window's counter and said the client was over the limit. The response headers were then built from an increment on the primary, which had expired the old window and started a fresh one. Redis replicas don't expire keys on their own; they wait for the primary to tell them. So the decision and its explanation came from two different views of the state. A second bug made the X-RateLimit-Reset header "wobble" by a second between requests, because a TTL was read in Lua and then added to the current time in application code, with time passing in between.

The general lesson: atomicity on one node doesn't make the whole limiter consistent, and if a decision and the explanation of that decision have to agree, they should come from the same snapshot of state.

Sharding brings another problem. If most tenants send 10 requests a second and one sends 100,000, every decision for that tenant touches the same key, and so the same shard.

Diagram

Tenant A

Tenant B

Tenant C

Huge Tenant

Redis Shard 1

Redis Shard 2

Redis Shard 3

Cluster-wide CPU can look fine while shard 2 is saturated. It's the same lesson as in Cassandra, caches and Kafka: spreading keys evenly doesn't mean the work is spread evenly.

Sharding also complicates limits with several dimensions. If a request has to pass a per-user limit, a per-tenant limit and a global load limit, those counters may live on different shards, and one Lua script can't update keys across independent shards atomically. The usual answer is to stop trying to make it one transaction and run the checks as separate stages, each with its own scope, consistency and failure policy:

Diagram

Request

User Limiter

Tenant Limiter

Global Load Shedder

Application

Who is being limited, and by how much

A limit only means something once you've decided whose budget a request spends. Each key choice is a different policy:

  • IP address catches anonymous abuse but can unfairly punish offices, universities and mobile carriers where many people share one public address.
  • User ID needs authentication to happen before the limiter can identify anyone.
  • API key suits developer APIs, but one leaked key can use up the whole account's budget.
  • Tenant ID protects fairness between customers, but one user inside a tenant can still use up the tenant's allowance.

Many systems end up with several layers: coarse IP protection, a per-user or per-account quota, a per-tenant quota, and endpoint-specific safety limits.

Requests also don't all cost the same. GET /profile might be 1 ms of CPU and one indexed read. POST /reports/export might be 2 seconds of CPU and millions of rows scanned. If both spend one token, the limiter pretends they cost the same. Weighted accounting fixes that (profile = 1 token, search = 3, export = 50):

TS
await limiter.consume({
  key: tenantId,
  cost: endpointCost,
});

That works if you have a credible model of cost. For very expensive operations, a plain concurrency limit is often simpler and closer to the resource you're protecting.

What the client does after a 429

Returning 429 isn't the end of the design. The client needs to know what to do next:

HTTP
HTTP/1.1 429 Too Many Requests
Retry-After: 8

If clients respond by retrying immediately, over and over, the rate limiter becomes the source of a retry storm. And if 10,000 clients all receive Retry-After: 10 and all retry at exactly 10 seconds, the burst has just moved ten seconds into the future. Clients should add jitter (random variation) around the suggested delay. Rate limiting works best as a feedback loop: a clear rejection, guidance on when to come back, and clients that back off with jitter. A well-designed limiter can still be undone by badly behaved client retries. (I go into this more in When do retries stop improving reliability?)

Observing the limiter

A limiter that sits in front of every request is production infrastructure and deserves its own telemetry:

  • checks, allows and rejections
  • backend errors and fallback decisions
  • limiter latency

Broken down by limiter type, endpoint, tenant class and region.

During a Redis incident, you'd like the dashboard to show something like "Redis errors 18%, local fallback decisions 18%, API availability 99.9%". That tells operators the limiter is degraded and the API isn't, which is much better than discovering Redis is down because the whole API went down.

If the design deliberately allows approximate decisions, measure how far they drift from ideal behaviour, and track false allows and false rejects separately, since they cost different things depending on what the limit is for.

Putting it together

Before choosing an algorithm, I'd want answers to these:

  • What resource or policy is this protecting?
  • What happens if it allows too much? What if it rejects too much?
  • How global does the limit really need to be, and how much burst is fine?
  • What happens if the state store fails, and can enforcement be approximate?
  • Do we need to limit rate, concurrency, or current fleet load?

Three limits all called "rate limits" can have very different answers. A free-tier quota of 1,000 requests a day that occasionally allows 1,004 doesn't matter. A cap of 100 concurrent exports that occasionally allows 300 might take down a database. A login control of 5 failed attempts a minute that allows 100 when Redis is down has lost its whole point. A token bucket is a way to implement a policy; it isn't the policy.

For a multi-tenant API, I'd think of admission control as a series of stages, each answering its own question:

Diagram

Request

Coarse IP Abuse Limit

Authenticate

Per-User Limit

Per-Tenant Redis Token Bucket

Expensive Endpoint
Concurrency Limit

Fleet Load Shedder

Business Logic

The IP limit asks whether the source is obviously abusive. The user limit asks whether this principal is behaving reasonably. The tenant limit asks whether one customer is monopolising shared capacity. The concurrency limit asks whether an expensive operation can safely start. The load shedder asks whether the fleet can take this work right now. Not every request needs every stage.

The degraded behaviour belongs right next to each policy, in code, rather than in someone's memory:

TS
type RateLimitMode = "normal" | "degraded-local" | "fail-closed";

async function checkLimit(request: RequestContext): Promise<RateLimitDecision> {
  const policy = policies.forEndpoint(request.route);

  try {
    return await distributedLimiter.check({
      key: policy.key(request),
      limit: policy.limit,
      cost: policy.cost(request),
    });
  } catch (error) {
    metrics.rateLimiterBackendError.inc();

    switch (policy.failureMode) {
      case "fail-open":
        return {
          allowed: true,
          mode: "degraded-local",
        };

      case "local-fallback":
        return localLimiter.check(policy.key(request), policy.localLimit);

      case "fail-closed":
        return {
          allowed: false,
          mode: "fail-closed",
        };
    }
  }
}

Finally, the limiter should have a smaller blast radius than the system it protects. If GET /health takes 1 ms and checking a distant global Redis cluster adds 25 ms, the check costs 25 times more than the operation. If five independent regions all depend synchronously on one global Redis cluster for every request, five failure domains have become one. Cloudflare's local counting, regional budgets and local fallbacks all make the same trade: accept some approximation so failures stay contained.

Sometimes "technically wrong" is operationally better. If two regions briefly disagree and two extra requests get through, but the service stays up, latency stays low, the protected dependency stays healthy and the customer notices nothing, that's often a better outcome than a perfectly accurate global counter that blocks every request during a network partition. Which one is "correct" depends on what the limit protects. Much of distributed systems work is deciding which kind of wrong you can safely tolerate.

Key takeaways

  • Decide what each limit protects (fairness, a fragile dependency, security) before choosing an algorithm or a consistency model.
  • Make increment and expiry atomic, and derive a decision and its response headers from the same read of state.
  • Use concurrency limits for expensive work and load shedding for fleet-wide overload; request rate alone misses both.
  • Give every limit an explicit behaviour for when its backend is down: fail open, fail closed, or a conservative local fallback.
  • Accept bounded approximation (local counting, regional budgets) where the cost of being slightly wrong is low, and measure false allows and false rejects.
  • Keep the limiter's blast radius smaller than the system it protects, and give it its own metrics.

References