Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

API rate limiting: Token Bucket, Leaky Bucket, Fixed Window and Sliding Window

Rate limiting controls how quickly a client can perform operations against an API. It is not one algorithm and it is not a complete overload-protection mechanism. Fixed Window, Sliding Window, Token Bucket and Leaky Bucket differ in counting model, burst behavior, memory use and accuracy. A production design must also define who or what is limited, where shared state lives, what HTTP response is returned and how expensive operations are accounted for.

Published Written by Reading time 21 min read
On this page Contents: quick navigation between sections

Rate limiting controls frequency, not total resource safety

Rate limiting defines how often a client can perform an operation within a period. Redis documents limits per user, IP, API key, tenant or other dimensions, while OWASP recommends tuning limits to the specific endpoint and business need. [4][12]

OWASP API4:2023 shows that request-rate limits alone do not solve unrestricted resource consumption. APIs should also bound payload sizes, batched operations, returned records and spending on external providers. [12]

429 Too Many Requests and Retry-After

RFC 6585 defines 429 Too Many Requests for cases where a client has sent too many requests in a given time. The response may include Retry-After to tell the client how long to wait. [1]

RFC 9110 defines Retry-After as either an HTTP-date or a number of delay seconds. [2]

RFC 6585 deliberately does not define how the origin server identifies the user or counts requests. Limits may apply per resource, across a server, across a server set or to different client identities. [1]

Fixed Window: the simplest time counter

Fixed Window divides time into discrete non-overlapping intervals, such as 60 seconds. Each request increments the current counter, and the next window starts with a fresh count. [6]

Redis shows implementations with INCR and EXPIRE. The update should be atomic to avoid cases where a counter increments but expiry is never set. [7][8]

Its main weakness is the boundary burst. Redis notes that traffic at the end of one window and the start of the next can allow close to twice the nominal rate over a short interval. [5][6]

Sliding Window Log: accuracy at a memory cost

Sliding Window Log stores a timestamp for every request in the current moving window. On each request, expired entries are removed and the remaining entries are counted. [6]

Redis classifies it as exact and free from fixed-window boundary bursts, but with O(n) memory because stored entries grow with the number of requests in the active window. [5][6]

It is useful for high-value endpoints or when a precise request trail matters, but can be much more expensive at very high request volume.

Sliding Window Counter: a practical compromise

Sliding Window Counter does not keep every request timestamp. It combines counters from adjacent windows to estimate use over the current moving interval. [6]

Redis describes it as near-exact, with smoother window boundaries and much lower memory use than Sliding Window Log. [5][6]

It is a good general-purpose choice when per-request precision is not required but Fixed Window boundary behavior is too coarse.

Token Bucket: controlled bursts

Token Bucket maintains a bucket with a maximum capacity. Tokens are replenished at a fixed rate and each operation consumes a token. A request is accepted when enough tokens are available. [5]

Accumulated tokens allow a short burst, while the refill rate limits sustained traffic over time. [5]

The token-bucket model has a long history in network traffic control. RFC 2697 and RFC 2698 define token-bucket-based traffic meters, although they are not HTTP rate limiting specifications. [10][11]

Leaky Bucket: policing and shaping are not the same

The term Leaky Bucket is used for more than one behavior. Redis describes a policing variant as exact with no bursts, where traffic beyond the configured rate is rejected. [5][6]

NGINX also describes limit_req as using the leaky bucket method, but by default excess requests inside the configured burst can be delayed to maintain the configured rate. Requests beyond the burst are rejected. [9]

When comparing implementations, check whether excess traffic is rejected immediately or queued and smoothed.

Choosing an algorithm

AlgorithmMemoryAccuracyBurst behaviorBest fit
Fixed Window1 counter per windowApproximate at boundariesBoundary burst possibleSimple API limits
Sliding Window LogO(n) timestampsExactNo boundary burstHigh-value APIs and audit
Sliding Window CounterSmall aggregated countersNear-exactSmoothed boundariesGeneral-purpose APIs
Token BucketSmall bucket stateExact for the modelControlled burstsBursty traffic
Leaky BucketSmall state / queue depending on implementationExact for the modelNone or smoothedSteady-rate enforcement

