Skip to content

Rate Limiting: Token Bucket, Leaky Bucket, Windows, Distributed Limits ​

"The 429 status code indicates that the user has sent too many requests in a given amount of time ("rate limiting")." — Mark Nottingham and Roy T. Fielding, RFC 6585: Additional HTTP Status Codes, section 4, April 2012

Summary: A rate limiter answers one question per request, "may this caller do this now?", by remembering a small amount of state per key (a token count, a timestamp or a counter) and comparing it with a policy such as "100 per minute, bursts of 20". Focus: Token bucket, leaky bucket as a queue and as a meter (GCRA), fixed window and its boundary burst, sliding window log and sliding window counter, hierarchical limits, keys (user, API key, IP behind NAT/CGNAT, tenant, endpoint), distributed limiting with Redis and Lua, local buckets with sync and cell-based designs, fail-open vs fail-closed, 429 / Retry-After / RateLimit fields / 503, client backoff, NGINX, Envoy, Cloudflare, AWS API Gateway, Kong, Laravel and Go code, and fake-clock testing. Learning goal: Pick the algorithm, key and enforcement layer for any endpoint and say what burst it allows; implement it so it stays correct across many instances and when Redis is down; return responses a client can act on; and prove the behaviour with tests that never sleep.

This chapter sits in the Traffic & Scale group after Load Balancing. It owns the algorithms, the numbers and the system-level decision. Neighbours keep their depth: Load Shedding decides what to drop when the whole system is overloaded (a rate limiter decides per caller); Backpressure & Flow Control slows producers inside a pipeline; Timeouts, Retries & Jitter owns the client retry policy; NAT, PAT & Port Forwarding; CGNAT explains why many people share one IP; Redis teaches the data structures; Write Buffering & Sharded Counters owns hot-counter sharding; API Gateway, BFF & Service Mesh owns the gateway itself; DDoS Protection owns volumetric attacks, which a request limiter cannot stop on its own.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why limit at all; limit vs shedding vs backpressure vs quotaWhy it exists
Telecom roots, RFC 6585, Stripe, Cloudflare, the IETF draftWhere it comes from
Token bucket, burst, refill rate, lazy refillToken bucket
Leaky bucket as a queue (NGINX) and as a meterLeaky bucket, GCRA
Fixed window and the window boundary burstFixed window
Sliding window log and sliding window counterSliding log, Sliding counter
Global, tenant, user and endpoint limits togetherHierarchical limits
Per-user, per-API-key, per-IP, NAT/CGNAT, per-tenantKeys
In-flight limits, GraphQL points, monthly quotasConcurrency, Cost-based, Quotas
Redis, Lua, INCR + EXPIRE, Redis Cell, local sync, cellsDistributed limiting
Fail-open or fail-closedWhen the limiter fails
429, Retry-After, RateLimit-Policy, RateLimit, 503Responses
Backoff with jitter, honouring headersClient behaviour
Edge vs gateway vs service; NGINX, Envoy, Cloudflare, AWS, KongWhere to enforce
Fake clocks and deterministic testsTesting
Formulas, memory, knobs, error messagesMechanics
CodeGo, Laravel
Ten classic failures and their fixesSolving the classic problems
Which algorithm, key and layerChoosing
From a monolith to many regionsIn architecture
Runnable simulation and expected experimentsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The algorithms. All of them below are set to mean "100 requests per minute". The last column is the number of requests each admitted when a client sent 100 at 12:00:59.9 and 100 more at 12:01:00.1 (measured with this chapter's simulation).

AlgorithmIn plain wordsState per keyBurst behaviourBoundary test (of 200)
Fixed windowCount per calendar minute, reset at :001 counterUp to 2x the limit across a reset200
Sliding window logRemember every request time; count the last 60 s1 timestamp per requestExact, never more than the limit in any 60 s100
Sliding window counterTwo counters, weight the previous one by how much of it still overlaps2 countersClose to exact (Cloudflare measured 6% average error)100
Token bucketTokens drip in at rate r up to b; each request takes oneToken count + last timeBursts of up to b, then rate r100
Leaky bucket (queue)Requests wait in a FIFO and leave at rate rQueueSmooths output; adds delay; rejects when the queue is fulln/a (delays instead)
GCRA (leaky bucket as meter)Remember when the next request is "due"1 timestampSame decisions as a token bucket100

The keys.

KeyGood forBreaks when
Per-API-keyPublic APIs, partner integrationsKeys leak or are shared; one key for many end users
Per-userLogged-in product trafficAnonymous endpoints (login, sign-up)
Per-tenantB2B SaaS plans, fairness between customersOne tenant has one abusive user (add a per-user tier)
Per-IPAnonymous traffic, login brute force, edge filteringNAT, CGNAT, corporate proxies, mobile networks, IPv6 rotation
Per-endpointExpensive routes (exports, search, GraphQL)Used alone: callers spread load over endpoints
GlobalProtecting a downstream with fixed capacityUsed alone: one caller can take everything

The responses and where they come from.

SituationStatusHeadersTypical producer
This caller exceeded its limit429 Too Many RequestsRetry-After, RateLimit, RateLimit-PolicyLaravel throttle, Envoy, Kong, AWS API Gateway, Go middleware
The whole service is overloaded503 Service UnavailableRetry-AfterLoad shedder, NGINX limit_req by default (limit_req_status 503)
The request can never pass (cost above the maximum)400 or 413noneCost-based limiters
Monthly or plan quota used up429 (or 402/403 by product decision)RateLimit with a long windowBilling quota checks
Limiter itself unavailableServe (fail-open) or 503 (fail-closed)Retry-After on 503Your middleware policy
ClientEdge / CDNLB / proxyAPI gatewayApplicationOutboundx/time/ratepacingRetry-Afterfull jitterRateLimitfield (a, w)Cloudflarerate limitingrulesIP, IP with NATsupport, header,cookie, ASNper data centerNGINXlimit_req_zonelimit_reqleaky bucketper IPdefault 503:set 429Envoy local +global RLSKong pluginAWS API Gatewayusage plans,API keys, quotaper key/tenantLaravel throttleGo middlewareper user,per tenant,per endpoint,cost-based,concurrencythird-partyAPI limitsRateLimitedjob middlewareRedis::funnelsemaphorecoarse, cheap, anonymousprecise, identity-aware, costly

The picture is the request path. Limits on the left are cheap and anonymous (they only know an IP); limits on the right know who the caller is and what the request costs. Real systems use two or three layers, never one.

Why it exists ​

A server has finite capacity and many callers who do not coordinate. Stripe's post lists the situations a limiter exists for: one user "responsible for a spike in traffic"; "a misbehaving script which is accidentally sending you a lot of requests"; low-priority traffic crowding out "critical transactions"; and incidents where you must drop work. The IETF draft adds the business reasons: servers use quotas "to avoid overload, to ensure an equitable distribution of computational resources, or to enforce other policies such as monetization".

ReasonExampleWhat the limit protects
FairnessOne tenant's batch job must not slow every other tenantOther customers' latency
Abuse and securityPassword guessing, card testing, scraping, OTP brute forceAccounts, money, data
CostEach call costs you an LLM token bill or an SMS feeYour invoice
Protecting downstreamsA database or a partner API that handles 500 req/sThe dependency and everything behind it
MonetisationFree plan 60/min, Pro 1,200/minThe pricing model

The fundamental trade-offs:

Simpler / cheaperStronger / more precise
Fixed window: 1 counter, 2x bursts at the boundarySliding log: exact, memory grows with the limit
Local per-instance counters: no network hopCentral Redis: one source of truth, one extra round trip
Fail-open: availability firstFail-closed: protection first
Per-IP: works without loginPer-identity: fair, needs authentication first
One flat limitHierarchical limits: global, tenant, user, endpoint

The analogy we reuse on this page: a museum ticket machine. The machine prints one ticket every few seconds into a tray that holds at most twenty (token bucket: refill rate and burst). A school group arriving at opening time takes twenty tickets at once; the next visitor waits for the next ticket. A queue barrier that lets people through one at a time is the leaky bucket as a queue. A guard who writes down "next person allowed at 10:04:30" and checks the clock is GCRA. A sign "200 visitors per hour, counter resets on the hour" is a fixed window, and everybody who knows it arrives at 10:59 and 11:00.

Rate limit, load shedding, backpressure, quota, concurrency limit ​

MechanismDecides onTypical answerOwner page
Rate limitOne caller's rate (per key)429 + Retry-AfterThis page
Concurrency limitOne caller's requests in flight429 (per caller) or 503 (whole process)Concurrency
QuotaOne caller's total over a long period (day, month)429 or plan errorQuotas
Load sheddingThe whole system's health (CPU, queue depth, latency)503, drop low priority firstLoad Shedding
BackpressureConsumer speed inside a pipelineSlow the producer, bounded buffersBackpressure
Circuit breakerA dependency's health, from the caller sideFail fast locallyCircuit Breaker

Stripe draws the line in one sentence: "A load shedder makes its decisions based on the whole state of the system rather than the user who is making the request."

Three common misunderstandings, up front ​

  1. "Rate limiting protects us from DDoS." A request limiter runs after the TCP and TLS handshakes and after your proxy has spent memory on the request. It stops abusive clients, not floods; volumetric attacks belong to the edge (DDoS Protection).
  2. "100 per minute means at most 100 in any minute." Only for a sliding log. A fixed window allows 200 in 200 ms around the reset, and a token bucket with burst 100 and refill 100/60 per second admits 100 + 100/60 x t over t seconds: 298 in two minutes in the lab.
  3. "Per-IP is a fair default." One IPv4 address can be a whole office, a university or thousands of mobile users behind carrier-grade NAT, and one attacker can rotate through a whole IPv6 /64. RFC 6269 warns that with shared addresses "one user who fails a number of login attempts may block out other users".

Where it comes from ​

Telecom traffic shaping. Token and leaky buckets come from network engineering. NGINX's own explanation calls the leaky bucket an algorithm "widely used in telecommunications and packet-switched computer networks to deal with burstiness when bandwidth is limited". The Generic Cell Rate Algorithm comes from ATM networks; Brandur Leach's article (secondary source, 2015) explains that GCRA "was the algorithm recommended by the ATM Forum" for scheduling fixed-size "cells". We did not read the ATM Forum specification itself.

NGINX limit_req. The module appeared in NGINX 0.7.21 and states plainly: "The limitation is done using the "leaky bucket" method." Later versions added limit_req_status (1.3.15), delay for two-stage limiting (1.15.7), limit_req_dry_run (1.17.1) and zone sync in the commercial version (1.15.3).

HTTP 429, April 2012. RFC 6585 defined 429 and explicitly left the algorithm open: it "does not define how the origin server identifies the user, nor how it counts requests". RFC 9110 (June 2022) is the current definition of Retry-After and 503.

GCRA in Redis, 2015. Brandur Leach's Rate Limiting, Cells, and GCRA explained why a "drip" process is fragile, introduced GCRA to web developers, and pointed to the Go library Throttled, "already taking production traffic at Stripe". He later wrote redis-cell, a Redis module that exposes GCRA as one command, CL.THROTTLE.

Stripe, 30 March 2017. Paul Tarjan's Scaling your API with rate limiters described Stripe's four limiters (request rate, concurrent requests, fleet usage load shedder, worker utilisation load shedder), the token bucket in Redis, and the rollout rules: fail open, kill switches, dark launches.

Cloudflare, 7 June 2017. Julien Desgats's How we built rate limiting capable of scaling to millions of domains introduced the sliding window counter approximation and measured it on 400 million requests.

The RateLimit header fields, 2021 to now. The IETF HTTPAPI working group draft started with three fields (RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset in draft -05, 6 July 2022) and now defines RateLimit-Policy and RateLimit with structured parameters, plus RateLimit-Partition (draft -12, 20 November 2026, still an Internet-Draft, not an RFC).

text
     Year   Event                                         What changed in practice
1    -      Leaky bucket, token bucket, GCRA (telecom/ATM) Burst + rate as the two knobs
2    -      NGINX limit_req (module since 0.7.21)         Per-IP leaky bucket at the proxy
3    2012   RFC 6585 defines 429                          A status that means "slow down"
4    2015   GCRA for web APIs (Brandur, Throttled)        One timestamp per key, no drip job
5    2017   Stripe's four limiters                        Rate vs concurrency vs shedding
6    2017   Cloudflare sliding window counter              2 counters, ~6% error, async counting
7    2022   RFC 9110 restates Retry-After and 503          Current HTTP semantics
8    2022   IETF draft -05: RateLimit-Limit/Remaining/Reset Many gateways adopt these names
9    2026   IETF draft -12: RateLimit-Policy + RateLimit   q/w policy, a/w service limit, pk, c

(Rows 1 and 2 have no year because the pages we read give a version number or a lineage, not a date.)

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what products do, and the fix.

Token bucketLeaky bucket as a queueGCRA: leaky bucket as a meterrefill r tokens/sservedrequestcapacity bRequest takes cost tokens.Empty: reject (429).Burst of up to b passes at once.Lazy refill: tokens = min(b,tokens + elapsed x r)FIFO, size = burstout atrate rqueue full: rejectSmooth output, added latency.NGINX limit_req burst=N(nodelay serves at once butstill frees one slot per 1/r).Default reject status: 503.cost x TnowTATOne timestamp per key: TAT.T = period / count (emission).DVT = T x burst (tolerance).tat = max(TAT, now)allow_at = tat + cost x T - DVTnow < allow_at: reject,Retry-After = allow_at - nowelse TAT = tat + cost x TSame decisions as a tokenbucket; no drip process.

Token bucket Must-know ​

In plain words: a bucket holds up to b tokens and gains r tokens per second. Every request takes one token (or cost tokens). No token, no service.

Common misunderstanding: "A token bucket needs a background job that adds tokens." It does not. Lazy refill computes the tokens from the elapsed time when the next request arrives: tokens = min(b, tokens + elapsed x r). A bucket that has refilled completely is identical to a bucket that does not exist, so idle keys can simply be deleted.

Definition: two parameters, refill rate r (sustained rate) and burst b (bucket capacity). Over any interval of t seconds the bucket admits at most b + r x t units. golang.org/x/time/rate describes its Limiter as a "token bucket" of size b, "initially full and refilled at rate r tokens per second".

text
     r = 2 tokens/s, b = 5                     tokens before -> after
1    12:00:00.000  5 requests arrive at once   5 -> 0   all 5 served (burst)
2    12:00:00.100  request 6                   0.2      rejected, Retry-After = (1-0.2)/2 = 0.4 s
3    12:00:00.500  request 7                   1.0 -> 0 served (one token refilled)
4    12:00:03.000  request 8                   5.0 -> 4 served; refill capped at b = 5
5    12:00:03.000  request costing 6           4.0      rejected forever: cost > b is an error, not a 429

Real scenario: Stripe's request rate limiter ("We use the token bucket algorithm"), allowing users to "briefly burst above the cap" during a flash sale; AWS API Gateway throttling (rate = token refill, burst = bucket size); Envoy's local rate limit filter; a mobile app that fires eight calls when it opens and then goes quiet; an SMS endpoint where the burst is 1 so nobody gets five codes at once.

What provides it:

ProductAlgorithm and knobsWhere the state lives
Go golang.org/x/time/raterate.NewLimiter(r, b); Allow, Reserve, Wait, AllowN, SetLimitOne process; you keep a map of limiters per key
Envoy local rate limittoken_bucket: max_tokens, tokens_per_fill, fill_intervalPer Envoy process (default) or per connection
AWS API Gateway"throttling rate" = tokens added per second, "throttling burst" = bucket capacityAWS, per account/Region, stage, method, usage plan
Stripe (blog)Token bucket per user in RedisRedis
This chapter's Go moduletokenbucket.New(clk, perSecond, burst) with lazy refill and SweepOne process

Fix / how to use it: choose r from the sustained rate the backend can serve per caller and b from the legitimate burst you observe (page load fan-out, mobile app start). Reject cost > b as a client error, because it can never succeed. Code: tokenbucket.go.

Leaky bucket: as a queue and as a meter Must-know ​

In plain words: water (requests) pours into a bucket that leaks at a constant rate; if it overflows, requests are refused. As a queue, requests really wait and are released at the leak rate. As a meter, nothing waits: the bucket level is only a number used to decide.

Common misunderstanding: "Leaky bucket and token bucket are different algorithms with different results." As meters they are mirror images (the leaky bucket counts used capacity, the token bucket counts free capacity) and make the same decisions. The real difference is the queue variant, which delays requests instead of rejecting them and therefore adds latency.

Definition: leaky bucket as a queue = a FIFO of size burst drained at rate r; when full, reject. Leaky bucket as a meter = a counter incremented per request and decremented over time at rate r; reject when it would exceed the capacity. Cloudflare's description: "incrementing a counter when each request comes in. That same counter is also decremented over time based on the allowed rate".

text
     NGINX: rate=10r/s (one slot per 100 ms), burst=20          21 requests arrive at t=0
1    without nodelay   1 forwarded now, 20 queued, one forwarded every 100 ms; the 20th waits 2 s
2    with nodelay      21 forwarded now; 20 slots marked taken; one slot freed every 100 ms
3    t=101 ms          20 more arrive: 1 slot free -> 1 forwarded, 19 rejected (503 by default)
4    t=501 ms instead  5 slots free -> 5 forwarded, 15 rejected

(These numbers are from the NGINX blog; its editor's note warns that the blog's description of bursts is imprecise and points to nginx.org for exact behaviour.)

Real scenario: NGINX in front of a PHP-FPM pool that can only run 50 workers; a login location limited to 1 request per second per IP with burst=5; a payment provider callback endpoint where delaying is better than refusing; a video transcoder that must receive jobs at a steady pace.

What provides it:

ProductVariantNotes
NGINX limit_reqQueue by default; nodelay serves the burst immediately; delay=N is two-stagelimit_req_status default 503; tracked at millisecond granularity
NGINX PlusSame, plus zone sync across a cluster and variable rateCommercial subscription
Cloudflare (2017 blog)Considered and rejected leaky bucket: "requires multiple distinct operations that we cannot do atomically" with memcacheChose sliding window counter
GCRA (next block)Meter, stored as one timestampredis-cell, go-redis redis_rate, Throttled

Fix / how to use it: use burst plus nodelay in NGINX for browser traffic (the blog's recommendation: "For most deployments, we recommend including the burst and nodelay parameters"); use the queue variant only where waiting is acceptable to the caller; set limit_req_status 429 so clients see a rate-limit status rather than an outage.

nginx
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
limit_req_zone $server_name        zone=perserver:10m rate=500r/s;

server {
    location /api/ {
        limit_req zone=perip burst=20 nodelay;   # per client
        limit_req zone=perserver burst=100;      # whole virtual server
        limit_req_status 429;
        limit_req_log_level warn;
    }
}

GCRA (Generic Cell Rate Algorithm) Important ​

In plain words: instead of counting tokens, remember one time per key: when the next request would be "on schedule" (the theoretical arrival time, TAT). A request is fine if it is not too far ahead of that schedule.

Common misunderstanding: "GCRA is a different policy from a token bucket." With burst b and emission interval T = 1/r, GCRA admits exactly the same sequence as a token bucket of capacity b refilled at r. This chapter's TestEquivalentToTokenBucket checks it on 100 requests with irregular gaps. Its advantages are storage (one timestamp) and that the state can be written as a single SET with an expiry.

Definition: emission interval T = period / count; delay variation tolerance DVT = T x burst. For a request with cost n: tat = max(TAT, now), new_tat = tat + n x T, allow_at = new_tat - DVT. If now is before allow_at, reject with Retry-After = allow_at - now; otherwise store new_tat. Brandur: "If it's in the past, we allow the incoming request, and if it's in the future, we don't."

text
     T = 1 s, burst 3, DVT = 3 s                 TAT before   new TAT   allow_at   result
1    t=0   request 1                              (none)=0     1         -2         allowed, remaining 2
2    t=0   request 2                              1            2         -1         allowed, remaining 1
3    t=0   request 3                              2            3          0         allowed, remaining 0
4    t=0   request 4                              3            4          1         rejected, Retry-After 1 s
5    t=1   request 5                              3            4          1         allowed

Real scenario: redis-cell's CL.THROTTLE user123 15 30 60 (burst 15, 30 per 60 s); Stripe via Throttled (Brandur: "already taking production traffic at Stripe and should be soon at Heroku as well"); go-redis's redis_rate package ("implements GCRA (aka leaky bucket) for rate limiting based on Redis"); any Redis-backed limiter that needs per-key memory of one integer.

What provides it:

ProductInterfaceNotes
redis-cell (module)CL.THROTTLE <key> <max_burst> <count per period> <period> [<quantity>]Returns limited, limit (max_burst + 1), remaining, retry after, reset after; maintainer says "best effort" maintenance mode
go-redis redis_rate v10limiter.Allow(ctx, "project:123", redis_rate.PerSecond(10))Lua script on plain Redis
Throttled (Go)GCRA rate limiterReference implementation named by Brandur
This chaptergcra.New in memory, redislimiter.NewGCRA with gcra.luaUses Redis TIME, key expires when it equals "absent"

Fix / how to use it: prefer GCRA when the state must live in Redis: one key, one SET ... PX per allowed request, and the key's expiry equals the time until the bucket is full again. Use the store's clock, as Brandur recommends ("use the store's time for synchronization (for example, by accessing the TIME command in Redis)"), so application servers with skewed clocks agree.

Fixed window and the window boundary burst Must-know ​

In plain words: count requests per calendar window (this minute, this hour) and reset the counter when the window changes.

Common misunderstanding: "It is too inaccurate to use." It is cheap, easy to explain to customers ("1,000 per hour, resets on the hour") and fine for quotas and coarse abuse limits. Its flaw is specific: the window boundary burst, up to twice the limit in a short time around each reset, which matters for protecting fragile backends.

Definition: key = identity + window index (floor(now / size)); INCR the key; allow while the count is at most the limit; the key expires with the window. Cloudflare: the counter is "arbitrarily reset at regular intervals, allowing regular traffic spikes to go through the rate limiter".

text
     limit 100/min, fixed windows aligned to :00            admitted
1    12:00:59.900   100 requests (window 12:00, count 0->100)   100
2    12:01:00.000   window changes; counter for 12:01 starts at 0
3    12:01:00.100   100 requests (window 12:01, count 0->100)   100
4    -> 200 requests reach the backend within 200 ms
5    A variant anchored at the first hit (Laravel's RateLimiter) has the same flaw at its own reset time

Real scenario: "1,000 requests per hour" public APIs (Brandur's article uses GitHub's REST API as its example of this "time bucketed" approach and shows how a script can "burn an account's entire rate limit immediately"); Laravel's RateLimiter (a counter plus a :timer key created on the first hit); Envoy's reference rate limit service with per-second, per-minute, per-hour and per-day units; Kong's rate-limiting plugin with second/minute/hour/day/month/year limits.

What provides it:

ProductWindowNotes
Laravel RateLimiter / throttleAnchored at the first hit, decaySeconds longX-RateLimit-Reset and Retry-After on 429
Laravel throttleWithRedisLua hash with start, end, countAtomic; key expiry set to twice the decay
Envoy envoyproxy/ratelimitUnits second/minute/hour/dayRedis backend, optional second Redis for per-second limits
Kong rate-limitingsecond ... year, several at onceRate Limiting Advanced adds sliding windows
Redis INCR docs, pattern 1Key ip:timestamp, INCR + EXPIRE in MULTIOne key per second per IP

Fix / how to use it: keep fixed windows for quotas and for limits where a 2x short burst is harmless; switch to a sliding window counter or GCRA in front of fragile resources. In Redis, set the expiry in the same atomic step as the increment (INCR + EXPIRE race).

Sliding window log Important ​

In plain words: store the timestamp of every admitted request; to decide, drop timestamps older than one window and count what is left.

Common misunderstanding: "Exact is always better." Cloudflare rejected it because it "has huge processing and memory requirements": a limit of 5,000 per hour means up to 5,000 timestamps per key, read on every request.

Definition: for each key keep an ordered set of timestamps; on each request remove entries at or before now - window; allow if count + cost is at most the limit and then append. Retry-After is the time until enough of the oldest entries expire.

text
     limit 3 per 10 s                         stored timestamps after the step
1    t=0    request A    allowed              [0]
2    t=4    requests B,C allowed              [0, 4, 4]
3    t=5    request D    rejected             [0, 4, 4]  Retry-After = 10 - 5 = 5 s (A expires)
4    t=10.1 request E    allowed              [4, 4, 10.1]

Real scenario: low limits where exactness matters (5 OTP attempts per 15 minutes, 3 password resets per hour); auditing ("show me the attempts"); Redis sorted sets with ZREMRANGEBYSCORE + ZCARD + ZADD in one Lua script; small per-account abuse limits in fraud systems.

What provides it:

ProductSupport
RedisNo built-in; sorted set + Lua script (one member per request)
Kong Rate Limiting AdvancedSliding windows (implementation not documented on the page we read)
This chapterwindow.NewLog, with Entries(key) exposing the memory cost

Fix / how to use it: only for small limits. Memory is O(limit) per key; a 10,000/hour limit for 100,000 keys is a billion timestamps in the worst case.

Sliding window counter Must-know ​

In plain words: keep the count of the previous window and of the current one; assume the previous window's requests were spread evenly and count only the share that still falls inside the last 60 seconds.

Common misunderstanding: "An approximation will let attackers through." Cloudflare's measurement on "400 million requests from 270,000 distinct sources" found "An average difference of 6% between real rate and the approximate rate", three sources allowed "slightly above the threshold" (less than 15% above), and "None of the mitigated sources was below the threshold".

Definition: estimate = previous x (window - elapsed) / window + current. Cloudflare's example: limit 50 per minute, 42 requests in the previous minute, 18 in the current one which started 15 seconds ago: 42 x 45/60 + 18 = 49.5. Two integers per key; both can be read with one GET of two keys or one hash.

text
     limit 60/min                         prev  curr  elapsed  estimate              decision
1    12:00:00-12:00:59  60 requests        -     60    -        -                     all allowed
2    12:01:15  request                     60    0     25%      60 x 0.75 + 0 = 45    allowed (15 more fit)
3    12:01:15  16th request at once        60    15    25%      45 + 15 = 60          rejected
4    12:01:45  request                     60    15    75%      60 x 0.25 + 15 = 30   allowed

Real scenario: Cloudflare's edge limiter (memcache INCR and GET only); Kong Rate Limiting Advanced sliding windows; API gateways that want "per minute" semantics without the boundary burst; this chapter's lab, where it admits 100 of 200 at the boundary and 125 of 200 when a second burst arrives 45 s after the first.

What provides it:

ProductHow
Cloudflare (2017)Counters in a per-PoP Twemproxy/memcache cluster, updated asynchronously
RedisTwo keys per window index (INCR, GET), or Lua
This chapterwindow.NewCounter with a computed Retry-After

Fix / how to use it: the default "windowed" algorithm for new systems when you want per-minute wording for customers and need only two integers per key in Redis.

Fixed windowSliding window logSliding window counter1 integer per key200 pass in 200 ms(boundary burst)12:00:00100 + 10012:01:0012:02:001 timestamp per requestexact: 2nd burst rejectedmemory O(limit) per keylast 60 s at 12:01:00.1100 entries already: reject2 integers per keyestimate = prev x (1 - elapsed/ window) + currprev: 42current: 1815 s into the minutesliding 60 s view: 75% of previous42 x 0.75 + 18 = 49.5(Cloudflare: 6% average error)

Hierarchical and multi-tier limits Important ​

In plain words: several limits apply to one request at once: the whole API, the tenant, the user and the endpoint. The request passes only if all of them have room.

Common misunderstanding: "Check them one after another and take a token from each." If the user tier passes and takes a token and the endpoint tier then rejects, the user lost a token for a request that was never served. Check every tier first, then consume from all (two-phase), or refund on rejection.

Definition: an ordered list of (key function, policy) pairs, from widest to narrowest. Laravel: "Each rate limit will be evaluated for the route based on the order they are placed within the array". NGINX: "All limits that match a given request are applied, meaning the most restrictive one is used". The response should name the policy that rejected (RateLimit: "tenant";a=0;w=30).

text
     tiers: global 1000/s > tenant 100/s > user 10/s burst 20 > POST /exports 1/s burst 2
1    acme/u1 POST /exports #1, #2        all tiers have room        allowed (each tier -1)
2    acme/u1 POST /exports #3            endpoint tier empty        rejected by "endpoint"; no tier consumed
3    acme/u1 GET /orders                 endpoint tier not applicable allowed
4    10 users of acme, 20 requests each  tenant tier caps at 100    100 admitted in total

Real scenario: SaaS plans (tenant limit by plan, user limit to stop one user starving colleagues); login (global ceiling, per-account and per-IP); Envoy descriptors with nested keys; AWS API Gateway's order of evaluation (AWS Region limits, account, stage/method, per-client usage plan); GitHub's primary plus secondary limits.

What provides it:

ProductMechanism
LaravelRateLimiter::for returning an array of Limit objects, each with its own by() prefix
NGINXSeveral limit_req directives in one location
EnvoySeveral rate limit actions/descriptors per route
AWS API GatewayAccount, stage, method and usage-plan throttles; a client limit "can't be higher than the per-account limits"
This chapterhierarchy.New(clk, tiers...): two-phase under one lock

Fix / how to use it: order tiers widest first; prefix every key with the tier name; make the endpoint tier optional (Key returns empty); for Redis-backed tiers, check and consume all tiers in one Lua script when they live on one node, or accept small over-consumption and refund.

Keys: per-user, per-API-key, per-IP, per-tenant, per-endpoint Must-know ​

In plain words: the key decides who shares a bucket. Choose the strongest identity you have at that layer.

Common misunderstanding: "IP addresses identify clients." Behind NAT, and especially CGNAT (carrier-grade NAT, where an ISP puts many subscribers behind one public IPv4), one address is many people; behind your own load balancer every request has the balancer's address unless you trust X-Forwarded-For correctly; and the left-most X-Forwarded-For entry is whatever the client typed. RFC 6269 says a server that puts an address "in a penalty box" will, with sharing, see "many login attempts from the same address because it is now shared across a potentially large number of subscribers". (NAT mechanics: NAT, PAT & Port Forwarding; CGNAT.)

Definition: a key function maps a request to a string. Typical order of preference: verified API key or OAuth client, authenticated user, tenant, then network address; endpoint and method are added as extra dimensions. The IETF draft calls this a quota partition and lets servers expose it (RateLimit-Partition: "api";user_id;method, and a pk partition-key parameter).

text
     request                                        key chosen by DefaultKey
1    X-Api-Key: sk_test_example                     key:<first 8 bytes of SHA-256, hex>
2    authenticated as user 42                       user:42
3    anonymous, peer 198.51.100.23                  ip:198.51.100.23
4    anonymous, peer 10.0.3.4 (our LB), XFF "203.0.113.99, 198.51.100.23, 10.0.1.1"
                                                    ip:198.51.100.23 (right-most untrusted hop)
5    anonymous IPv6 2001:db8:1:2:aaaa::1             ip:2001:db8:1:2::/64 (group by /64)

Real scenario: a university of 20,000 students behind a handful of addresses hitting a per-IP login limit; a mobile carrier's CGNAT making one IPv4 look like a botnet; a partner sharing one API key across 200 stores; a tenant with one runaway integration user; an attacker rotating addresses inside one IPv6 /64.

What provides it:

ProductKey optionsNotes
Cloudflare rate limiting rulesIP, "IP with NAT support", query, host, headers, cookie, ASN, country, path, JA3/JA4, JSON field, bodySome characteristics need Enterprise or Bot Management
NGINXAny variables ($binary_remote_addr, $http_x_api_key, $server_name)"Requests with an empty key value are not accounted" (used for allowlists)
Kong rate-limitingConsumer if authenticated, else client IP (from X-Real-IP, real_ip_header, trusted_ips)Also service, header, path
AWS API GatewayAPI key in a usage plan"Don't use API keys for authentication or authorization"
LaravelLimit::...->by($value); unnamed throttle:60,1 keys on user ID or domain + IP$request->ip() needs trustProxies
This chapter's Gohttplimit.DefaultKey(trusted): hashed API key, user, IP with trusted proxies, IPv6 /64Never stores raw API keys in Redis

Fix / how to use it: limit anonymous endpoints per IP generously and per account tightly; authenticate first, then limit by identity; configure trusted proxies (Laravel trustProxies, NGINX real_ip, Kong trusted_ips); group IPv6 by /64; hash API keys before using them as Redis keys.

Concurrency limits (semaphores) Important ​

In plain words: limit how many of a caller's requests are in progress at once, not how many start per second.

Common misunderstanding: "A rate limit already limits load." Ten requests per second that each take 30 seconds means 300 in flight. Stripe: "Instead of "You can use our API 1000 times a second", this rate limiter says "You can only have 20 API requests in progress at the same time"."

Definition: a counting semaphore per key (and usually one per process): acquire on entry, release on exit (including on panic or timeout), reject when no permit is free. The IETF draft has a quota unit for it: qu="concurrent-requests".

text
     per-user limit 2 in flight, process limit 3
1    user 1 request A starts            in flight: u1=1, total=1
2    user 1 request B starts            u1=2, total=2
3    user 1 request C                   rejected 429 (user share)
4    user 2 request D starts            u2=1, total=3
5    user 3 request E                   rejected 503 (process full: this is load shedding)
6    A finishes                         u1=1, total=2; E would now pass

Real scenario: Stripe's concurrent request limiter for "CPU-intensive API endpoints"; GitHub's "No more than 100 concurrent requests are allowed"; report exports; LLM inference calls; outbound connections to a CRM that allows ten concurrent connections.

What provides it:

ProductMechanism
GoBuffered channel or golang.org/x/sync/semaphore; this chapter's concurrency.Limiter
LaravelRedis::funnel('name')->limit(10)->then(...) (Redis concurrency limiter); WithoutOverlapping job middleware for one-at-a-time
EnvoyCircuit breakers (max_requests, max_pending_requests) per cluster
NGINXlimit_conn (connection count per key)

Fix / how to use it: combine both: a rate limit for "how often" and a concurrency limit for "how much at once"; always release in defer/finally; give permits an expiry in distributed semaphores so a crashed worker does not hold one forever (releaseAfter in Laravel's funnel builder).

Cost-based limits (GraphQL complexity, LLM tokens) Important ​

In plain words: not every request costs the same, so charge each one a number of points and limit points per window.

Common misunderstanding: "One GraphQL request is one request." GitHub's documentation shows a query returning 60 labels where "the API has to connect to each of the 5,000 potential total issues", so it counts 5,000 requests' worth of work.

Definition: compute cost before execution (from the parsed query, the page size, the model's token estimate) and consume cost units; reject requests whose cost exceeds the burst outright; optionally reconcile with the actual cost after execution. The IETF draft's c parameter reports "the cost of the corresponding request in quota units".

text
     budget 5,000 points/hour (GitHub's user limit), max 500 per query
1    query { viewer { repositories(first: 100) { issues(first: 50) } } }  nodes 100 x 50 = 5,000 -> 50 points
2    budget 5,000 -> 4,950; response RateLimit: "graphql";a=4950;w=3600;c=50
3    query asking first: 100 x first: 100 x first: 10 = 100,000 nodes -> 1,000 points  rejected 400 (never fits)
4    when used + cost > budget                                                     429, refund the cost

Real scenario: GitHub GraphQL (5,000 points per hour per user, secondary limit "no more than 2,000 points per minute" for the GraphQL endpoint); Shopify-style GraphQL cost budgets (not read for this page); LLM APIs limiting tokens per minute; bulk endpoints charged per item; Envoy's local rate limit with a request cost; Laravel RateLimiter::increment($key, amount: $cost).

What provides it:

ProductMechanism
GitHub GraphQLPoints per query; rateLimit { cost remaining } field; x-ratelimit-* headers
Envoy local rate limitToken cost per request; with local_cluster_rate_limit cost is scaled by cluster membership
LaravelRateLimiter::increment($key, $decay, $cost), atomic on redis, memcached and database stores
Gox/time/rate AllowN(t, n); this chapter's Allow(ctx, key, cost) everywhere

Fix / how to use it: estimate cost from the AST, not from the raw string; cap the cost per request (400 if exceeded); return the cost in the response so clients can plan. Code: GraphQLCostLimit.php.

Quotas vs rate limits Good to know ​

In plain words: a rate limit is about speed (per second or minute); a quota is about total consumption over a long, often billed period (per day or month).

Common misunderstanding: "A quota is a rate limit with a longer window." Technically yes, operationally no: quotas must survive a cache flush, be auditable, be resettable by support and match an invoice, so they belong in a database, not only in Redis.

Definition: AWS API Gateway: "A quota limit sets the target maximum number of requests with a given API key that can be submitted within a specified time interval"; its throttles and quotas are both "applied on a best-effort basis and should be thought of as targets". The IETF draft generalises both as a quota policy with quota q over a window w.

text
     plan: 50,000 calls/month, 1,200/min
1    each request    Redis: per-minute GCRA (fast path)
2    each request    PostgreSQL: UPDATE ... used = used + cost WHERE used + cost <= 50000 (or batched every few seconds)
3    used reaches 50,000  plan error / 429 with RateLimit: "month";a=0;w=<seconds to month end>
4    support raises the quota   one row update, no cache surgery

Real scenario: API products sold by volume (AWS usage plans); free tiers; per-tenant daily export limits; LLM monthly token budgets.

What provides it:

ProductQuota feature
AWS API GatewayUsage plan quota per API key "within a specified time interval", plus throttle
KongLong windows (day, month, year) in rate-limiting
LaravelLimit::perDay(); durable quotas in your own table (this chapter's QuotaLedger)

Fix / how to use it: keep fast short-window limits in Redis and authoritative quotas in SQL with an atomic conditional update:

sql
-- PostgreSQL: consume `cost` only if the month's total still fits
INSERT INTO api_quota_usage (tenant_id, period, used, created_at, updated_at)
VALUES ($1, to_char(now(), 'YYYY-MM'), $2, now(), now())
ON CONFLICT (tenant_id, period) DO UPDATE
    SET used = api_quota_usage.used + EXCLUDED.used, updated_at = now()
    WHERE api_quota_usage.used + EXCLUDED.used <= $3
RETURNING used;   -- no row returned: quota exhausted, nothing changed

Distributed rate limiting Must-know ​

In plain words: with N application instances, a per-process limiter allows N times the limit. To enforce one number across the fleet you either ask a shared store on every request, or count locally and reconcile.

Common misunderstanding: "INCR then EXPIRE is fine, Redis is single-threaded." Each command is atomic, the pair is not. The Redis documentation spells out the failure: "If for some reason the client performs the INCR command but does not perform the EXPIRE the key will be leaked until we'll see the same IP address again". With a fixed key that means the counter never resets and the client is limited forever. The fix is a Lua script (EVAL, "Redis guarantees the script's atomic execution") or MULTI/EXEC.

Definition: the design space has five points:

  1. Centralised store with atomic scripts. Every decision is one EVALSHA on Redis (GCRA, sliding counter or fixed window). Exact; adds one round trip; Redis is on the request path.
  2. Redis Cell. The CL.THROTTLE command does GCRA inside Redis as a module; redis-cell's README measures "very roughly 0.1 ms per command as seen from a Redis client". Needs a module you can load (not available on every managed Redis).
  3. Sharded counters and approximate global limits. A hot key (one huge tenant) is split into k sub-counters on different shards, or each instance gets a local share limit / N (Kong's advice: 100/s over 5 balanced nodes, "you can set the local limit to 30 requests every second"). See Sharded Counters.
  4. Local buckets with periodic sync. Decide from memory; push deltas every 100 ms to 1 s; pull the global total. Kong's sync_rate; Cloudflare's asynchronous counting where only the mitigation flag is checked on the hot path. Overshoot is bounded by instances x traffic per sync interval.
  5. Gossip and cell-based designs. Instances exchange counts peer to peer (Gossip Protocols), or the system is split into cells (Cloudflare's per-PoP counting, per-region Redis) so each cell enforces its share and no cross-region call sits on the hot path. Anycast keeps a client in one PoP, so per-PoP counting is close to per-client.
text
     Race without atomicity (Redis INCR pattern 2, as in the Redis docs)
1    client A: GET ip:198.51.100.7          -> nil
2    client A: INCR ip:198.51.100.7          -> 1
3    client A: (process crashes before EXPIRE)
4    key has no TTL: counter grows forever; once above 10 the IP is limited until someone deletes it
     Fix: one script  local n = redis.call('INCRBY', KEYS[1], ARGV[2]); if n == tonumber(ARGV[2]) then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end

Real scenario: a Laravel app on 12 Octane workers across 4 hosts sharing one Redis; Envoy fleets calling one rate limit service; Kong clusters with policy: redis; Cloudflare's millions of domains; a multi-region API that limits per region and accepts up to "regions x limit" globally.

What provides it:

ApproachAccuracyLatency addedFailure modeProducts
Central Redis + LuaExact1 RTT (sub-ms in one zone)Redis down = decide fail-open/closedLaravel throttleWithRedis, go-redis redis_rate, this chapter
Redis CellExact1 RTTSame; module availabilityredis-cell
Local share (limit / N)Drifts when traffic is unbalanced or N changesNoneKeeps workingKong policy: local
Local + periodic syncOvershoot bounded by sync intervalNone on hot pathKeeps working, drift growsKong sync_rate, Cloudflare, Envoy quota-based global limit
Two-stage local + globalExact at stage 21 RTT only for requests passing stage 1Stage 1 still protectsEnvoy local + global rate limit service
Cell-based / per regionExact per cellLocal RTTOne cell's store down affects one cellCloudflare per PoP, per-region Redis

Fix / how to use it: start with central Redis and one atomic script; keep all keys of one script on one Redis Cluster slot ("all keys that a script accesses must be explicitly provided as input key arguments"; use a hash tag such as rl:{tenant42}:user7); add a local token bucket in front for burst absorption; move to local + sync or cells only when the round trip or one hot key becomes the bottleneck.

Centralised (exact)Local + periodic syncTwo-stage (Envoy)app 1app 2app 3Redis: EVALSHAGCRA / INCRevery request+ exact, one source of truth- 1 RTT added per request- Redis is now on therequest path: decidefail-open or fail-closed- one hot key per tenantlands on one shardapp 1app 2app 3locallocallocalRedis INCRBYglobal totalsync every 100 ms to 1 s+ no RTT on the hot path+ survives Redis outages- overshoot up toinstances x traffic per syncKong: sync_rateCloudflare: async counting,mitigation cached in memorylocal token bucket (per Envoy)global rate limit service (gRPC)Redis (per-second, per-minute...)Stage 1 absorbs large burstscheaply; stage 2 is precise.RLS error or timeout: allowby default; deny only withfailure_mode_deny: true

When the limiter fails: fail-open vs fail-closed Must-know ​

In plain words: if Redis or the rate limit service does not answer, you must decide whether to let the request through (fail-open) or refuse it (fail-closed).

Common misunderstanding: "Fail-closed is the safe choice." For most APIs it turns a cache outage into a full outage. Stripe's guidance was to catch "exceptions at all levels so that any coding or operational errors would fail open and the API would still stay functional". Envoy's default is the same: the reference service returns an error at the deadline and "Envoy then applies its failure mode right away (allow by default, or deny with failure_mode_deny)".

Definition: a per-policy rule: fail-open (serve, log, alert, optionally fall back to a local in-memory bucket) or fail-closed (503 + Retry-After). Always with a tight timeout on the limiter call (tens of milliseconds), so a slow Redis does not become slow requests.

text
     policy "api" fail-open + local fallback; policy "otp" fail-closed
1    Redis timeout (50 ms)    GET /orders        served; local bucket 20/s applied; warn log; metric limiter_errors++
2    Redis timeout (50 ms)    POST /otp/verify   503 Retry-After: 1   (guessing must stay impossible)
3    Redis back               both policies use Redis again; local fallback idle

Real scenario: product APIs (fail-open: a limiter outage should not take down checkout); login, OTP, password reset, gift-card redemption (fail-closed: the limit is the security control); cost-protection limits on paid upstream APIs (fail-closed or fall back to a strict local bucket).

What provides it:

ProductDefaultKnob
Envoy global rate limitFail-openfailure_mode_deny: true
Laravel throttleNo fallback in the 13.x source: a cache-store exception propagates (inference: a 500)Wrap or catch in your own middleware
This chapter's GoOptions.FailOpen, Options.Timeout (default 50 ms)Per policy

Fix / how to use it: decide per policy and write it down; fail-open with a local fallback bucket for general traffic; fail-closed for security limits; alert on limiter errors, not only on 429s; add kill switches and dark launches (Stripe: "Dark launch each rate limiter to watch the traffic they would block"; NGINX limit_req_dry_run; shadow_mode in envoyproxy/ratelimit).

Response semantics: 429, Retry-After, RateLimit fields, 503 Must-know ​

In plain words: tell the caller clearly that they are going too fast (429), when they may try again (Retry-After), and how much room they have left (RateLimit).

Common misunderstanding: "Any 4xx will do" or "503 is fine for limits". A 403 or 400 tells clients the request is wrong and should not be retried; a 503 tells them the server is broken. RFC 9110 reserves 503 for when the server "is currently unable to handle the request due to a temporary overload or scheduled maintenance". NGINX answers 503 by default, which makes per-client limits look like an outage on dashboards.

Definition:

  • 429 Too Many Requests (RFC 6585): the responses "SHOULD include details explaining the condition, and MAY include a Retry-After header", and "MUST NOT be stored by a cache".
  • Retry-After (RFC 9110 section 10.2.3): "either an HTTP-date or a number of seconds"; Retry-After: 120 means two minutes. Seconds are safer than dates because they do not depend on clock synchronisation.
  • RateLimit-Policy and RateLimit (IETF draft -12): RateLimit-Policy: burst;q=100;w=60,"daily";q=1000;w=86400 describes policies (quota q, window w, unit qu, partition key pk); RateLimit: default;a=50;w=30 gives the available quota a and effective window w, optional cost c. "If a response contains both the RateLimit and Retry-After fields, the Retry-After field MUST take precedence".
  • Legacy names: draft -05 used RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset; Kong sends those three ("based on the Internet-Draft ... and may change"); Laravel and GitHub send X-RateLimit-Limit, X-RateLimit-Remaining (and Laravel X-RateLimit-Reset on 429).
  • 503 Service Unavailable: for load shedding and for a fail-closed limiter outage, with Retry-After.
text
     HTTP/1.1 200 OK
     RateLimit-Policy: "default";q=100;w=60
     RateLimit: "default";a=1;w=7
1    client: one request left in the next 7 s; slow down
     HTTP/1.1 429 Too Many Requests
     Content-Type: application/problem+json
     Retry-After: 7
     RateLimit: "default";a=0;w=7
2    client: wait 7 s (Retry-After wins over w), then resume at the advertised rate

Real scenario: public APIs publishing limits so SDKs can pace; mobile clients showing "try again in 30 s"; a CDN that must not cache a 429; a gateway translating an upstream's X-RateLimit-* into the standard fields.

What provides it:

ProductStatusHeaders sent
Laravel throttle429 (ThrottleRequestsException, message "Too Many Attempts.")X-RateLimit-Limit, X-RateLimit-Remaining; on 429 also Retry-After, X-RateLimit-Reset
NGINX limit_req503 default, limit_req_status to changeNone; $limit_req_status variable for logs
Envoy local rate limit429, x-envoy-ratelimited headerRetry-After when enable_retry_after_header is set (delay-seconds, at least 1)
Kong rate-limiting429, body { "message": "API rate limit exceeded" }RateLimit-Limit/Remaining/Reset, X-RateLimit-Limit-Minute etc., Retry-After
AWS API Gateway429 Too Many Requests(not documented on the pages read)
CloudflareConfigured action; visitors see error 1015Configurable
This chapter's Go429 problem+json, 503 when fail-closed, 400 when cost can never fitRateLimit-Policy, RateLimit (draft -12), Retry-After

Fix / how to use it: 429 for per-caller limits, 503 for system overload, both with Retry-After in seconds rounded up; send RateLimit on successful responses too (at least when the quota is low, as the draft allows for performance); never send a 429 with Cache-Control that lets it be stored.

Client behaviour: backoff with jitter and respecting headers Important ​

In plain words: a good client paces itself below the limit, waits as long as Retry-After says, and when it has no hint waits a random, growing amount of time.

Common misunderstanding: "Retry immediately, the limit will reset." Immediate retries from many clients arrive in lockstep and keep the bucket empty. AWS's analysis of backoff concluded that "Equal Jitter" is "the loser" and that full or decorrelated jitter spread retries best (Timeouts, Retries & Jitter owns the detail).

Definition: (1) client-side token bucket at or below the documented rate; (2) on 429/503 with Retry-After, wait exactly that long (it takes precedence over RateLimit); (3) without a hint, full jitter: sleep = random(0, min(cap, base x 2^attempt)); (4) give up when the wait would pass the caller's deadline; (5) retry only idempotent requests or those with an idempotency key (API Idempotency). Google's SRE book adds adaptive throttling: each client tracks requests and accepts over two minutes and starts rejecting locally once requests exceed K x accepts (the book's worked example uses K = 2 and discusses lowering it to 1.1).

text
     client limited to 8 req/s by x/time/rate; server 429 with Retry-After: 2
1    t=0.000  request 1   429 Retry-After: 2        sleep 2 s (hint wins)
2    t=2.000  request 1   429 Retry-After: 2        sleep 2 s
3    t=4.000  request 1   200                        continue at 8/s
4    deadline 1 s, Retry-After: 30                   give up now (ErrGaveUp), do not sleep 30 s

Real scenario: SDKs for payment and messaging APIs; queue workers calling a CRM (release the job for Retry-After seconds instead of sleeping in the worker); browsers retrying a failed fetch; batch exporters that must finish overnight without tripping limits.

What provides it:

ProductClient feature
Go x/time/rateWait(ctx) blocks until a token is available or the context ends
This chapter's clientPacing + Retry-After (seconds and HTTP-date) + full jitter + deadline check
Laravel HTTP clientHttp::retry($times, $sleepClosure, $when); read Retry-After from $exception->response
Laravel queues$this->release($seconds); RateLimited job middleware releases with the limiter's delay

Fix / how to use it: see client.go and SyncContactToCrm.php.

Where to enforce: edge, gateway, service Important ​

In plain words: limit as early as possible for cheap anonymous filtering and as late as necessary for identity-aware, precise limits.

Common misunderstanding: "Pick one layer." The edge cannot see your tenant plan; the application cannot stop a flood before it costs you CPU. Most production systems combine an edge or proxy limit (per IP, generous) with a gateway or application limit (per key, user or tenant, exact).

Definition: the layers in the layer diagram: client, edge/CDN, load balancer or reverse proxy, API gateway or sidecar, application, outbound. Each layer has a different key available, a different cost per decision and a different failure blast radius.

text
     request path for POST /v1/exports from tenant acme, user 7
1    Cloudflare rule: 600/min per IP with NAT support   passes
2    NGINX limit_req: 20 r/s burst 40 per IP            passes
3    Envoy local token bucket: 1,000/s per Envoy        passes (burst absorption)
4    Envoy global RLS: tenant acme 100/s (Redis)        passes
5    Laravel throttle:exports  10/hour per user          429, Retry-After: 1260

Real scenario: an e-commerce site protecting login at the edge and checkout per user in the app; a public API with AWS API Gateway usage plans per API key; a Kubernetes platform with Envoy/Istio sidecars applying per-route local limits; a PHP monolith with NGINX in front and Laravel limiters inside.

What provides it:

LayerProductsKeys availableStrengthWeakness
Edge / CDNCloudflare rate limiting rulesIP, headers, cookie, ASN, country, JA3/JA4Stops traffic before your network"not designed to allow a precise number of requests"; counters per data center
Reverse proxyNGINX limit_req, HAProxy stick tablesIP, any header/variableVery cheap; shared memory across workersPer instance unless NGINX Plus sync
API gateway / sidecarEnvoy local + global, Kong, AWS API GatewayAPI key, consumer, route, headersCentral policy, no app codeNeeds identity propagated to it
ApplicationLaravel throttle, Go middlewareUser, tenant, plan, cost, endpointFull business contextRequest already consumed resources
Outboundx/time/rate, RateLimited jobs, Redis::funnelUpstream accountStay under partners' limitsMust share state across workers

Fix / how to use it: edge or proxy limits generous per IP (abuse filter); gateway or application limits exact per identity (fairness and plans); outbound limits per upstream account. Keep the policies in one place in version control and document which layer owns which limit.

Testing limiters with a fake clock Good to know ​

In plain words: limiters depend on time, so inject the clock and move it in tests instead of sleeping.

Common misunderstanding: "time.Sleep(time.Second) in a test is fine." It makes the suite slow and flaky on loaded CI machines, and it cannot test boundaries such as 12:00:59.9 versus 12:01:00.1.

Definition: the limiter reads time through an interface (clock.Clock in Go; Laravel's now() / Carbon, controlled with $this->travel() and $this->freezeTime()); tests set the time, call the limiter, advance, and assert exact decisions and Retry-After values. For Redis scripts that call TIME, use an in-process Redis whose time you control (miniredis SetTime) or pass "now" as an argument.

text
     fake clock at 12:00:59.900
1    fire 100      -> fixed: 100, log: 100, counter: 100
2    Advance(200ms)
3    fire 100      -> fixed: +100 (boundary burst), log: +0, counter: +0
4    assert exact counts; the test runs in milliseconds

Real scenario: proving that a refactor kept the same burst; reproducing a customer's "I was limited after 59 requests" report; testing clock steps backwards (an NTP correction) so a bucket does not mint tokens.

What provides it:

ToolUse
Go: this chapter's clock.FakeAdvance, Set (including backwards)
Go: miniredis v2Runs Lua scripts in process; SetTime controls TIME
Laravel$this->travel(61)->seconds(), $this->freezeTime(), RateLimiter::clear($key)
NGINXlimit_req_dry_run on to observe in production without enforcing

Fix / how to use it: every package in this chapter's Go module takes a clock.Clock; see the tests imported in Go and RateLimitTest.php in Laravel.

Mechanics ​

Formulas ​

AlgorithmStateDecisionRetry-After
Token buckettokens, lasttokens = min(b, tokens + (now - last) x r); allow if tokens >= cost(cost - tokens) / r
GCRATATtat = max(TAT, now); allow if now >= tat + cost x T - T x btat + cost x T - T x b - now
Fixed windowcount per floor(now / w)allow if count + cost <= limitwindow end - now
Sliding logtimestampsdrop <= now - w; allow if len + cost <= limitoldest needed entry + w - now
Sliding counterprev, currprev x (1 - elapsed / w) + curr + cost <= limitsolve for elapsed, or window end
Admitted over t secondstoken bucket / GCRA: b + r x t; fixed window: up to 2 x limit in any window-length span; sliding log: limit

Memory per key ​

AlgorithmPer key1 million keys (back-of-envelope, excluding store overhead)
Fixed window1 integerabout 8 MB of values
Sliding counter2 integersabout 16 MB
Token bucketfloat + timestampabout 16 MB
GCRA1 timestampabout 8 MB
Sliding log, limit 1,000up to 1,000 timestampsup to about 8 GB
NGINX limit_req_zone"128 bytes on 64-bit platforms"1 MB zone holds "about 8 thousand 128-byte states", so about 125 MB per million keys

Redis adds per-key overhead (key name, expiry, encoding) on top of these values; measure with MEMORY USAGE on a sample.

Product knobs ​

ProductKnobMeaning
NGINXlimit_req_zone key zone=name:size rate=10r/sShared-memory zone; rate in r/s or r/m ("half-request per second is 30r/m")
NGINXlimit_req zone=name burst=N [nodelay | delay=N]Burst size; serve burst at once; two-stage after N
NGINXlimit_req_status, limit_req_log_level, limit_req_dry_runRejection status (default 503), log level (default error), observe only
Envoy localtoken_bucket.max_tokens, tokens_per_fill, fill_intervalBucket size and refill
Envoy locallocal_rate_limit_per_downstream_connection, local_cluster_rate_limit, enable_retry_after_headerPer connection vs per process; share across cluster members; add Retry-After
Envoy global (filter + ratelimit service)domain, descriptors, rate_limit.unit, requests_per_unit, shadow_mode, failure_mode_denyPolicy tree in the rate limit service; shadow evaluation; fail-closed
envoyproxy/ratelimitREDIS_PERSECOND, LocalCacheSizeInBytes, REDIS_PIPELINE_WINDOWSeparate Redis for per-second limits; cache over-limit keys locally; write buffering
Kong rate-limitingsecond...year, policy: local | cluster | redis, sync_rate, hide_client_headersLimits, counter store, sync frequency (0 = synchronous)
AWS API GatewayThrottling rate, throttling burst, quota (usage plan), method-level throttlesToken bucket targets, best effort
CloudflareCharacteristics, period, requests per period, duration (mitigation timeout), actionPeriods from 10 s to 86,400 s
LaravelLimit::perSecond/perMinute/perMinutes/perHour/perDay, by, after, response, Limit::none()Named limiters for throttle:name
Laravelthrottle:60,1, throttleWithRedis(), RateLimited, RateLimitedWithRedis, releaseAfter, dontReleaseInline limits; Redis Lua limiter; job limiter
Go x/time/rateNewLimiter(r, b), Every(d), AllowN, ReserveN, WaitN, SetLimit, SetBurst, TokensIn-process token bucket
redis-cellCL.THROTTLE key max_burst count period [quantity]GCRA as one command

Error messages and signals you will actually see ​

SourceText or signal
NGINX error loglimiting requests, excess: 1.000 by zone "mylimit", client: ... (delays are logged one level lower)
NGINX variable$limit_req_status: PASSED, DELAYED, REJECTED, DELAYED_DRY_RUN, REJECTED_DRY_RUN
LaravelIlluminate\Http\Exceptions\ThrottleRequestsException: Too Many Attempts.
LaravelMissingRateLimiterException when throttle:name refers to an undefined limiter
EnvoyResponse header x-envoy-ratelimited on locally limited responses
Kong{ "message": "API rate limit exceeded" } with 429
CloudflareVisitors see "error 1015"
RedisNOSCRIPT on EVALSHA before the script is loaded (go-redis Script.Run falls back to EVAL)
Redis ClusterCross-slot errors when one script touches keys in different hash slots

Go ​

The Go module (academy/rate-limiting-algorithms, go 1.24) has one package per idea. Everything takes a clock.Clock, so every test is deterministic. Dependencies: github.com/redis/go-redis/v9 v9.7.3, github.com/alicebob/miniredis/v2 v2.34.0 (tests only) and golang.org/x/time v0.11.0, pinned so the module keeps the go 1.24 directive.

Before ​

A per-process map, a ticker that resets it every minute, the left-most X-Forwarded-For as the key and a 403 without hints:

go
// Before: the limiter most teams write first. It compiles, it "works" on a
// laptop, and every line below is a design problem the chapter fixes.
package main

import (
	"log"
	"net/http"
	"strings"
	"sync"
	"time"
)

var (
	mu     sync.Mutex
	counts = map[string]int{} // per process: 4 replicas = 4x the limit
)

const perMinute = 100

func limited(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Trusts the left-most X-Forwarded-For entry, which any client can set.
		ip := strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0]
		if ip == "" {
			ip = r.RemoteAddr // includes the port: every connection is a new key
		}
		mu.Lock()
		counts[ip]++
		n := counts[ip]
		mu.Unlock()
		if n > perMinute {
			// Wrong status, no Retry-After, no RateLimit fields: clients can
			// only guess, so they retry immediately.
			http.Error(w, "forbidden", http.StatusForbidden)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func main() {
	// Fixed window reset by a ticker: 2x the limit passes across each reset,
	// and the map grows with every address ever seen during the minute.
	go func() {
		for range time.Tick(time.Minute) {
			mu.Lock()
			counts = map[string]int{}
			mu.Unlock()
		}
	}()
	http.Handle("/v1/", limited(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Write([]byte("ok\n"))
	})))
	log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

After ​

The clock and the common decision type. Every limiter returns Decision{Allowed, Limit, Remaining, RetryAfter, ResetAfter}.

go
// Package clock lets limiters read time through an interface so tests can
// move time forward deterministically instead of sleeping.
package clock

import (
	"sync"
	"time"
)

// Clock returns the current time.
type Clock interface {
	Now() time.Time
}

// Real reads the wall clock (monotonic reading included).
type Real struct{}

// Now returns time.Now().
func (Real) Now() time.Time { return time.Now() }

// Fake is a manually advanced clock for tests. It is safe for concurrent use.
type Fake struct {
	mu sync.Mutex
	t  time.Time
}

// NewFake returns a fake clock frozen at t.
func NewFake(t time.Time) *Fake { return &Fake{t: t} }

// Now returns the frozen time.
func (f *Fake) Now() time.Time {
	f.mu.Lock()
	defer f.mu.Unlock()
	return f.t
}

// Advance moves the clock forward by d.
func (f *Fake) Advance(d time.Duration) {
	f.mu.Lock()
	f.t = f.t.Add(d)
	f.mu.Unlock()
}

// Set jumps to t (it may move backwards, to test clock-skew handling).
func (f *Fake) Set(t time.Time) {
	f.mu.Lock()
	f.t = t
	f.mu.Unlock()
}
go
// Package limit holds the types every limiter in this module returns, so the
// HTTP middleware can work with any algorithm.
package limit

import (
	"context"
	"errors"
	"time"
)

// Decision is the answer to "may this request go through now?".
type Decision struct {
	Allowed    bool          // true: serve the request
	Limit      int           // quota of the policy (burst or window quota)
	Remaining  int           // whole units still available after this decision
	RetryAfter time.Duration // when Allowed is false: wait at least this long
	ResetAfter time.Duration // time until the quota is fully restored
}

// Limiter is implemented by every algorithm (in memory or Redis-backed).
// cost is the number of units the request consumes (1 for plain counting).
type Limiter interface {
	Allow(ctx context.Context, key string, cost int) (Decision, error)
}

// ErrCostTooHigh means the request can never pass: its cost exceeds the burst.
var ErrCostTooHigh = errors.New("limit: cost exceeds burst capacity")

Token bucket with lazy refill and its tests (burst, refill, cost, clock going backwards, sweeping full buckets):

go
// Package tokenbucket is a per-key token bucket with lazy refill: no
// background goroutine; tokens are recomputed from elapsed time on each call.
package tokenbucket

import (
	"context"
	"math"
	"sync"
	"time"

	"academy/rate-limiting-algorithms/clock"
	"academy/rate-limiting-algorithms/limit"
)

type bucket struct {
	tokens float64
	last   time.Time
}

// Limiter allows a sustained rate of `rate` units per second and bursts of up
// to `burst` units. A new key starts with a full bucket.
type Limiter struct {
	mu      sync.Mutex
	clk     clock.Clock
	rate    float64 // refill rate, tokens per second
	burst   float64 // bucket capacity
	buckets map[string]*bucket
}

// New returns a limiter refilling `perSecond` tokens per second up to `burst`.
func New(clk clock.Clock, perSecond float64, burst int) *Limiter {
	return &Limiter{clk: clk, rate: perSecond, burst: float64(burst), buckets: map[string]*bucket{}}
}

// refill applies lazy refill: tokens = min(burst, tokens + elapsed*rate).
func (l *Limiter) refill(b *bucket, now time.Time) {
	elapsed := now.Sub(b.last).Seconds()
	if elapsed < 0 { // clock went backwards: do not mint or remove tokens
		elapsed = 0
	}
	b.tokens = math.Min(l.burst, b.tokens+elapsed*l.rate)
	b.last = now
}

// Allow takes `cost` tokens from the bucket of key if they are available.
func (l *Limiter) Allow(_ context.Context, key string, cost int) (limit.Decision, error) {
	if float64(cost) > l.burst {
		return limit.Decision{Limit: int(l.burst)}, limit.ErrCostTooHigh
	}
	now := l.clk.Now()
	l.mu.Lock()
	defer l.mu.Unlock()
	b, ok := l.buckets[key]
	if !ok {
		b = &bucket{tokens: l.burst, last: now}
		l.buckets[key] = b
	}
	l.refill(b, now)
	d := limit.Decision{Limit: int(l.burst)}
	if b.tokens >= float64(cost) {
		b.tokens -= float64(cost)
		d.Allowed = true
	} else {
		missing := float64(cost) - b.tokens
		d.RetryAfter = seconds(missing / l.rate)
	}
	d.Remaining = int(math.Floor(b.tokens))
	d.ResetAfter = seconds((l.burst - b.tokens) / l.rate)
	return d, nil
}

// Sweep deletes buckets that have refilled completely. A full bucket behaves
// exactly like a missing one, so this bounds memory without changing results.
func (l *Limiter) Sweep() int {
	now := l.clk.Now()
	l.mu.Lock()
	defer l.mu.Unlock()
	n := 0
	for k, b := range l.buckets {
		l.refill(b, now)
		if b.tokens >= l.burst {
			delete(l.buckets, k)
			n++
		}
	}
	return n
}

func seconds(s float64) time.Duration {
	return time.Duration(math.Ceil(s * float64(time.Second)))
}
go
package tokenbucket

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/rate-limiting-algorithms/clock"
	"academy/rate-limiting-algorithms/limit"
)

var t0 = time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)

func TestBurstThenSteadyRate(t *testing.T) {
	clk := clock.NewFake(t0)
	l := New(clk, 2, 5) // 2 tokens/s, burst 5
	ctx := context.Background()

	for i := 0; i < 5; i++ { // the whole burst passes at once
		if d, _ := l.Allow(ctx, "user:7", 1); !d.Allowed {
			t.Fatalf("request %d rejected inside burst", i+1)
		}
	}
	d, _ := l.Allow(ctx, "user:7", 1)
	if d.Allowed || d.RetryAfter != 500*time.Millisecond {
		t.Fatalf("6th request: allowed=%v retry=%v, want rejected with 500ms", d.Allowed, d.RetryAfter)
	}
	clk.Advance(500 * time.Millisecond) // one token refilled
	if d, _ := l.Allow(ctx, "user:7", 1); !d.Allowed || d.Remaining != 0 {
		t.Fatalf("after refill: %+v", d)
	}
	if d, _ := l.Allow(ctx, "user:8", 1); !d.Allowed || d.Remaining != 4 {
		t.Fatalf("other key must have its own bucket: %+v", d)
	}
}

func TestCostAndCap(t *testing.T) {
	clk := clock.NewFake(t0)
	l := New(clk, 10, 20)
	ctx := context.Background()
	if d, _ := l.Allow(ctx, "k", 15); !d.Allowed || d.Remaining != 5 {
		t.Fatalf("cost 15: %+v", d)
	}
	clk.Advance(time.Hour) // refill never exceeds the burst
	if d, _ := l.Allow(ctx, "k", 1); d.Remaining != 19 {
		t.Fatalf("bucket overfilled: %+v", d)
	}
	if _, err := l.Allow(ctx, "k", 21); !errors.Is(err, limit.ErrCostTooHigh) {
		t.Fatalf("cost above burst must be an error, got %v", err)
	}
}

func TestClockBackwardsDoesNotMintTokens(t *testing.T) {
	clk := clock.NewFake(t0)
	l := New(clk, 1, 1)
	ctx := context.Background()
	l.Allow(ctx, "k", 1)
	clk.Set(t0.Add(-time.Hour))
	if d, _ := l.Allow(ctx, "k", 1); d.Allowed {
		t.Fatal("a clock step backwards must not refill the bucket")
	}
}

func TestSweepDropsFullBuckets(t *testing.T) {
	clk := clock.NewFake(t0)
	l := New(clk, 1, 3)
	ctx := context.Background()
	l.Allow(ctx, "a", 1)
	l.Allow(ctx, "b", 3)
	clk.Advance(1 * time.Second) // a is full again, b has 1 of 3
	if n := l.Sweep(); n != 1 {
		t.Fatalf("swept %d buckets, want 1", n)
	}
}

GCRA, with a test that it makes the same decisions as the token bucket:

go
// Package gcra implements the Generic Cell Rate Algorithm: a leaky bucket
// "as a meter" that stores one timestamp per key, the theoretical arrival
// time (TAT), instead of a token count.
package gcra

import (
	"context"
	"sync"
	"time"

	"academy/rate-limiting-algorithms/clock"
	"academy/rate-limiting-algorithms/limit"
)

// Limiter admits `burst` requests at once and then one request every
// emission interval T = period / count.
type Limiter struct {
	mu    sync.Mutex
	clk   clock.Clock
	t     time.Duration // emission interval T
	dvt   time.Duration // delay variation tolerance = T * burst
	burst int
	tat   map[string]time.Time
}

// New allows `count` requests per `period` with bursts of up to `burst`.
func New(clk clock.Clock, count int, period time.Duration, burst int) *Limiter {
	t := period / time.Duration(count)
	return &Limiter{clk: clk, t: t, dvt: t * time.Duration(burst), burst: burst, tat: map[string]time.Time{}}
}

// Allow applies GCRA for a request that costs `cost` emission intervals.
//
//	tat     = max(stored TAT, now)
//	newTAT  = tat + cost*T
//	allowAt = newTAT - DVT
//	now < allowAt  -> reject, retry after allowAt-now
//	otherwise      -> store newTAT, allow
func (l *Limiter) Allow(_ context.Context, key string, cost int) (limit.Decision, error) {
	if cost > l.burst {
		return limit.Decision{Limit: l.burst}, limit.ErrCostTooHigh
	}
	now := l.clk.Now()
	l.mu.Lock()
	defer l.mu.Unlock()

	tat, ok := l.tat[key]
	if !ok || tat.Before(now) {
		tat = now
	}
	newTAT := tat.Add(time.Duration(cost) * l.t)
	allowAt := newTAT.Add(-l.dvt)
	d := limit.Decision{Limit: l.burst}
	if now.Before(allowAt) {
		d.RetryAfter = allowAt.Sub(now)
		d.ResetAfter = tat.Sub(now)
		d.Remaining = int((l.dvt - tat.Sub(now)) / l.t)
		return d, nil
	}
	l.tat[key] = newTAT
	d.Allowed = true
	d.ResetAfter = newTAT.Sub(now)
	d.Remaining = int((l.dvt - newTAT.Sub(now)) / l.t)
	return d, nil
}
go
package gcra

import (
	"context"
	"testing"
	"time"

	"academy/rate-limiting-algorithms/clock"
	"academy/rate-limiting-algorithms/tokenbucket"
)

var t0 = time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)

func TestBurstThenEmissionInterval(t *testing.T) {
	clk := clock.NewFake(t0)
	l := New(clk, 1, time.Second, 3) // 1 req/s, burst 3
	ctx := context.Background()
	for i, want := range []int{2, 1, 0} {
		d, _ := l.Allow(ctx, "ip:203.0.113.9", 1)
		if !d.Allowed || d.Remaining != want {
			t.Fatalf("request %d: %+v, want allowed remaining=%d", i+1, d, want)
		}
	}
	d, _ := l.Allow(ctx, "ip:203.0.113.9", 1)
	if d.Allowed || d.RetryAfter != time.Second {
		t.Fatalf("4th request: %+v, want rejected, retry 1s", d)
	}
	clk.Advance(time.Second)
	if d, _ := l.Allow(ctx, "ip:203.0.113.9", 1); !d.Allowed {
		t.Fatalf("after one emission interval: %+v", d)
	}
}

// GCRA with burst b and interval T admits exactly the same sequence as a
// token bucket with capacity b and refill 1/T.
func TestEquivalentToTokenBucket(t *testing.T) {
	cg := clock.NewFake(t0)
	ct := clock.NewFake(t0)
	g := New(cg, 5, time.Second, 10)
	tb := tokenbucket.New(ct, 5, 10)
	ctx := context.Background()
	gaps := []time.Duration{0, 0, 10, 50, 0, 200, 0, 0, 0, 0, 0, 0, 0, 0, 900, 0, 0, 30, 400, 0}
	for round := 0; round < 5; round++ {
		for i, gap := range gaps {
			cg.Advance(gap * time.Millisecond)
			ct.Advance(gap * time.Millisecond)
			a, _ := g.Allow(ctx, "k", 1)
			b, _ := tb.Allow(ctx, "k", 1)
			if a.Allowed != b.Allowed {
				t.Fatalf("round %d step %d: gcra=%v bucket=%v", round, i, a.Allowed, b.Allowed)
			}
		}
	}
}

func TestIdleKeyResets(t *testing.T) {
	clk := clock.NewFake(t0)
	l := New(clk, 10, time.Minute, 2)
	ctx := context.Background()
	l.Allow(ctx, "k", 2)
	clk.Advance(time.Hour) // stored TAT is far in the past: treated as now
	if d, _ := l.Allow(ctx, "k", 2); !d.Allowed {
		t.Fatalf("idle key must get its full burst back: %+v", d)
	}
}

Fixed window, sliding window log and sliding window counter, with the boundary-burst test:

go
// Package window implements the three window counters: fixed window,
// sliding window log and sliding window counter (the Cloudflare
// approximation). Each allows `limit` units per `size`.
package window

import (
	"context"
	"sync"
	"time"

	"academy/rate-limiting-algorithms/clock"
	"academy/rate-limiting-algorithms/limit"
)

// Fixed counts per calendar window ([12:00:00, 12:01:00) ...). One integer
// per key; allows up to 2x the limit across a window boundary.
type Fixed struct {
	mu     sync.Mutex
	clk    clock.Clock
	limit  int
	size   time.Duration
	counts map[string]fixedState
}

type fixedState struct {
	start time.Time
	n     int
}

// NewFixed returns a fixed-window limiter.
func NewFixed(clk clock.Clock, limit int, size time.Duration) *Fixed {
	return &Fixed{clk: clk, limit: limit, size: size, counts: map[string]fixedState{}}
}

// Allow counts the request in the current window if it fits.
func (f *Fixed) Allow(_ context.Context, key string, cost int) (limit.Decision, error) {
	now := f.clk.Now()
	start := now.Truncate(f.size)
	f.mu.Lock()
	defer f.mu.Unlock()
	s := f.counts[key]
	if !s.start.Equal(start) {
		s = fixedState{start: start}
	}
	d := limit.Decision{Limit: f.limit, ResetAfter: start.Add(f.size).Sub(now)}
	if s.n+cost <= f.limit {
		s.n += cost
		d.Allowed = true
	} else {
		d.RetryAfter = d.ResetAfter
	}
	f.counts[key] = s
	d.Remaining = f.limit - s.n
	return d, nil
}

// Log keeps one timestamp per admitted unit: exact, memory O(limit) per key.
type Log struct {
	mu    sync.Mutex
	clk   clock.Clock
	limit int
	size  time.Duration
	logs  map[string][]time.Time
}

// NewLog returns a sliding-window-log limiter.
func NewLog(clk clock.Clock, limit int, size time.Duration) *Log {
	return &Log{clk: clk, limit: limit, size: size, logs: map[string][]time.Time{}}
}

// Allow drops entries older than now-size, then admits if room is left.
func (l *Log) Allow(_ context.Context, key string, cost int) (limit.Decision, error) {
	now := l.clk.Now()
	l.mu.Lock()
	defer l.mu.Unlock()
	entries := l.logs[key]
	cut := 0
	for cut < len(entries) && !entries[cut].After(now.Add(-l.size)) {
		cut++
	}
	entries = entries[cut:]
	d := limit.Decision{Limit: l.limit}
	if len(entries)+cost <= l.limit {
		for i := 0; i < cost; i++ {
			entries = append(entries, now)
		}
		d.Allowed = true
	} else {
		// the oldest entries that must expire before `cost` units fit
		d.RetryAfter = entries[len(entries)+cost-l.limit-1].Add(l.size).Sub(now)
	}
	l.logs[key] = entries
	d.Remaining = l.limit - len(entries)
	if len(entries) > 0 {
		d.ResetAfter = entries[len(entries)-1].Add(l.size).Sub(now)
	}
	return d, nil
}

// Entries reports how many timestamps are stored for key (memory cost).
func (l *Log) Entries(key string) int {
	l.mu.Lock()
	defer l.mu.Unlock()
	return len(l.logs[key])
}

// Counter keeps two integers per key (previous and current fixed window) and
// estimates the sliding count as prev*(1-elapsed/size) + curr.
type Counter struct {
	mu    sync.Mutex
	clk   clock.Clock
	limit int
	size  time.Duration
	state map[string]counterState
}

type counterState struct {
	start      time.Time // start of the current fixed window
	prev, curr int
}

// NewCounter returns a sliding-window-counter limiter.
func NewCounter(clk clock.Clock, limit int, size time.Duration) *Counter {
	return &Counter{clk: clk, limit: limit, size: size, state: map[string]counterState{}}
}

// Allow admits the request if the weighted estimate plus cost fits.
func (c *Counter) Allow(_ context.Context, key string, cost int) (limit.Decision, error) {
	now := c.clk.Now()
	start := now.Truncate(c.size)
	c.mu.Lock()
	defer c.mu.Unlock()
	s := c.state[key]
	switch {
	case s.start.Equal(start):
	case s.start.Add(c.size).Equal(start): // moved into the next window
		s = counterState{start: start, prev: s.curr}
	default: // idle for more than a full window
		s = counterState{start: start}
	}
	weight := 1 - float64(now.Sub(start))/float64(c.size)
	estimate := float64(s.prev)*weight + float64(s.curr)
	d := limit.Decision{Limit: c.limit, ResetAfter: start.Add(c.size).Sub(now)}
	if estimate+float64(cost) <= float64(c.limit) {
		s.curr += cost
		estimate += float64(cost)
		d.Allowed = true
	} else {
		d.RetryAfter = c.retryAfter(s, now, start, cost)
	}
	c.state[key] = s
	d.Remaining = max(0, c.limit-int(estimate+0.999999))
	return d, nil
}

// retryAfter finds when the previous window's weight has decayed enough.
func (c *Counter) retryAfter(s counterState, now, start time.Time, cost int) time.Duration {
	if s.prev == 0 || s.curr+cost > c.limit {
		return start.Add(c.size).Sub(now) // only the next window helps
	}
	// prev*(1-x) + curr + cost <= limit  =>  x >= 1 - (limit-curr-cost)/prev
	x := 1 - float64(c.limit-s.curr-cost)/float64(s.prev)
	at := start.Add(time.Duration(x * float64(c.size)))
	if at.Before(now) {
		return 0
	}
	return at.Sub(now)
}
go
package window

import (
	"context"
	"testing"
	"time"

	"academy/rate-limiting-algorithms/clock"
	"academy/rate-limiting-algorithms/limit"
)

var t0 = time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)

// fire sends n requests at the current fake time and counts the admitted ones.
func fire(l limit.Limiter, n int) int {
	ok := 0
	for i := 0; i < n; i++ {
		if d, _ := l.Allow(context.Background(), "k", 1); d.Allowed {
			ok++
		}
	}
	return ok
}

// 100 requests/minute. A client sends 100 at 12:00:59.9 and 100 at 12:01:00.1.
func TestWindowBoundaryBurst(t *testing.T) {
	cases := []struct {
		name string
		mk   func(clock.Clock) limit.Limiter
		want int // admitted in the 200 ms around the boundary
	}{
		{"fixed", func(c clock.Clock) limit.Limiter { return NewFixed(c, 100, time.Minute) }, 200},
		{"log", func(c clock.Clock) limit.Limiter { return NewLog(c, 100, time.Minute) }, 100},
		{"counter", func(c clock.Clock) limit.Limiter { return NewCounter(c, 100, time.Minute) }, 100},
	}
	for _, tc := range cases {
		clk := clock.NewFake(t0.Add(59*time.Second + 900*time.Millisecond))
		l := tc.mk(clk)
		got := fire(l, 100)
		clk.Advance(200 * time.Millisecond)
		got += fire(l, 100)
		if got != tc.want {
			t.Errorf("%s: admitted %d, want %d", tc.name, got, tc.want)
		}
	}
}

func TestSlidingCounterRecoversGradually(t *testing.T) {
	clk := clock.NewFake(t0)
	c := NewCounter(clk, 60, time.Minute)
	if got := fire(c, 60); got != 60 {
		t.Fatalf("first window admitted %d", got)
	}
	clk.Advance(time.Minute + 15*time.Second) // 25% into the next window
	// estimate = 60*0.75 + 0 = 45, so 15 more fit
	if got := fire(c, 30); got != 15 {
		t.Fatalf("admitted %d at 25%% of next window, want 15", got)
	}
}

func TestLogMemoryAndRetryAfter(t *testing.T) {
	clk := clock.NewFake(t0)
	l := NewLog(clk, 3, 10*time.Second)
	fire(l, 1)
	clk.Advance(4 * time.Second)
	fire(l, 2)
	d, _ := l.Allow(context.Background(), "k", 1)
	if d.Allowed || d.RetryAfter != 6*time.Second {
		t.Fatalf("got %+v, want rejected with retry 6s (first entry expires)", d)
	}
	if n := l.Entries("k"); n != 3 {
		t.Fatalf("stored %d timestamps, want 3", n)
	}
}

func TestFixedRetryAfterIsWindowEnd(t *testing.T) {
	clk := clock.NewFake(t0.Add(45 * time.Second))
	f := NewFixed(clk, 1, time.Minute)
	fire(f, 1)
	d, _ := f.Allow(context.Background(), "k", 1)
	if d.Allowed || d.RetryAfter != 15*time.Second {
		t.Fatalf("got %+v", d)
	}
}

Hierarchical limits, two-phase so a rejection never burns tokens of another tier:

go
// Package hierarchy applies several token-bucket tiers to one request
// (global, tenant, user, endpoint) and takes tokens from all of them or none.
package hierarchy

import (
	"math"
	"sync"
	"time"

	"academy/rate-limiting-algorithms/clock"
)

// Request carries the identities a tier can key on.
type Request struct {
	Tenant, User, Endpoint string
}

// Tier is one level of the hierarchy.
type Tier struct {
	Name      string
	PerSecond float64
	Burst     float64
	Key       func(Request) string // "" means the tier does not apply
}

type bucket struct {
	tokens float64
	last   time.Time
}

// Limiter evaluates all tiers under one lock so a rejection by a lower tier
// never burns tokens of a higher tier.
type Limiter struct {
	mu      sync.Mutex
	clk     clock.Clock
	tiers   []Tier
	buckets map[string]*bucket
}

// New builds a hierarchy; order the tiers from widest to narrowest.
func New(clk clock.Clock, tiers ...Tier) *Limiter {
	return &Limiter{clk: clk, tiers: tiers, buckets: map[string]*bucket{}}
}

// Result names the tier that rejected the request ("" when allowed).
type Result struct {
	Allowed    bool
	RejectedBy string
	RetryAfter time.Duration
}

// Allow is two-phase: check every applicable tier, then consume from all.
func (l *Limiter) Allow(r Request, cost float64) Result {
	now := l.clk.Now()
	l.mu.Lock()
	defer l.mu.Unlock()
	type hit struct {
		b *bucket
		t Tier
	}
	hits := make([]hit, 0, len(l.tiers))
	for _, t := range l.tiers {
		k := t.Key(r)
		if k == "" {
			continue
		}
		id := t.Name + "|" + k
		b, ok := l.buckets[id]
		if !ok {
			b = &bucket{tokens: t.Burst, last: now}
			l.buckets[id] = b
		}
		if el := now.Sub(b.last).Seconds(); el > 0 {
			b.tokens = math.Min(t.Burst, b.tokens+el*t.PerSecond)
		}
		b.last = now
		if b.tokens < cost {
			wait := (cost - b.tokens) / t.PerSecond
			return Result{RejectedBy: t.Name, RetryAfter: time.Duration(math.Ceil(wait * float64(time.Second)))}
		}
		hits = append(hits, hit{b, t})
	}
	for _, h := range hits {
		h.b.tokens -= cost
	}
	return Result{Allowed: true}
}
go
package hierarchy

import (
	"testing"
	"time"

	"academy/rate-limiting-algorithms/clock"
)

func tiers() []Tier {
	return []Tier{
		{Name: "global", PerSecond: 1000, Burst: 1000, Key: func(Request) string { return "all" }},
		{Name: "tenant", PerSecond: 100, Burst: 100, Key: func(r Request) string { return r.Tenant }},
		{Name: "user", PerSecond: 10, Burst: 20, Key: func(r Request) string { return r.Tenant + "/" + r.User }},
		{Name: "endpoint", PerSecond: 1, Burst: 2, Key: func(r Request) string {
			if r.Endpoint == "POST /exports" { // only expensive endpoints get a tier
				return r.Tenant + "/" + r.User + "/" + r.Endpoint
			}
			return ""
		}},
	}
}

func TestNarrowestTierRejectsFirst(t *testing.T) {
	l := New(clock.NewFake(time.Unix(0, 0)), tiers()...)
	exp := Request{Tenant: "acme", User: "u1", Endpoint: "POST /exports"}
	l.Allow(exp, 1)
	l.Allow(exp, 1)
	res := l.Allow(exp, 1)
	if res.Allowed || res.RejectedBy != "endpoint" || res.RetryAfter != time.Second {
		t.Fatalf("got %+v", res)
	}
	// the same user can still call cheap endpoints
	if res := l.Allow(Request{Tenant: "acme", User: "u1", Endpoint: "GET /orders"}, 1); !res.Allowed {
		t.Fatalf("cheap endpoint rejected: %+v", res)
	}
}

func TestTenantCapSharedByUsers(t *testing.T) {
	l := New(clock.NewFake(time.Unix(0, 0)), tiers()...)
	allowed := 0
	for u := 0; u < 10; u++ { // 10 users x 20 burst = 200 wanted, tenant allows 100
		for i := 0; i < 20; i++ {
			if l.Allow(Request{Tenant: "acme", User: string(rune('a' + u))}, 1).Allowed {
				allowed++
			}
		}
	}
	if allowed != 100 {
		t.Fatalf("tenant admitted %d, want 100", allowed)
	}
}

func TestRejectionDoesNotBurnHigherTiers(t *testing.T) {
	l := New(clock.NewFake(time.Unix(0, 0)), tiers()...)
	exp := Request{Tenant: "t2", User: "u", Endpoint: "POST /exports"}
	for i := 0; i < 50; i++ {
		l.Allow(exp, 1) // 2 pass, 48 rejected by the endpoint tier
	}
	ok := 0
	for i := 0; i < 20; i++ {
		if l.Allow(Request{Tenant: "t2", User: "u"}, 1).Allowed {
			ok++
		}
	}
	if ok != 18 { // the user tier lost only the 2 admitted requests
		t.Fatalf("user tier admitted %d, want 18", ok)
	}
}

Redis-backed limiters with Lua (go:embed loads the scripts; redis.NewScript(...).Run uses EVALSHA and falls back to EVAL). The GCRA script reads Redis TIME; the fixed-window script fixes the INCR + EXPIRE race:

lua
-- GCRA in one atomic script. Time comes from the Redis server (TIME), so
-- application servers with skewed clocks still agree.
-- KEYS[1] = limiter key
-- ARGV[1] = emission interval T in microseconds
-- ARGV[2] = delay variation tolerance (T * burst) in microseconds
-- ARGV[3] = cost (number of emission intervals this request uses)
-- returns {allowed (0|1), remaining, retry_after_us, reset_after_us}
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000000 + tonumber(t[2])
local interval = tonumber(ARGV[1])
local dvt = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])

local tat = tonumber(redis.call('GET', KEYS[1])) or now
if tat < now then
  tat = now
end
local new_tat = tat + cost * interval
local allow_at = new_tat - dvt

if now < allow_at then
  local remaining = math.floor((dvt - (tat - now)) / interval)
  return {0, remaining, allow_at - now, tat - now}
end

-- the key expires exactly when it would be equivalent to "absent"
redis.call('SET', KEYS[1], new_tat, 'PX', math.ceil((new_tat - now) / 1000))
local remaining = math.floor((dvt - (new_tat - now)) / interval)
return {1, remaining, 0, new_tat - now}
lua
-- Fixed window with INCR and an expiry set in the same atomic step.
-- Without the script, a crash between INCR and EXPIRE leaves a key with no
-- TTL: the counter never resets and the client is limited forever.
-- KEYS[1] = counter key (one per window), ARGV[1] = window in ms, ARGV[2] = cost
local n = redis.call('INCRBY', KEYS[1], ARGV[2])
if n == tonumber(ARGV[2]) then
  redis.call('PEXPIRE', KEYS[1], ARGV[1])
end
return {n, redis.call('PTTL', KEYS[1])}
go
// Package redislimiter is a cluster-wide limiter: every application instance
// asks one Redis (or one Redis Cluster shard per key) and the decision is made
// atomically inside a Lua script.
package redislimiter

import (
	"context"
	_ "embed"
	"fmt"
	"strconv"
	"time"

	"github.com/redis/go-redis/v9"

	"academy/rate-limiting-algorithms/limit"
)

//go:embed gcra.lua
var gcraSource string

//go:embed fixed.lua
var fixedSource string

var (
	gcraScript  = redis.NewScript(gcraSource)
	fixedScript = redis.NewScript(fixedSource)
)

// GCRA is a Redis-backed GCRA limiter: `count` per `period`, burst `burst`.
type GCRA struct {
	rdb      redis.Scripter
	prefix   string
	interval time.Duration
	burst    int
}

// NewGCRA builds the limiter. Keys are stored as prefix + key.
func NewGCRA(rdb redis.Scripter, prefix string, count int, period time.Duration, burst int) *GCRA {
	return &GCRA{rdb: rdb, prefix: prefix, interval: period / time.Duration(count), burst: burst}
}

// Allow runs the script with EVALSHA, falling back to EVAL on NOSCRIPT.
func (g *GCRA) Allow(ctx context.Context, key string, cost int) (limit.Decision, error) {
	if cost > g.burst {
		return limit.Decision{Limit: g.burst}, limit.ErrCostTooHigh
	}
	us := g.interval.Microseconds()
	res, err := gcraScript.Run(ctx, g.rdb, []string{g.prefix + key},
		us, us*int64(g.burst), cost).Int64Slice()
	if err != nil {
		return limit.Decision{}, fmt.Errorf("redislimiter: gcra: %w", err)
	}
	return limit.Decision{
		Allowed:    res[0] == 1,
		Limit:      g.burst,
		Remaining:  int(res[1]),
		RetryAfter: time.Duration(res[2]) * time.Microsecond,
		ResetAfter: time.Duration(res[3]) * time.Microsecond,
	}, nil
}

// Fixed is a Redis fixed-window counter (INCRBY + PEXPIRE in one script).
type Fixed struct {
	rdb    redis.Scripter
	prefix string
	limit  int
	window time.Duration
	now    func() time.Time
}

// NewFixed builds a fixed-window limiter. now picks the window; pass
// time.Now in production and a fake clock's Now in tests.
func NewFixed(rdb redis.Scripter, prefix string, limit int, window time.Duration, now func() time.Time) *Fixed {
	return &Fixed{rdb: rdb, prefix: prefix, limit: limit, window: window, now: now}
}

// Allow counts first and decides second: the counter can exceed the limit,
// which is harmless because the key expires with the window.
func (f *Fixed) Allow(ctx context.Context, key string, cost int) (limit.Decision, error) {
	win := f.now().UnixMilli() / f.window.Milliseconds()
	k := f.prefix + key + ":" + strconv.FormatInt(win, 10)
	res, err := fixedScript.Run(ctx, f.rdb, []string{k}, f.window.Milliseconds(), cost).Int64Slice()
	if err != nil {
		return limit.Decision{}, fmt.Errorf("redislimiter: fixed: %w", err)
	}
	n, ttl := int(res[0]), time.Duration(res[1])*time.Millisecond
	d := limit.Decision{Limit: f.limit, Remaining: max(0, f.limit-n), ResetAfter: ttl}
	if n <= f.limit {
		d.Allowed = true
	} else {
		d.RetryAfter = ttl
	}
	return d, nil
}
go
package redislimiter

import (
	"context"
	"testing"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/redis/go-redis/v9"
)

// miniredis is an in-process Redis that runs Lua scripts, so these tests need
// no server. Its TIME follows the fake time set with SetTime.
func setup(t *testing.T) (*miniredis.Miniredis, *redis.Client) {
	t.Helper()
	mr := miniredis.RunT(t)
	mr.SetTime(time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC))
	return mr, redis.NewClient(&redis.Options{Addr: mr.Addr()})
}

func TestGCRAOverRedis(t *testing.T) {
	mr, rdb := setup(t)
	ctx := context.Background()
	g := NewGCRA(rdb, "rl:gcra:", 10, time.Second, 5) // 10/s, burst 5

	for i := 0; i < 5; i++ {
		if d, err := g.Allow(ctx, "key-1", 1); err != nil || !d.Allowed {
			t.Fatalf("burst request %d: %+v %v", i+1, d, err)
		}
	}
	d, err := g.Allow(ctx, "key-1", 1)
	if err != nil || d.Allowed || d.RetryAfter != 100*time.Millisecond {
		t.Fatalf("6th: %+v %v, want rejected with 100ms", d, err)
	}
	mr.SetTime(time.Date(2026, 11, 26, 12, 0, 0, int(100*time.Millisecond), time.UTC))
	if d, _ := g.Allow(ctx, "key-1", 1); !d.Allowed {
		t.Fatalf("after 100ms: %+v", d)
	}
	if ttl := mr.TTL("rl:gcra:key-1"); ttl <= 0 || ttl > time.Second {
		t.Fatalf("key TTL %v: the key must expire when it equals absent", ttl)
	}
}

func TestFixedWindowSetsExpiryAtomically(t *testing.T) {
	mr, rdb := setup(t)
	ctx := context.Background()
	now := time.Date(2026, 11, 26, 12, 0, 30, 0, time.UTC)
	f := NewFixed(rdb, "rl:fw:", 3, time.Minute, func() time.Time { return now })
	for i := 0; i < 3; i++ {
		if d, _ := f.Allow(ctx, "ip:198.51.100.7", 1); !d.Allowed {
			t.Fatalf("request %d rejected", i+1)
		}
	}
	d, _ := f.Allow(ctx, "ip:198.51.100.7", 1)
	if d.Allowed {
		t.Fatal("4th request must be rejected")
	}
	for _, k := range mr.Keys() {
		if mr.TTL(k) <= 0 {
			t.Fatalf("key %s has no TTL", k)
		}
	}
}

Local counting with periodic sync (approximate global limit). The test measures the overshoot: 380 admitted against a global 300 with three nodes and 40 requests per node between syncs (the bound is 300 + 3 x 40 = 420):

go
// Package localsync is an approximate global limit: each node decides from
// local memory and pushes its counts to a shared store every sync interval.
// The hot path never waits for the network; the price is bounded overshoot.
package localsync

import (
	"context"
	"strconv"
	"sync"
	"time"

	"academy/rate-limiting-algorithms/clock"
)

// Store adds delta to the global counter of key in the given window and
// returns the new global total (Redis: INCRBY on key:window with an expiry).
type Store interface {
	IncrBy(ctx context.Context, key string, window int64, delta int64) (int64, error)
}

type state struct {
	window  int64 // index of the fixed window this state belongs to
	global  int64 // last global total seen at sync time
	pending int64 // admitted locally since the last sync
}

// Node is one application instance.
type Node struct {
	mu    sync.Mutex
	clk   clock.Clock
	store Store
	limit int64
	size  time.Duration
	keys  map[string]*state
}

// NewNode allows about `limit` requests per `size` across all nodes.
func NewNode(clk clock.Clock, store Store, limit int64, size time.Duration) *Node {
	return &Node{clk: clk, store: store, limit: limit, size: size, keys: map[string]*state{}}
}

func (n *Node) current(key string) *state {
	w := n.clk.Now().UnixNano() / int64(n.size)
	s, ok := n.keys[key]
	if !ok || s.window != w {
		s = &state{window: w}
		n.keys[key] = s
	}
	return s
}

// Allow decides locally: global total from the last sync plus local pending.
func (n *Node) Allow(key string) bool {
	n.mu.Lock()
	defer n.mu.Unlock()
	s := n.current(key)
	if s.global+s.pending >= n.limit {
		return false
	}
	s.pending++
	return true
}

// Sync pushes pending counts and pulls the global totals. Run it from a
// ticker (every 100 ms to 1 s). On store errors the counts stay pending.
func (n *Node) Sync(ctx context.Context) error {
	n.mu.Lock()
	type job struct {
		key   string
		s     *state
		delta int64
	}
	jobs := make([]job, 0, len(n.keys))
	for k, s := range n.keys {
		jobs = append(jobs, job{k, s, s.pending})
		s.pending = 0
	}
	n.mu.Unlock()

	var firstErr error
	for _, j := range jobs {
		total, err := n.store.IncrBy(ctx, j.key, j.s.window, j.delta)
		n.mu.Lock()
		if err != nil {
			j.s.pending += j.delta // retry on the next sync
			if firstErr == nil {
				firstErr = err
			}
		} else if total > j.s.global {
			j.s.global = total
		}
		n.mu.Unlock()
	}
	return firstErr
}

// MemStore is an in-memory Store for tests and the lab.
type MemStore struct {
	mu sync.Mutex
	m  map[string]int64
}

// NewMemStore returns an empty store.
func NewMemStore() *MemStore { return &MemStore{m: map[string]int64{}} }

// IncrBy implements Store.
func (m *MemStore) IncrBy(_ context.Context, key string, window int64, delta int64) (int64, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	k := key + "@" + strconv.FormatInt(window, 10)
	m.m[k] += delta
	return m.m[k], nil
}
go
package localsync

import (
	"context"
	"testing"
	"time"

	"academy/rate-limiting-algorithms/clock"
)

// Three nodes share a limit of 300/min. Traffic is balanced.
func TestOvershootIsBoundedBySyncInterval(t *testing.T) {
	clk := clock.NewFake(time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC))
	store := NewMemStore()
	nodes := []*Node{
		NewNode(clk, store, 300, time.Minute),
		NewNode(clk, store, 300, time.Minute),
		NewNode(clk, store, 300, time.Minute),
	}
	ctx := context.Background()
	admitted := 0
	// 10 sync rounds; between syncs each node receives 40 requests.
	for round := 0; round < 10; round++ {
		for _, n := range nodes {
			for i := 0; i < 40; i++ {
				if n.Allow("tenant:acme") {
					admitted++
				}
			}
		}
		for _, n := range nodes {
			if err := n.Sync(ctx); err != nil {
				t.Fatal(err)
			}
		}
		clk.Advance(time.Second)
	}
	// Exact would be 300. Worst case is limit + nodes*perSyncTraffic = 300 + 3*40.
	if admitted < 300 || admitted > 420 {
		t.Fatalf("admitted %d, want between 300 and 420", admitted)
	}
	t.Logf("admitted %d of 1200 against a global limit of 300", admitted)
}

func TestWithoutSyncEachNodeAdmitsTheFullLimit(t *testing.T) {
	clk := clock.NewFake(time.Unix(0, 0))
	store := NewMemStore()
	a, b := NewNode(clk, store, 10, time.Minute), NewNode(clk, store, 10, time.Minute)
	n := 0
	for i := 0; i < 20; i++ {
		if a.Allow("k") {
			n++
		}
		if b.Allow("k") {
			n++
		}
	}
	if n != 20 { // the failure mode of "local only": limit x number of nodes
		t.Fatalf("admitted %d, want 20", n)
	}
}

HTTP middleware: key selection with trusted proxies and IPv6 /64, cost, RateLimit-Policy / RateLimit / Retry-After, Problem Details, fail-open and fail-closed:

go
// Package httplimit is net/http middleware around any limit.Limiter: it picks
// the key, applies the cost, writes RateLimit-Policy / RateLimit / Retry-After
// and chooses between fail-open and fail-closed when the limiter is down.
package httplimit

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"log/slog"
	"math"
	"net"
	"net/http"
	"net/netip"
	"strings"
	"time"

	"academy/rate-limiting-algorithms/limit"
)

// Options configures one policy.
type Options struct {
	Policy   string        // policy name in the headers, e.g. "default"
	Quota    int           // advertised quota (q)
	Window   time.Duration // advertised window (w)
	Limiter  limit.Limiter
	Key      func(*http.Request) string // nil: DefaultKey with no trusted proxies
	Cost     func(*http.Request) int    // nil: every request costs 1
	FailOpen bool                       // limiter error: serve (true) or 503 (false)
	Timeout  time.Duration              // budget for the limiter call (default 50 ms)
	Log      *slog.Logger
}

type userKey struct{}

// WithUser is what an authentication middleware would call after it has
// verified the caller; the limiter then keys on the user, not the IP.
func WithUser(r *http.Request, id string) *http.Request {
	return r.WithContext(context.WithValue(r.Context(), userKey{}, id))
}

// DefaultKey prefers a verified identity over the network address:
// API key (hashed, never stored raw), then user, then client IP.
func DefaultKey(trusted []netip.Prefix) func(*http.Request) string {
	return func(r *http.Request) string {
		if k := r.Header.Get("X-Api-Key"); k != "" {
			sum := sha256.Sum256([]byte(k))
			return "key:" + hex.EncodeToString(sum[:8])
		}
		if u, ok := r.Context().Value(userKey{}).(string); ok && u != "" {
			return "user:" + u
		}
		return "ip:" + IPKey(ClientIP(r, trusted))
	}
}

// ClientIP returns the peer address, or, when the peer is a trusted proxy,
// the right-most X-Forwarded-For entry that is not itself a trusted proxy.
// Left-most entries are client-controlled and are never trusted.
func ClientIP(r *http.Request, trusted []netip.Prefix) netip.Addr {
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		host = r.RemoteAddr
	}
	peer, err := netip.ParseAddr(host)
	if err != nil {
		return netip.Addr{}
	}
	peer = peer.Unmap()
	if !isTrusted(peer, trusted) {
		return peer
	}
	hops := strings.Split(strings.Join(r.Header.Values("X-Forwarded-For"), ","), ",")
	for i := len(hops) - 1; i >= 0; i-- {
		a, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
		if err != nil {
			return peer // malformed chain: fall back to the proxy itself
		}
		a = a.Unmap()
		if !isTrusted(a, trusted) {
			return a
		}
	}
	return peer
}

func isTrusted(a netip.Addr, trusted []netip.Prefix) bool {
	for _, p := range trusted {
		if p.Contains(a) {
			return true
		}
	}
	return false
}

// IPKey groups IPv6 clients by /64 (one customer site usually gets a /64 or
// larger, so per-address limits are trivial to bypass); IPv4 stays per address.
func IPKey(a netip.Addr) string {
	if a.Is6() {
		p, _ := a.Prefix(64)
		return p.String()
	}
	return a.String()
}

// Middleware enforces the policy in front of next.
func Middleware(o Options, next http.Handler) http.Handler {
	if o.Key == nil {
		o.Key = DefaultKey(nil)
	}
	if o.Timeout == 0 {
		o.Timeout = 50 * time.Millisecond
	}
	if o.Log == nil {
		o.Log = slog.Default()
	}
	policy := fmt.Sprintf("%q;q=%d;w=%d", o.Policy, o.Quota, int(o.Window.Seconds()))
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cost := 1
		if o.Cost != nil {
			cost = o.Cost(r)
		}
		ctx, cancel := context.WithTimeout(r.Context(), o.Timeout)
		d, err := o.Limiter.Allow(ctx, o.Key(r), cost)
		cancel()
		switch {
		case errors.Is(err, limit.ErrCostTooHigh): // can never pass: not a 429
			problem(w, http.StatusBadRequest, "Request cost exceeds the maximum per request", 0)
			return
		case err != nil && o.FailOpen:
			o.Log.Warn("rate limiter unavailable, failing open", "policy", o.Policy, "err", err)
			next.ServeHTTP(w, r)
			return
		case err != nil:
			o.Log.Error("rate limiter unavailable, failing closed", "policy", o.Policy, "err", err)
			problem(w, http.StatusServiceUnavailable, "Rate limiter unavailable", time.Second)
			return
		}
		h := w.Header()
		h.Set("RateLimit-Policy", policy)
		h.Set("RateLimit", fmt.Sprintf("%q;a=%d;w=%d", o.Policy, d.Remaining, ceilSeconds(d.ResetAfter)))
		if !d.Allowed {
			problem(w, http.StatusTooManyRequests, "Too Many Requests", d.RetryAfter)
			return
		}
		next.ServeHTTP(w, r)
	})
}

// problem writes an RFC 9457 body and, when wait > 0, Retry-After in
// delay-seconds (rounded up, at least 1, so clients never retry early).
func problem(w http.ResponseWriter, status int, title string, wait time.Duration) {
	if wait > 0 {
		w.Header().Set("Retry-After", fmt.Sprint(max(1, ceilSeconds(wait))))
	}
	w.Header().Set("Content-Type", "application/problem+json")
	w.WriteHeader(status)
	fmt.Fprintf(w, `{"type":"about:blank","title":%q,"status":%d}`, title, status)
}

func ceilSeconds(d time.Duration) int {
	return int(math.Ceil(d.Seconds()))
}
go
package httplimit

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"net/netip"
	"testing"
	"time"

	"academy/rate-limiting-algorithms/clock"
	"academy/rate-limiting-algorithms/limit"
	"academy/rate-limiting-algorithms/tokenbucket"
)

var ok = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })

func get(h http.Handler, remote string, hdr map[string]string) *httptest.ResponseRecorder {
	r := httptest.NewRequest("GET", "/v1/orders", nil)
	r.RemoteAddr = remote
	for k, v := range hdr {
		r.Header.Set(k, v)
	}
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	return w
}

func TestHeadersAnd429(t *testing.T) {
	clk := clock.NewFake(time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC))
	h := Middleware(Options{Policy: "default", Quota: 2, Window: time.Second,
		Limiter: tokenbucket.New(clk, 2, 2)}, ok)

	w := get(h, "192.0.2.10:5000", nil)
	if w.Code != 204 || w.Header().Get("RateLimit") != `"default";a=1;w=1` {
		t.Fatalf("first: %d %q", w.Code, w.Header().Get("RateLimit"))
	}
	if got := w.Header().Get("RateLimit-Policy"); got != `"default";q=2;w=1` {
		t.Fatalf("policy header %q", got)
	}
	get(h, "192.0.2.10:5000", nil)
	w = get(h, "192.0.2.10:5000", nil)
	if w.Code != 429 || w.Header().Get("Retry-After") != "1" {
		t.Fatalf("third: %d Retry-After=%q", w.Code, w.Header().Get("Retry-After"))
	}
	if w := get(h, "192.0.2.11:5000", nil); w.Code != 204 {
		t.Fatalf("another IP must have its own bucket, got %d", w.Code)
	}
}