Redis compares Fixed Window Counter, Sliding Window Log, Sliding Window Counter, Token Bucket and Leaky Bucket across memory, accuracy and burst behavior. [5][6]

Token Bucket fits APIs that should tolerate short bursts. Sliding Window Counter is a broad compromise. Sliding Window Log fits cases where exactness matters more than memory, while Leaky Bucket policing fits strict no-burst enforcement. [5]

What should be limited: IP, user, API key or tenant

Limit keyAdvantageRisk
IPWorks before sign-in and at the edge.NAT can group many users; proxies and botnets evade it.
User / accountProtects one account regardless of source.Requires reliable user identity.
API keyGood for machine-to-machine integrations.A client may have several keys if policy allows it.
Tenant / organizationControls a shared organization budget.One active user may consume quota for others.
Endpoint / operationAllows stricter limits for expensive operations.Does not itself provide fair usage between clients.

Redis notes that quotas can be keyed by user, IP, API key, tenant, model or another dimension. The key determines whether the limit protects an account, integration, organization or the whole service. [4]

OWASP recommends not relying only on IP. For login, its bot-management guidance proposes separate per-username and per-IP limits because a single combined IP+username bucket can allow one source to try the threshold against many usernames. [13]

Distributed proxy networks can also keep per-IP traffic low, so per-IP throttling should be only one layer against credential stuffing. [14]

Distributed rate limiting: local counters are not enough

When an API runs on multiple instances behind a load balancer, process-local counters do not provide one global limit because the same client can hit different instances. Redis documents this limitation directly. [4]

A shared store such as Redis lets all instances make allow/deny decisions against the same state. Atomic operations are important so concurrent requests cannot double-spend tokens or lose counter updates. [4][5][8]

Gateway or application layer

An edge or API-gateway limiter can reject traffic before it reaches expensive services and can apply broad shared policies. An application-level limiter has richer access to authenticated identity, business context and operation cost.

OWASP recommends layered defenses: basic controls at the edge, identity-aware and behavioral limits in the application, and business-level anomaly detection deeper in the system. [13]

A production system can therefore apply multiple simultaneous limits, such as a tenant-wide quota plus a stricter login or report-generation limit.

Not every request should cost one unit

Counting every request as one unit may be insufficient when operations have very different costs. OWASP API4 highlights CPU, memory, storage, batch size, returned records and external-service spending. [12]

The current IETF RateLimit headers draft includes quota units so a policy can express units other than raw request count. The document is still an Internet-Draft, not a published RFC. [3]

A limiter can therefore charge more units for expensive operations if that policy is consistent and documented for clients.

RateLimit headers in 2026: standards status matters

Field / statusMeaning in 2026
429 Too Many RequestsRFC standard: the client sent too many requests in a given time.
Retry-AfterRFC standard: HTTP-date or number of seconds before retry.
RateLimit-PolicyDefined in an active IETF Internet-Draft, not a final RFC.
RateLimitDefined in an active IETF Internet-Draft, not a final RFC.
X-RateLimit-*Commonly deployed, but naming and semantics are inconsistent.

As of May 2026, active Internet-Draft draft-ietf-httpapi-ratelimit-headers-11 defines RateLimit-Policy and RateLimit fields to advertise quota policy and current service limits. [3]

It is still an IETF Internet-Draft and should not be presented as a finalized RFC. [3]

The draft also documents commonly deployed X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset headers and interoperability problems caused by inconsistent names and semantics. [3]

Rate limiting login and abuse

OWASP recommends rate limiting as a foundational control against automation, credential stuffing and abuse, but not as the only defense. [13][14]

For login, consider at least independent per-account and per-IP or source limits. OWASP also highlights MFA, breached-password checks, selective CAPTCHA and anomaly monitoring. [13][14]

Limits should be temporary and risk-aware. Overly aggressive account blocking can itself become a denial-of-service vector against legitimate users.

A practical rate limiter architecture

For one simple API, Fixed Window may be sufficient. A multi-instance API needs shared state or a gateway layer, and state updates should be atomic. [4][7][8]