type down struct{}

func (down) Allow(context.Context, string, int) (limit.Decision, error) {
	return limit.Decision{}, errors.New("dial tcp 192.0.2.50:6379: i/o timeout")
}

func TestFailOpenAndFailClosed(t *testing.T) {
	open := Middleware(Options{Policy: "p", Limiter: down{}, FailOpen: true}, ok)
	if w := get(open, "192.0.2.1:1", nil); w.Code != 204 {
		t.Fatalf("fail-open served %d", w.Code)
	}
	closed := Middleware(Options{Policy: "p", Limiter: down{}}, ok)
	w := get(closed, "192.0.2.1:1", nil)
	if w.Code != 503 || w.Header().Get("Retry-After") != "1" {
		t.Fatalf("fail-closed served %d", w.Code)
	}
}

func TestSpoofedForwardedForIsIgnored(t *testing.T) {
	trusted := []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}
	// Peer is not a trusted proxy: X-Forwarded-For is attacker-controlled.
	r := httptest.NewRequest("GET", "/", nil)
	r.RemoteAddr = "198.51.100.23:4444"
	r.Header.Set("X-Forwarded-For", "203.0.113.99")
	if got := ClientIP(r, trusted).String(); got != "198.51.100.23" {
		t.Fatalf("got %s", got)
	}
	// Peer is our load balancer: take the right-most untrusted hop.
	r.RemoteAddr = "10.0.3.4:4444"
	r.Header.Set("X-Forwarded-For", "203.0.113.99, 198.51.100.23, 10.0.1.1")
	if got := ClientIP(r, trusted).String(); got != "198.51.100.23" {
		t.Fatalf("got %s, want the address our proxy saw", got)
	}
}

func TestKeysPreferIdentityAndGroupIPv6(t *testing.T) {
	key := DefaultKey(nil)
	r := httptest.NewRequest("GET", "/", nil)
	r.RemoteAddr = "[2001:db8:1:2:aaaa::1]:443"
	if got := key(r); got != "ip:2001:db8:1:2::/64" {
		t.Fatalf("ipv6 key %q", got)
	}
	if got := key(WithUser(r, "42")); got != "user:42" {
		t.Fatalf("user key %q", got)
	}
	r.Header.Set("X-Api-Key", "sk_test_example")
	if got := key(r); len(got) != 4+16 || got[:4] != "key:" {
		t.Fatalf("api key must be hashed, got %q", got)
	}
}

func TestCostAboveBurstIs400(t *testing.T) {
	clk := clock.NewFake(time.Unix(0, 0))
	h := Middleware(Options{Policy: "graphql", Quota: 100, Window: time.Minute,
		Limiter: tokenbucket.New(clk, 1, 100), Cost: func(*http.Request) int { return 500 }}, ok)
	if w := get(h, "192.0.2.1:1", nil); w.Code != 400 {
		t.Fatalf("got %d", w.Code)
	}
}

Concurrency limit (per-key semaphore plus a process-wide one; 429 vs 503):

go
// Package concurrency limits requests in flight, not requests per second:
// a per-key counting semaphore plus a global one.
package concurrency

import (
	"fmt"
	"net/http"
	"sync"
)

// Limiter allows at most perKey requests in flight per key and total overall.
type Limiter struct {
	mu       sync.Mutex
	perKey   int
	inflight map[string]int
	global   chan struct{} // buffered channel used as a semaphore
}

// New returns a limiter; total bounds the whole process (worker pool size).
func New(perKey, total int) *Limiter {
	return &Limiter{perKey: perKey, inflight: map[string]int{}, global: make(chan struct{}, total)}
}

// Acquire never blocks. It returns a release func, or ok=false and the reason.
func (l *Limiter) Acquire(key string) (release func(), ok bool, global bool) {
	select {
	case l.global <- struct{}{}:
	default:
		return nil, false, true // the process itself is full: shed load
	}
	l.mu.Lock()
	if l.inflight[key] >= l.perKey {
		l.mu.Unlock()
		<-l.global
		return nil, false, false // this caller already has enough in flight
	}
	l.inflight[key]++
	l.mu.Unlock()
	var once sync.Once
	return func() {
		once.Do(func() {
			l.mu.Lock()
			if l.inflight[key]--; l.inflight[key] == 0 {
				delete(l.inflight, key)
			}
			l.mu.Unlock()
			<-l.global
		})
	}, true, false
}

// Middleware answers 429 when one caller exceeds its share and 503 when the
// whole process is saturated (that second case is load shedding).
func (l *Limiter) Middleware(key func(*http.Request) string, next http.Handler) http.Handler {
	policy := fmt.Sprintf(`"inflight";q=%d;qu="concurrent-requests"`, l.perKey)
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		release, ok, global := l.Acquire(key(r))
		if !ok {
			w.Header().Set("Retry-After", "1")
			if global {
				http.Error(w, "server busy", http.StatusServiceUnavailable)
				return
			}
			w.Header().Set("RateLimit-Policy", policy)
			http.Error(w, "too many concurrent requests", http.StatusTooManyRequests)
			return
		}
		defer release()
		next.ServeHTTP(w, r)
	})
}

A polite client: x/time/rate pacing, Retry-After in both forms, full jitter, deadline-aware:

go
// Package client is the polite side of rate limiting: pace requests
// client-side with x/time/rate, honour Retry-After, and back off with full
// jitter when the server gives no hint.
package client

import (
	"context"
	"errors"
	"math/rand/v2"
	"net/http"
	"strconv"
	"time"

	"golang.org/x/time/rate"
)

// Client wraps an http.Client.
type Client struct {
	HTTP        *http.Client
	Pace        *rate.Limiter // client-side token bucket, e.g. rate.NewLimiter(8, 8)
	MaxAttempts int
	Base, Cap   time.Duration // backoff base and cap
	Sleep       func(context.Context, time.Duration) error
	Now         func() time.Time
}

// New returns a client that stays under perSecond and retries 429/503.
func New(perSecond float64, burst int) *Client {
	return &Client{
		HTTP:        &http.Client{Timeout: 10 * time.Second},
		Pace:        rate.NewLimiter(rate.Limit(perSecond), burst),
		MaxAttempts: 5,
		Base:        200 * time.Millisecond,
		Cap:         20 * time.Second,
		Sleep:       sleepCtx,
		Now:         time.Now,
	}
}

// ErrGaveUp is returned when the deadline or attempt budget is exhausted.
var ErrGaveUp = errors.New("client: rate limited, giving up")

// Do sends a request built by mk (a fresh request per attempt, so bodies can
// be re-read). Only idempotent requests should be retried this way.
func (c *Client) Do(ctx context.Context, mk func(context.Context) (*http.Request, error)) (*http.Response, error) {
	for attempt := 0; attempt < c.MaxAttempts; attempt++ {
		if err := c.Pace.Wait(ctx); err != nil { // blocks until a token is free
			return nil, err
		}
		req, err := mk(ctx)
		if err != nil {
			return nil, err
		}
		resp, err := c.HTTP.Do(req)
		if err != nil {
			return nil, err
		}
		if resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode != http.StatusServiceUnavailable {
			return resp, nil
		}
		wait, hinted := RetryAfter(resp.Header, c.Now())
		resp.Body.Close()
		if !hinted {
			wait = c.fullJitter(attempt)
		}
		if dl, ok := ctx.Deadline(); ok && c.Now().Add(wait).After(dl) {
			return nil, ErrGaveUp // waiting would miss the caller's deadline
		}
		if err := c.Sleep(ctx, wait); err != nil {
			return nil, err
		}
	}
	return nil, ErrGaveUp
}

// fullJitter: sleep = random_between(0, min(cap, base * 2^attempt)).
func (c *Client) fullJitter(attempt int) time.Duration {
	ceiling := min(c.Cap, c.Base<<attempt)
	return time.Duration(rand.Int64N(int64(ceiling) + 1))
}

// RetryAfter reads Retry-After (delay-seconds or HTTP-date, RFC 9110 10.2.3).
// Retry-After takes precedence over the RateLimit field, as the draft says.
func RetryAfter(h http.Header, now time.Time) (time.Duration, bool) {
	v := h.Get("Retry-After")
	if v == "" {
		return 0, false
	}
	if s, err := strconv.Atoi(v); err == nil && s >= 0 {
		return time.Duration(s) * time.Second, true
	}
	if t, err := http.ParseTime(v); err == nil {
		return max(0, t.Sub(now)), true
	}
	return 0, false
}

func sleepCtx(ctx context.Context, d time.Duration) error {
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-t.C:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}
go
package client

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func TestHonoursRetryAfter(t *testing.T) {
	calls := 0
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		calls++
		if calls < 3 {
			w.Header().Set("Retry-After", "2")
			w.WriteHeader(http.StatusTooManyRequests)
			return
		}
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()

	c := New(100, 10)
	var slept []time.Duration
	c.Sleep = func(_ context.Context, d time.Duration) error { slept = append(slept, d); return nil }

	resp, err := c.Do(context.Background(), func(ctx context.Context) (*http.Request, error) {
		return http.NewRequestWithContext(ctx, "GET", srv.URL, nil)
	})
	if err != nil || resp.StatusCode != 200 {
		t.Fatalf("err=%v", err)
	}
	resp.Body.Close()
	if len(slept) != 2 || slept[0] != 2*time.Second {
		t.Fatalf("slept %v, want [2s 2s]", slept)
	}
}

func TestGivesUpBeforeDeadline(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Retry-After", "30")
		w.WriteHeader(http.StatusTooManyRequests)
	}))
	defer srv.Close()
	c := New(100, 10)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_, err := c.Do(ctx, func(ctx context.Context) (*http.Request, error) {
		return http.NewRequestWithContext(ctx, "GET", srv.URL, nil)
	})
	if err != ErrGaveUp {
		t.Fatalf("err=%v, want ErrGaveUp without sleeping 30s", err)
	}
}

func TestRetryAfterForms(t *testing.T) {
	now := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)
	h := http.Header{}
	h.Set("Retry-After", "120")
	if d, ok := RetryAfter(h, now); !ok || d != 2*time.Minute {
		t.Fatalf("seconds form: %v %v", d, ok)
	}
	h.Set("Retry-After", "Thu, 26 Nov 2026 12:00:30 GMT")
	if d, ok := RetryAfter(h, now); !ok || d != 30*time.Second {
		t.Fatalf("date form: %v %v", d, ok)
	}
}

func TestFullJitterStaysUnderCap(t *testing.T) {
	c := New(1, 1)
	for a := 0; a < 20; a++ {
		if d := c.fullJitter(a); d < 0 || d > c.Cap {
			t.Fatalf("attempt %d: %v", a, d)
		}
	}
}

The Go angle ​

Go featureUse in rate limitingNote
golang.org/x/time/rateIn-process token bucket: Allow, Reserve, Wait, AllowNOne limiter per key needs a map and eviction; "The zero value is a valid Limiter, but it will reject all events"
rate.Sometimes"Do this at most once per interval" (log sampling)Not a request limiter
sync.Mutex + mapPer-key stateShard the map (by key hash) when one lock becomes contended
time.Time monotonic readingnow.Sub(last) is immune to wall-clock steps in one processNot across machines: use the store's clock (TIME)
github.com/redis/go-redis/v9redis.NewScript, Script.Run (EVALSHA with EVAL fallback)Use hash tags for Redis Cluster
github.com/go-redis/redis_rate/v10Ready-made GCRA on Redislimiter.Allow(ctx, key, redis_rate.PerSecond(10))
net/netipParse and mask client addresses (Prefix(64))Allocation-free, comparable
net/http/httptestMiddleware and client testsNo network
log/slogStructured logs for limiter errorsLog the policy and key hash, never the raw API key

Laravel ​

Before ​

A controller that reads a cache value, compares and writes it back: check-then-act, IP-only, sliding ban, wrong status:

php
<?php

namespace App\Http\Controllers\Before;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

// Before: a hand-rolled limit inside a controller.
class SendMessageController
{
    public function __invoke(Request $request): JsonResponse
    {
        // Keyed on the IP only: every user behind one office NAT or mobile
        // CGNAT address shares these 5 messages.
        $key = 'messages:'.$request->ip();

        // Check-then-act: two concurrent requests both read 4, both pass.
        $count = Cache::get($key, 0);

        if ($count >= 5) {
            // No Retry-After and a status clients do not treat as "slow down".
            return response()->json(['error' => 'limit'], 400);
        }

        // put() resets the TTL on every hit, so a steady sender is never
        // released: this is a sliding ban, not a window.
        Cache::put($key, $count + 1, now()->addMinute());

        // ... send the message ...

        return response()->json(['sent' => true]);
    }
}

After ​

Named limiters with RateLimiter::for and Limit::perMinute()->by(): per user or IP, hierarchical tenant/user/day, login, 404-only counting with after(), a custom response(), and a queue limiter:

php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Default API policy: per user when authenticated, per IP otherwise.
        RateLimiter::for('api', function (Request $request) {
            return $request->user()
                ? Limit::perMinute(120)->by('user:'.$request->user()->id)
                : Limit::perMinute(30)->by('ip:'.$request->ip());
        });

        // Hierarchical: a tenant-wide cap plus a per-user cap, evaluated in order.
        // Prefixes keep the two counters apart.
        RateLimiter::for('tenant-api', function (Request $request) {
            $user = $request->user();
            $perMinute = match ($user?->tenant?->plan) {
                'enterprise' => 6000,
                'pro' => 1200,
                default => 300,
            };

            return [
                Limit::perMinute($perMinute)->by('tenant:'.$user?->tenant_id),
                Limit::perMinute(200)->by('user:'.$user?->id),
                Limit::perDay(50_000)->by('tenant-day:'.$user?->tenant_id),
            ];
        });

        // Login: a global ceiling and a tight per-account limit, so one IP
        // cannot spray many accounts and many IPs cannot hammer one account.
        RateLimiter::for('login', function (Request $request) {
            return [
                Limit::perMinute(500),
                Limit::perMinute(5)->by('login:'.strtolower((string) $request->input('email'))),
                Limit::perMinute(20)->by('login-ip:'.$request->ip()),
            ];
        });

        // Only 404s count: stops ID enumeration without punishing normal use.
        RateLimiter::for('lookup', function (Request $request) {
            return Limit::perMinute(10)
                ->by($request->user()?->id ?: $request->ip())
                ->after(fn ($response) => $response->status() === 404);
        });

        // Expensive endpoint with a custom 429 body (headers are passed in).
        RateLimiter::for('exports', function (Request $request) {
            return Limit::perHour(10)
                ->by('exports:'.$request->user()?->id)
                ->response(function (Request $request, array $headers) {
                    return response()->json([
                        'type' => 'https://example.com/problems/rate-limited',
                        'title' => 'Export limit reached',
                        'status' => 429,
                        'retry_after' => $headers['Retry-After'] ?? null,
                    ], 429, $headers + ['Content-Type' => 'application/problem+json']);
                });
        });

        // Queue side: the CRM allows 100 calls per minute for our whole account.
        RateLimiter::for('crm', fn (object $job) => Limit::perMinute(100)->by('crm-account'));
    }
}

Bootstrap: throttleWithRedis() (atomic Lua instead of cache check-then-hit), trustProxies so $request->ip() is the client, one Problem Details shape for 429:

php
<?php

use App\Http\Middleware\GraphQLCostLimit;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Atomic Lua-based counting instead of the cache-based check-then-hit.
        $middleware->throttleWithRedis();

        // Without this, $request->ip() is the load balancer and every client
        // shares one bucket. Only list proxies you operate.
        $middleware->trustProxies(at: ['10.0.0.0/8']);

        $middleware->alias(['graphql.cost' => GraphQLCostLimit::class]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // One problem+json shape for every 429, keeping Retry-After and X-RateLimit-*.
        $exceptions->render(function (ThrottleRequestsException $e, Request $request) {
            if (! $request->expectsJson()) {
                return null;
            }

            return response()->json([
                'type' => 'about:blank',
                'title' => 'Too Many Requests',
                'status' => 429,
            ], 429, $e->getHeaders() + ['Content-Type' => 'application/problem+json']);
        });
    })
    ->create();

Routes with the throttle middleware:

php
<?php

use Illuminate\Support\Facades\Route;

Route::post('/login', fn () => null)->middleware('throttle:login');

Route::middleware(['auth:sanctum', 'throttle:tenant-api'])->group(function () {
    Route::get('/orders', fn () => null);
    Route::get('/orders/{order}', fn () => null)->middleware('throttle:lookup');
    Route::post('/exports', fn () => null)->middleware('throttle:exports');
    Route::post('/graphql', fn () => null)->middleware('graphql.cost');
});

// Inline limits without a named limiter: 60 attempts per 1 minute.
Route::get('/status', fn () => ['ok' => true])->middleware('throttle:60,1');

Cost-based limiting for GraphQL with atomic RateLimiter::increment($key, $decay, $cost), refund on rejection and draft -12 headers:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Symfony\Component\HttpFoundation\Response;

// Cost-based limiting: a GraphQL request consumes "points", not one unit.
class GraphQLCostLimit
{
    private const POINTS_PER_HOUR = 5000;

    private const MAX_POINTS_PER_QUERY = 500;

    public function handle(Request $request, Closure $next): Response
    {
        $cost = $this->estimate((string) $request->input('query', ''));

        if ($cost > self::MAX_POINTS_PER_QUERY) {
            // Can never succeed: reject as a bad request, not as 429.
            return response()->json(['title' => 'Query too expensive', 'cost' => $cost], 400);
        }

        $key = 'graphql:'.($request->user()?->id ?? $request->ip());

        // increment() is atomic on the redis, memcached and database stores,
        // so concurrent requests each see a distinct running total.
        $used = RateLimiter::increment($key, 3600, $cost);

        if ($used > self::POINTS_PER_HOUR) {
            RateLimiter::decrement($key, 3600, $cost); // refund: nothing was served

            $retryAfter = max(1, RateLimiter::availableIn($key));

            return response()->json(['title' => 'Point budget exhausted'], 429, [
                'Retry-After' => $retryAfter,
                'RateLimit-Policy' => '"graphql";q='.self::POINTS_PER_HOUR.';w=3600;qu="requests"',
                'RateLimit' => '"graphql";a=0;w='.$retryAfter,
            ]);
        }

        $response = $next($request);

        $response->headers->set('RateLimit-Policy', '"graphql";q='.self::POINTS_PER_HOUR.';w=3600');
        $response->headers->set('RateLimit', sprintf(
            '"graphql";a=%d;w=%d;c=%d',
            self::POINTS_PER_HOUR - $used,
            RateLimiter::availableIn($key),
            $cost,
        ));

        return $response;
    }

    /**
     * Rough cost: every connection asks for up to first/last N nodes; charge
     * one point per 100 requested nodes, minimum 1. A real server computes
     * this from the parsed query (webonyx/graphql-php query complexity).
     */
    private function estimate(string $query): int
    {
        preg_match_all('/\b(?:first|last)\s*:\s*(\d+)/', $query, $m);

        $nodes = 1;
        foreach ($m[1] as $n) {
            $nodes *= max(1, (int) $n); // nested connections multiply
        }

        return max(1, intdiv($nodes, 100));
    }
}

GCRA through Redis::eval (the same Lua as the Go module):

php
<?php

namespace App\RateLimiting;

use Illuminate\Support\Facades\Redis;

// GCRA in Redis: one key per client holding the theoretical arrival time.
// The script is the same one the Go module runs (redislimiter/gcra.lua).
class RedisGcra
{
    private const SCRIPT = <<<'LUA'
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000000 + tonumber(t[2])
local interval = tonumber(ARGV[1])
local dvt = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local tat = tonumber(redis.call('GET', KEYS[1])) or now
if tat < now then
  tat = now
end
local new_tat = tat + cost * interval
local allow_at = new_tat - dvt
if now < allow_at then
  local remaining = math.floor((dvt - (tat - now)) / interval)
  return {0, remaining, allow_at - now, tat - now}
end
redis.call('SET', KEYS[1], new_tat, 'PX', math.ceil((new_tat - now) / 1000))
local remaining = math.floor((dvt - (new_tat - now)) / interval)
return {1, remaining, 0, new_tat - now}
LUA;

    public function __construct(
        private readonly int $count,      // requests ...
        private readonly int $periodSeconds, // ... per period
        private readonly int $burst,
    ) {}

    /**
     * @return array{allowed: bool, remaining: int, retry_after: int, reset_after: int}
     */
    public function attempt(string $key, int $cost = 1): array
    {
        $intervalUs = intdiv($this->periodSeconds * 1_000_000, $this->count);

        [$allowed, $remaining, $retryUs, $resetUs] = Redis::eval(
            self::SCRIPT, 1, 'gcra:'.$key, $intervalUs, $intervalUs * $this->burst, $cost
        );

        return [
            'allowed' => $allowed === 1,
            'remaining' => (int) $remaining,
            'retry_after' => (int) ceil($retryUs / 1_000_000), // seconds, for Retry-After
            'reset_after' => (int) ceil($resetUs / 1_000_000),
        ];
    }
}

Outbound limits in a queued job: RateLimitedWithRedis releases the job instead of calling the CRM, Redis::funnel caps concurrent connections, the CRM's own Retry-After wins:

php
<?php

namespace App\Jobs;

use App\Models\Contact;
use DateTime;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Middleware\RateLimitedWithRedis;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;

// Outbound limiting: we are the client of a CRM that allows 100 calls/minute
// and 10 concurrent connections for our account.
class SyncContactToCrm implements ShouldQueue
{
    use Queueable;

    public function __construct(public Contact $contact) {}

    /**
     * The named 'crm' limiter (AppServiceProvider) releases the job back to
     * the queue with a delay instead of calling the CRM and getting a 429.
     */
    public function middleware(): array
    {
        return [new RateLimitedWithRedis('crm')];
    }

    // Releases count as attempts, so bound the job by time, not by tries.
    public function retryUntil(): DateTime
    {
        return now()->addHours(6);
    }

    public function handle(): void
    {
        // Concurrency limit (a semaphore in Redis), separate from the rate limit.
        Redis::funnel('crm-connections')->limit(10)->block(0)->then(function () {
            $response = Http::timeout(10)
                ->put('https://crm.example.com/v2/contacts/'.$this->contact->id, [
                    'email' => $this->contact->email,
                ]);

            if ($response->status() === 429) {
                // The CRM is the authority: wait as long as it asks.
                $this->release((int) ($response->header('Retry-After') ?: 60));

                return;
            }

            $response->throw();
        }, function () {
            $this->release(5); // all 10 slots busy
        });
    }
}

A durable monthly quota (PostgreSQL conditional upsert):

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Quotas (per month, billed) live in the database, not in the cache:
// they must survive a Redis flush and be auditable.
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('api_quota_usage', function (Blueprint $table) {
            $table->foreignId('tenant_id')->constrained();
            $table->char('period', 7); // '2026-11'
            $table->unsignedBigInteger('used')->default(0);
            $table->timestamps();
            $table->primary(['tenant_id', 'period']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('api_quota_usage');
    }
};
php
<?php

namespace App\Billing;

use Illuminate\Support\Facades\DB;

// Monthly quota with one atomic statement (PostgreSQL): the row is updated
// only if the new total still fits, so concurrent requests cannot overspend.
class QuotaLedger
{
    public function consume(int $tenantId, int $cost, int $quota): bool
    {
        if ($cost > $quota) {
            return false;
        }

        $row = DB::selectOne(<<<'SQL'
            INSERT INTO api_quota_usage (tenant_id, period, used, created_at, updated_at)
            VALUES (?, to_char(now(), 'YYYY-MM'), ?, now(), now())
            ON CONFLICT (tenant_id, period) DO UPDATE
                SET used = api_quota_usage.used + EXCLUDED.used, updated_at = now()
                WHERE api_quota_usage.used + EXCLUDED.used <= ?
            RETURNING used
            SQL, [$tenantId, $cost, $quota]);

        return $row !== null; // no row returned: the WHERE failed, quota exhausted
    }
}

Tests with Laravel's clock (freezeTime, travel):

php
<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;

// The test clock is Laravel's: travel() moves "now" without sleeping.
class RateLimitTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        Route::get('/_probe', fn () => 'ok')->middleware('throttle:3,1');
    }

    public function test_fourth_request_in_a_minute_gets_429_with_retry_after(): void
    {
        $this->freezeTime();

        foreach (range(1, 3) as $i) {
            $this->get('/_probe')
                ->assertOk()
                ->assertHeader('X-RateLimit-Limit', 3)
                ->assertHeader('X-RateLimit-Remaining', 3 - $i);
        }

        $this->get('/_probe')
            ->assertStatus(429)
            ->assertHeader('Retry-After', 60);

        $this->travel(61)->seconds();

        $this->get('/_probe')->assertOk();
    }

    public function test_attempt_counts_only_executed_callbacks(): void
    {
        $sent = 0;

        foreach (range(1, 7) as $ignored) {
            RateLimiter::attempt('send-message:7', 5, function () use (&$sent) {
                $sent++;
            });
        }

        $this->assertSame(5, $sent);
        $this->assertTrue(RateLimiter::tooManyAttempts('send-message:7', 5));
    }
}

The Laravel angle ​

Laravel 13 featureBehaviour (from the docs and the 13.x source)Note
RateLimiter facadeCounter + :timer key in the cache store (limiter key in config/cache.php selects the store)A fixed window anchored at the first hit
RateLimiter::attempt($key, $max, $callback, $decay)Checks tooManyAttempts, runs the callback, then hitNot atomic across concurrent callers
RateLimiter::increment($key, $decay, $amount)"incremented atomically" on redis, memcached and database storesUse its return value instead of check-then-increment
tooManyAttempts, remaining, availableIn, clear, decrementInspect, refund, resetavailableIn gives seconds for Retry-After
throttle middleware (ThrottleRequests)Check all limits, hit all, call next; 429 with headersSmall overshoot possible under concurrency
throttleWithRedis() (ThrottleRequestsWithRedis)DurationLimiter Lua: hash start/end/count, EXPIRE decay x 2Atomic per limit
Limit::perMinute(60)->by($key), arrays of limitsHierarchical limits, evaluated in orderPrefix by() values when they would collide
Limit::...->after(fn ($response) => ...)Count only some responses (404s, failed validation)Hits after the response
Limit::...->response(fn ($request, $headers) => ...)Custom 429 body, headers passed inKeep Retry-After
RateLimited / RateLimitedWithRedis job middlewareRelease with delay; releaseAfter(), dontRelease()Releases count as attempts: use retryUntil()
Redis::throttle() / Redis::funnel()Rate limiter / concurrency limiter builders on a Redis connectionfunnel()->limit(10)->releaseAfter(60)->block(0)
trustProxies(at: [...])Makes $request->ip() the real client behind your proxiesOtherwise every client shares the proxy's bucket

Solving the classic problems ​

Twice the limit at every window reset ​

SolutionHowAdvantageCost / limitation
Sliding window counterTwo counters, weighted2 integers, near-exactApproximation (~6% error measured)
GCRA / token bucketOne timestamp or token countExact rate + explicit burstBurst b must be chosen consciously
Sliding window logTimestampsExactMemory O(limit) per key
Add a short per-second limit next to the hourly oneTwo tiersKeeps the "per hour" contractTwo counters

Go: window.NewCounter or gcra.New; Laravel: throttleWithRedis() plus a second Limit::perSecond() tier, or RedisGcra.

An office, a campus or a CGNAT pool is limited as one user ​

SolutionHowAdvantageCost / limitation
Limit by identityAPI key, user, tenant after authenticationFairNeeds auth before the limiter
Generous per-IP, tight per-account on loginTwo tiersBrute force on one account still blockedDistributed guessing needs other signals
Edge characteristicsCloudflare "IP with NAT support", headers, cookie, JA3/JA4Separates clients behind one IPPlan-dependent features
IPv6 /64 groupingKey on the prefixStops address rotationMay group a small network's hosts

The limit is multiplied by the number of replicas ​

SolutionHowAdvantageCost / limitation
Central Redis + LuaOne atomic decision per requestExactExtra round trip, Redis on the path
Local sharelimit / N per instanceNo networkWrong when N changes or traffic is unbalanced
Local + syncPeriodic push/pullNo network on the hot pathBounded overshoot
Consistent-hash routingSame key to same instance (Kong's advice)Local counters become accurateRebalancing resets counters

Counters that never expire (INCR without EXPIRE) ​

Put INCRBY and PEXPIRE in one Lua script (fixed.lua) or in MULTI/EXEC, or use GCRA where every SET carries PX. Audit existing keys with TTL (a value of -1 means no expiry).

Redis is down ​

SolutionHowAdvantageCost / limitation
Fail-open + local fallback bucketTimeout 20 to 50 ms, then local x/time/rateAPI stays up, still some protectionLimit is per instance during the outage
Fail-closed for security limits503 + Retry-AfterGuessing stays impossibleThose endpoints are down
Redis replica / Sentinel / ClusterHA for the limiter storeFewer outagesFailover may lose recent counts (acceptable for limits)

Clients retry immediately and keep the bucket empty ​

Send Retry-After on every 429 and 503; publish the policy in RateLimit-Policy; ship SDKs that use full jitter and client-side pacing; for queue workers, release the job for the hinted delay instead of sleeping.

Spoofed X-Forwarded-For gives every request a fresh key ​

Trust X-Forwarded-For only when the peer is your proxy and read it from the right, skipping your own proxies (httplimit.ClientIP); in Laravel use trustProxies(at: ...) with exact ranges, never * on an internet-facing app.

One huge tenant makes one Redis key hot ​

Add a local token bucket in front (Envoy's two-stage pattern) so most rejections never reach Redis; cache "this key is over the limit until T" in memory (envoyproxy/ratelimit's local cache, Cloudflare's cached mitigation); split the tenant's counter into k sub-keys on different slots and sum them (Sharded Counters).

Expensive requests get through a request-count limit ​

Charge points (cost), cap the cost per request (400 when it can never fit), and return c in RateLimit; for long jobs add a concurrency limit.

Our own workers break a partner's limit ​

Treat the partner's limit as a shared resource: one Redis-backed limiter for the whole worker fleet (RateLimitedWithRedis('crm')), a funnel for concurrent connections, and always obey the partner's Retry-After.

Choosing ​

Which algorithm ​

SituationRecommendationExtra techniqueReason
General API limit per key, Redis availableGCRA or sliding window counter in one Lua scriptLocal token bucket in front at high QPSExact enough, one or two integers per key
Bursty but legitimate clients (page loads, app start)Token bucket / GCRA with explicit burstDocument burst in RateLimit-PolicyBurst is a first-class parameter
Proxy in front of a fixed worker poolNGINX limit_req with burst (+ nodelay)limit_req_status 429Cheap, shared memory per instance
Very small security limits (OTP, password reset)Sliding window logFail-closedExactness matters, memory is tiny
Quotas per day or monthFixed window in SQLShort-window limit in Redis tooDurable, auditable, billable
Expensive or variable requestsCost-based token bucketConcurrency limitFair by work, not by count
Smooth output required (downstream cannot take bursts)Leaky bucket as a queueSmall queue, timeoutsConverts bursts into delay

Which layer ​

NeedLayerProduct examples
Stop anonymous floods and brute force cheaplyEdge / reverse proxyCloudflare rules, NGINX limit_req
Per API key plans, no app codeAPI gatewayAWS API Gateway usage plans, Kong, Envoy global RLS
Per tenant, per plan, per costApplicationLaravel throttle + named limiters, Go middleware
Respect a partner's limitOutbound client / queuex/time/rate, RateLimitedWithRedis, Redis::funnel

Fail-open or fail-closed ​

Policy protectsChooseWhy
Fairness, general capacityFail-open + local fallbackA limiter outage must not be an API outage
Security (login, OTP, card checks)Fail-closedThe limit is the control
Money paid per call upstreamFail-closed or strict local fallbackUnbounded cost is worse than refusing

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One Laravel or Go process can keep limits in memory: x/time/rate per key in a map with eviction, or Laravel's RateLimiter on the array/file store for a single server. Example: a small SaaS on one VM limits login to 5 per minute per account with Limit::perMinute(5)->by(email) and puts NGINX limit_req per IP in front. The simplest correct version is already two layers.

Modular monolith: boundaries without the network ​

Several modules share the process and the cache. Give each module its own named limiters (billing:*, search:*), keep the key prefixes distinct, and keep one place where policies are defined (the service provider). Example: the search module has a cost-based limiter by result size; the billing module has a tight per-tenant limit on invoice exports; both use the same Redis store through throttleWithRedis(), and neither can starve the other because their keys and limits are separate.

Microservices: every arrow is a decision ​

Limits move to the gateway or the sidecar for external traffic, and to clients for internal traffic. Example flow: Envoy at the edge applies a local token bucket and then calls the global rate limit service (gRPC) with descriptors tenant=acme, route=/v1/exports; the service checks Redis and answers whether the descriptor is over its limit; Envoy returns 429 with Retry-After. Internally, the orders service calls inventory with a client-side x/time/rate limiter sized to inventory's capacity, and inventory protects itself with a concurrency limit and load shedding. Identity (tenant, user) must be propagated in headers so the gateway can key on it; the gateway must not trust those headers from outside.

Distributed data: replicas, caches, regions ​

A Redis primary with replicas can lose the last increments on failover: a client might get a few extra requests, which is acceptable for limits and not for quotas (keep those in SQL). In Redis Cluster, all keys of one script must share a slot (hash tag {tenant}). Across regions, a single global counter adds a cross-region round trip to every request; most designs enforce per region (cell-based) and accept that a client spread over three regions may get up to three times the per-region limit, or allocate each region a share. Clock skew between app servers is solved by using the store's clock (TIME) for GCRA. CDNs count per data center (Cloudflare: counters have a "per-data-center scope"), which is why the edge limit is generous and the precise limit lives behind it.

Scaling path: 1x, 10x, 100x ​

LoadDesignWhat changes
1x (one server, hundreds of req/s)In-memory limiter + NGINX per IPNothing shared
10x (several instances, thousands of req/s)Central Redis with one Lua script per decision; Laravel throttleWithRedisAtomic scripts, fail-open policy, hash tags
100x (fleets, tens of thousands of req/s, hot tenants)Two-stage: local token bucket + global service; local cache of over-limit keys; sharded hot keys; per-region cellsApproximate global limits, bounded overshoot, metrics per tier

Lab: the same traffic against every algorithm ​

  1. Run the Go tests (run on the host; all pass):
bash
cd docs/snippets/system-design/rate-limiting-algorithms/go
go test ./...
# ok  academy/rate-limiting-algorithms/client
# ok  academy/rate-limiting-algorithms/concurrency
# ok  academy/rate-limiting-algorithms/gcra
# ok  academy/rate-limiting-algorithms/hierarchy
# ok  academy/rate-limiting-algorithms/httplimit
# ok  academy/rate-limiting-algorithms/localsync
# ok  academy/rate-limiting-algorithms/redislimiter
# ok  academy/rate-limiting-algorithms/tokenbucket
# ok  academy/rate-limiting-algorithms/window
  1. Run the simulation (single-process Go program, run on the host; output copied verbatim). All policies mean "100 per minute"; bucket-style ones have burst 100.
go
// boundarysim replays the same traffic against every in-memory algorithm with
// a fake clock and prints how many requests each admits. Used by the lab.
package main

import (
	"context"
	"fmt"
	"time"

	"academy/rate-limiting-algorithms/clock"
	"academy/rate-limiting-algorithms/gcra"
	"academy/rate-limiting-algorithms/limit"
	"academy/rate-limiting-algorithms/tokenbucket"
	"academy/rate-limiting-algorithms/window"
)

type algo struct {
	name string
	mk   func(clock.Clock) limit.Limiter
}

// All policies mean "100 requests per minute"; the bucket-style ones allow a
// burst of 100 and refill 100/60 per second.
var algos = []algo{
	{"fixed window", func(c clock.Clock) limit.Limiter { return window.NewFixed(c, 100, time.Minute) }},
	{"sliding log", func(c clock.Clock) limit.Limiter { return window.NewLog(c, 100, time.Minute) }},
	{"sliding counter", func(c clock.Clock) limit.Limiter { return window.NewCounter(c, 100, time.Minute) }},
	{"token bucket", func(c clock.Clock) limit.Limiter { return tokenbucket.New(c, 100.0/60, 100) }},
	{"gcra", func(c clock.Clock) limit.Limiter { return gcra.New(c, 100, time.Minute, 100) }},
}

// scenario: at each offset from 12:00:00, send n requests.
type burst struct {
	at time.Duration
	n  int
}

func run(a algo, plan []burst) int {
	start := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)
	clk := clock.NewFake(start)
	l := a.mk(clk)
	ok := 0
	for _, b := range plan {
		clk.Set(start.Add(b.at))
		for i := 0; i < b.n; i++ {
			if d, _ := l.Allow(context.Background(), "client", 1); d.Allowed {
				ok++
			}
		}
	}
	return ok
}

func main() {
	boundary := []burst{{59*time.Second + 900*time.Millisecond, 100}, {60*time.Second + 100*time.Millisecond, 100}}
	var steady []burst // 3 requests every second for 2 minutes (360 requests)
	for s := 0; s < 120; s++ {
		steady = append(steady, burst{time.Duration(s) * time.Second, 3})
	}
	late := []burst{{30 * time.Second, 100}, {75 * time.Second, 100}} // burst, then another 45 s later

	fmt.Printf("%-16s %10s %10s %10s\n", "algorithm", "boundary", "steady", "45s-later")
	fmt.Printf("%-16s %10s %10s %10s\n", "", "(of 200)", "(of 360)", "(of 200)")
	for _, a := range algos {
		fmt.Printf("%-16s %10d %10d %10d\n", a.name, run(a, boundary), run(a, steady), run(a, late))
	}
}
text
algorithm          boundary     steady  45s-later
                   (of 200)   (of 360)   (of 200)
fixed window            200        200        200
sliding log             100        200        100
sliding counter         100        198        125
token bucket            100        298        175
gcra                    100        298        175

Read it: the fixed window admits both bursts around 12:01:00; the token bucket and GCRA admit the full burst plus the refill, 100 + 100/60 x 119 = 298 (the last requests arrive at t = 119 s), so a burst equal to the full minute quota doubles the first minute; the sliding counter is close to the exact log.

  1. NGINX burst and nodelay (expected, not run):
bash
# nginx.conf: limit_req_zone $binary_remote_addr zone=lab:1m rate=1r/s;
#             location / { limit_req zone=lab burst=5 nodelay; limit_req_status 429; }
for i in $(seq 1 8); do curl -s -o /dev/null -w '%{http_code} ' http://127.0.0.1:8080/; done; echo
# expected: 200 200 200 200 200 200 429 429   (1 + burst 5 served at once)
sleep 2; curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/
# expected: 200   (two slots freed)
  1. The INCR + EXPIRE race in redis-cli (expected, not run):
bash
redis-cli INCR rl:ip:198.51.100.7          # (integer) 1
# the client "crashes" here, EXPIRE is never sent
redis-cli TTL rl:ip:198.51.100.7           # (integer) -1   -> no expiry, the counter never resets
redis-cli EVAL "local n = redis.call('INCRBY', KEYS[1], ARGV[2]) if n == tonumber(ARGV[2]) then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end return n" 1 rl:ip:198.51.100.8 60000 1
# (integer) 1
redis-cli PTTL rl:ip:198.51.100.8          # (integer) 59998 or close
  1. Laravel throttle with a frozen clock (expected, not run):
bash
php artisan test --filter=RateLimitTest
# PASS  Tests\Feature\RateLimitTest
# ✓ fourth request in a minute gets 429 with retry after
# ✓ attempt counts only executed callbacks
  1. Check the headers on a running app (expected, not run):
bash
curl -si http://127.0.0.1:8000/api/status | grep -i -E '^(HTTP|x-ratelimit|retry-after)'
# HTTP/1.1 200 OK
# X-RateLimit-Limit: 60
# X-RateLimit-Remaining: 59

Common misconceptions ​

BeliefReality
"Rate limiting stops DDoS attacks."It stops abusive clients after the request is parsed; floods need edge protection (DDoS).
"100 per minute means never more than 100 in 60 s."True only for a sliding log; fixed windows allow 200 around a reset, token buckets allow b + r x t.
"Token bucket and leaky bucket behave differently."As meters they make the same decisions; only the queue variant differs, by adding delay.
"Per-IP limits are fair."NAT, CGNAT and proxies put many users behind one address; IPv6 lets one user use many.
"INCR then EXPIRE is safe because Redis is single-threaded."The pair is not atomic; a crash between them leaks a key with no TTL.
"Fail-closed is always safer."It turns a Redis outage into an API outage; reserve it for security limits.
"503 and 429 are interchangeable."429 is "you are too fast", 503 is "the server is overloaded"; dashboards and clients treat them differently.
"Retry-After is optional politeness."Without it clients guess and retry in lockstep; the IETF draft says it takes precedence over the RateLimit fields.
"Laravel's throttle is exact under concurrency."The cache-based middleware checks then hits; use throttleWithRedis() or RateLimiter::increment() for atomic counting.
"A rate limit also limits concurrency."Slow requests pile up at any rate; add a semaphore (Stripe's concurrent request limiter).
"Quotas can live in Redis only."Quotas are billing data: durable, auditable, resettable; keep them in SQL.
"The edge limit is enough."Edge counters are per data center and anonymous; precise per-tenant limits need the gateway or app.

Cheat sheet ​

TopicWhat to remember
Two knobsRate (sustained) and burst (instant); every algorithm encodes both
Token bucketmin(b, tokens + elapsed x r); lazy refill; delete full buckets
GCRAOne timestamp (TAT); T = period/count; DVT = T x burst; same as token bucket
Fixed windowCheap; up to 2x at the boundary; fine for quotas
Sliding counterprev x (1 - elapsed/w) + curr; ~6% error (Cloudflare)
Sliding logExact; memory O(limit) per key; small limits only
KeysIdentity first (API key, user, tenant); IP only for anonymous traffic; IPv6 /64
NAT / CGNATOne IP = many users; trusted proxies only; right-most untrusted XFF hop
RedisOne Lua script per decision; INCR + EXPIRE in one step; hash tags in Cluster; TIME for clocks
DistributedCentral (exact) → two-stage local + global → local + sync / cells (approximate)
FailureFail-open + local fallback for general limits; fail-closed for security limits
Responses429 + Retry-After (seconds, round up) + RateLimit/RateLimit-Policy; 503 for shedding
ClientsPace below the limit; obey Retry-After; full jitter; stop at the deadline
ProductsNGINX leaky bucket (503 default); Envoy local token bucket + global RLS (fail-open default); Kong local/cluster/redis; AWS usage plans; Cloudflare per data center
LaravelRateLimiter::for + Limit::perMinute()->by(); throttle:name; throttleWithRedis(); RateLimited jobs; Redis::funnel
TestsInject a clock; never sleep; test the boundary and clock steps

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A token bucket has r = 5/s and b = 10. A client sends 10 requests at once and then one request every 100 ms. How many of the next 20 requests pass? Important ​

Answer

Answer: After the burst the bucket is empty. Every 100 ms it gains 0.5 tokens, so every second request passes: 10 of the next 20 (one every 200 ms, matching the rate of 5/s).

2 — Why does a fixed window of 100/min allow 200 requests in 200 ms, and which two algorithms fix it with the least memory? Must-know ​

Answer

Answer: The counter resets at the window boundary, so 100 just before and 100 just after both fit. The sliding window counter (two integers) and GCRA (one timestamp) fix it; the sliding log fixes it too but stores one timestamp per request.

3 — Write the GCRA decision for a request of cost 1. Good to know ​

Answer

Answer: tat = max(TAT, now), new_tat = tat + T, allow_at = new_tat - T x burst. If now is before allow_at, reject with Retry-After = allow_at - now; otherwise store new_tat.

4 — Using Cloudflare's numbers (limit 50/min, 42 requests last minute, 18 in the current minute, 15 s elapsed), what is the estimate, and is the next request allowed? Good to know ​

Answer

Answer: 42 x 45/60 + 18 = 49.5. One more request makes 50.5, which is over 50 with the "estimate + cost must fit" rule used in this chapter (Cloudflare: "One more request during the next second and the rate limiter will start being very angry!").

5 — What goes wrong with INCR followed by EXPIRE as two commands, and how do you fix it? Must-know ​

Answer

Answer: If the client dies after INCR, the key has no TTL, so the counter never resets. Fix with a Lua script (EVAL/EVALSHA, executed atomically) or MULTI/EXEC, or use GCRA where every SET carries PX.

6 — Your Laravel app runs behind an AWS ALB and every anonymous user gets 429 at the same moment. Why? Must-know ​

Answer

Answer: Without trustProxies, $request->ip() is the load balancer's address, so all anonymous traffic shares one key. Configure trustProxies(at: [...]) with your proxy ranges.

7 — Envoy's global rate limit service times out. What does Envoy do by default, and how do you change it? Important ​

Answer

Answer: It allows the request (fail-open). Set failure_mode_deny: true to fail closed.

8 — When should a limiter answer 503 instead of 429? Must-know ​

Answer

Answer: When the reason is the whole system (overload, load shedding, or a fail-closed limiter outage), not one caller. NGINX answers 503 by default; set limit_req_status 429 for per-client limits.

9 — Three nodes count locally and sync every second; each sees 40 requests per second for one tenant whose global limit is 300 per minute. What is the worst-case overshoot? Important ​

Answer

Answer: Up to one sync interval of traffic per node beyond the limit: 3 x 40 = 120, so up to 420 admitted. The chapter's test measured 380.

10 — A response carries Retry-After: 10 and RateLimit: "default";a=0;w=4. How long should the client wait? Important ​

Answer

Answer: 10 seconds. The draft says Retry-After "MUST take precedence and the effective window MAY be ignored".

11 — Why is RateLimiter::attempt() not enough to enforce "exactly 5 messages" under concurrent requests, and what should you use? Important ​

Answer

Answer: It checks tooManyAttempts, runs the callback, then hits: two concurrent calls can both pass the check. Use the return value of RateLimiter::increment() (atomic on redis, memcached and database stores) or throttleWithRedis().

12 — A GraphQL query would cost 1,000 points and the per-query maximum is 500. Which status, and why not 429? Must-know ​

Answer

Answer: A 400-class error such as 400. Waiting will never make it fit, so a 429 with Retry-After would only cause pointless retries.

Glossary ​

TermMeaning
Rate limitingRestricting how often a caller (key) may perform an action within a time period
Token bucketBucket of capacity b refilled at rate r; each request takes tokens
BurstThe number of requests allowed at once (bucket capacity, NGINX burst)
Refill rateTokens added per second; the sustained rate
Lazy refillComputing tokens from elapsed time on each request instead of a background job
Leaky bucketBucket that drains at a constant rate; as a queue it delays, as a meter it decides
GCRAGeneric Cell Rate Algorithm: leaky bucket as a meter stored as one timestamp
Theoretical arrival time (TAT)GCRA's stored time at which the client is exactly on schedule
Emission interval (T)Time per request at the sustained rate, period / count
Delay variation tolerance (DVT)How far ahead of schedule a client may be, T x burst
Fixed windowCounter per calendar window, reset at the boundary
Window boundary burstUp to twice the limit admitted around a fixed-window reset
Sliding window logExact limiter storing one timestamp per admitted request
Sliding window counterApproximation weighting the previous window's count by its remaining overlap
Hierarchical limitsSeveral tiers (global, tenant, user, endpoint) applied to one request
Per-user / per-API-key / per-tenant / per-IP / per-endpointThe key dimension that defines who shares a bucket
Quota partitionIETF draft term for the division of capacity by key; pk parameter
NATNetwork address translation; many private hosts share one public address
CGNATCarrier-grade NAT: an ISP shares one public IPv4 among many subscribers
X-Forwarded-ForProxy header listing client and proxy addresses; only the hops your proxies appended are trustworthy
Trusted proxiesThe proxy ranges whose forwarding headers you accept (Laravel trustProxies)
Penalty boxTemporarily denying an address after abuse (RFC 6269)
Distributed rate limitOne limit enforced across many instances
RedisIn-memory data store used as the shared limiter state
Lua / EVAL / EVALSHARedis server-side scripting; a script executes atomically
INCR / INCRBYRedis atomic increment
EXPIRE / PEXPIRERedis key expiry in seconds / milliseconds
AtomicExecuted as one indivisible step; no other command interleaves
RaceA bug that depends on the interleaving of concurrent operations
MULTI / EXECRedis transaction block
Redis CellRedis module providing GCRA as CL.THROTTLE
Hash tag{...} part of a Redis Cluster key that forces keys into one slot
Sharded counterA hot counter split into several sub-counters summed on read
Local bucketPer-instance limiter state used without a network call
SyncPeriodic push of local counts and pull of global totals
Cell-basedSplitting a system into independent cells (PoP, region) that each enforce their share
GossipPeer-to-peer exchange of state between instances
Fail-openOn limiter failure, let requests through
Fail-closedOn limiter failure, reject requests (503)
Dark launch / shadow mode / dry runEvaluate a limiter and record decisions without enforcing
429 Too Many RequestsRFC 6585 status for rate limiting; must not be cached
Retry-AfterRFC 9110 header: delay-seconds or HTTP-date to wait
RateLimit-PolicyIETF draft header advertising quota policies (q, w, qu, pk)
RateLimitIETF draft header with the current service limit (a, w, c, pk)
RateLimit-Limit / RateLimit-Remaining / RateLimit-ResetEarlier draft (-05) header names, still sent by Kong and others
X-RateLimit-*Pre-standard vendor headers (Laravel, GitHub)
503 Service UnavailableServer temporarily overloaded; used for load shedding
BackoffWaiting longer between retries
JitterRandomness in the wait so clients do not retry in lockstep
Full jitterWait uniformly between 0 and the exponential backoff value
Adaptive throttlingClient-side rejection once requests exceed K x accepts (Google SRE)
limit_req / limit_req_zoneNGINX directives for leaky-bucket request limiting
nodelayNGINX option to serve a burst immediately while still accounting slots
Envoy rate limit servicegRPC service Envoy calls for global limits; reference implementation in Go with Redis
failure_mode_denyEnvoy option to fail closed when the rate limit service errors
Cloudflare rate limitingEdge rules counting requests per characteristic and period
API Gateway usage planAWS feature tying API keys to throttles and quotas
KongAPI gateway; rate-limiting plugin with local, cluster or redis policy
QuotaTotal allowed consumption over a long period (day, month)
Concurrency limitMaximum requests in flight per key or process
SemaphoreCounting permit mechanism used for concurrency limits
Cost-based limitRequests consume points according to their cost
Load sheddingDropping work based on system health, not caller identity
BackpressureSlowing producers to match consumer speed
Fake clockTest clock moved manually instead of sleeping
RateLimiter facadeLaravel's limiter API (for, attempt, increment, availableIn, clear)
throttle middlewareLaravel route middleware applying a named or inline limiter
Limit::perMinuteLaravel builder for a per-minute limit; by() sets the key
RateLimited job middlewareLaravel queue middleware that releases a job when its limiter is full
Redis::funnelLaravel Redis concurrency limiter builder
x/time/rateGo's token bucket package

References ​

Built by Morteza Negahi