A sound design defines the algorithm, limit key, quota unit, short- and long-term limits, exceed behavior and client-facing response. Choosing Token Bucket over Sliding Window does not fix poor client identity or an unbounded cost per request. [12][13]

  • Start by identifying the resource you are protecting: CPU, database capacity, third-party API cost, an account or fair usage.
  • Separate limits for cheap and expensive endpoints.
  • Do not rely only on per-IP limits for authenticated users.
  • Use shared state or a gateway in multi-instance systems.
  • Keep read-decide-update atomic.
  • Return 429 when the semantics are too many requests and consider Retry-After.
  • Monitor rejected requests, hot keys and impact on legitimate clients.
  • Test boundary bursts, shared-store failure, clock behavior and recovery after limiter outages.

There is no single best rate limiting algorithm. Fixed Window fits cases where simplicity matters more than precision. Sliding Window Log provides accuracy, Sliding Window Counter a practical compromise, Token Bucket controlled bursts and Leaky Bucket a steady rate. In production, the choice of limit key, atomic shared-state updates, separation of cheap and expensive endpoints and correct client communication through 429 and Retry-After are as important as the algorithm itself.

Rate Limiting API Security Token Bucket Leaky Bucket Fixed Window Sliding Window HTTP 429 Redis API Gateway Distributed Systems

Frequently asked questions

What does HTTP 429 mean?

429 Too Many Requests means the client sent too many requests in a given amount of time. [1]

Should 429 include Retry-After?

RFC 6585 says it may. RFC 9110 defines Retry-After as an HTTP-date or delay in seconds. [1][2]

Which rate limiting algorithm is best?

There is no universal best. Redis documents trade-offs among Fixed Window, Sliding Window, Token Bucket and Leaky Bucket. [5][6]

Why can Fixed Window permit a larger burst?

Requests can arrive just before one window ends and immediately after the next begins, producing a short-term rate above the nominal limit. [5][6]

How do Sliding Window Log and Counter differ?

Log stores every timestamp and is exact with O(n) memory. Counter uses aggregates and is cheaper but approximate. [5][6]

Does Token Bucket always prevent bursts?

No. It intentionally allows controlled bursts by spending previously accumulated tokens. [5]

Does Leaky Bucket always reject excess traffic?

No. A policing variant can reject, while NGINX can delay requests that fit inside the configured burst. [5][9]

Can I rate limit only by IP?

You can, but it should not be the only dimension for many use cases. OWASP documents limitations of per-IP control with proxies, botnets and login abuse. [13][14]

Is Redis required?

No. Redis is one shared-state option. A limiter can also live in a gateway, proxy or another shared service. [4][9]

Is X-RateLimit-Limit an HTTP standard?

No single standardized historical X-RateLimit-* convention exists. The current IETF draft documents inconsistent names and semantics. [3]

Is RateLimit-Policy already an RFC?

No. On November 18, 2026, draft-ietf-httpapi-ratelimit-headers-11 remains an active Internet-Draft. [3]

Does rate limiting stop every DoS attack?

No. OWASP also recommends limits on memory, execution time, payloads, batching and external-service cost, and distributed attacks can evade simple per-IP limits. [12][14]

Sources and references

  1. RFC 6585, Additional HTTP Status Codes - 429 Too Many Requests↩1↩2↩3↩4
  2. RFC 9110, HTTP Semantics - Retry-After↩1↩2
  3. IETF HTTPAPI, draft-ietf-httpapi-ratelimit-headers-11↩1↩2↩3↩4↩5↩6
  4. Redis Docs, Redis rate limiter↩1↩2↩3↩4↩5↩6
  5. Redis Docs, Token bucket rate limiter↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10↩11↩12↩13↩14
  6. Redis, Build 5 Rate Limiters with Redis↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10↩11
  7. Redis Docs, INCR command and rate limiter pattern↩1↩2
  8. Redis, Atomicity with Lua for rate limiting↩1↩2↩3
  9. NGINX, ngx_http_limit_req_module↩1↩2↩3
  10. RFC 2697, A Single Rate Three Color Marker↩
  11. RFC 2698, A Two Rate Three Color Marker↩
  12. OWASP API Security Top 10 2023, API4 Unrestricted Resource Consumption↩1↩2↩3↩4↩5
  13. OWASP Cheat Sheet, Bot Management and Anti-Automation↩1↩2↩3↩4↩5↩6
  14. OWASP Cheat Sheet, Credential Stuffing Prevention↩1↩2↩3↩4↩5

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning