How systems work

Rate limiters.

A rate limiter counts requests and says no once a caller has had enough: “at most 100 a minute per API key”. The no is an HTTP 429 Too Many Requests, usually with a Retry-After header saying when to come back.

The idea is simple. The details are not: what “a minute” means, whether a burst is fine, how ten servers agree on one count, and what callers do after the 429. Each choice changes who gets through, and this page shows each one happening.

In the labs after the walkthrough, every small square is one request in a simulation running in your browser. Time flows from right to left: new requests appear at the “now” line and slide away. Green got through, red got a 429. Requests that land close together stack into a column, so a burst looks like a tower. Under each timeline is the limiter itself: its counter, its log, its tokens or its queue. Click any square to follow that one request and read what happened to it.

00 The life of one request

Before the live labs, follow a single request through a rate limiter, from the moment it is sent to its answer. Step through at your own pace, or press Play all.

Mobile appClient · API key AOrders serviceDoes the real workRate limiterChecks each requestkey A4 of 4 tokenskey B4 of 4 tokensKey A’s bucketholds up to 4 tokensRefills 1 token every secondsends requestsdoes the real workone record per API key ↑

Step 1 of 10

Meet the pieces

A rate limiter sits in front of a service and checks every request before it gets in. It keeps one small record per caller, here a bucket of tokens for each API key. The service behind it only sees what the limiter lets through.

01 Why limit at all

A service can only do so much work a second. Without a limit, any one caller can use all of it: a script stuck in a loop, a scraper, a customer’s batch job. Everyone else then waits or fails, though they did nothing wrong.

A limiter turns away the extra before it reaches the service. Where you count matters as much as how much. One limit for everyone protects the service but not the other callers: the noisy one still takes most of the allowance. One limit per key (a user, an API key, an IP address) gives each caller a fair share.

Requests, last 5 snowClient A · 2/srequests from one callerClient B · 20/srequests from one callerClient C · 2/srequests from one callerNo limiterEvery request goes straight to the service.ServiceHandles 10 a second. 0 waiting, 0 dropped.
A got through
–
B got through
–
Dropped (503)
0
429s
0

Click any square to follow that one request.

Three clients and a service that handles 10 requests a second. Client B sends 20 a second.
Limiter
    Try this. With the limiter off, the service’s queue is full and most of A’s requests are dropped. Pick “One for everyone” (10 a second): nothing is dropped, but A still gets 429s, because B uses up the window first. Pick “One per client” (4 a second each): once the service has worked off its backlog, A gets through and only B sees red.

    Limit per caller to keep things fair, and keep a global limit as well if the service has a hard ceiling. The rest of this page uses one key so you can see the algorithm itself.

    02 Fixed window counter

    The simplest limiter cuts time into windows (0–1 s, 1–2 s, …) and keeps one counter for the current one. Each request adds one. Past the limit, 429. When the window ends the counter goes back to zero. It needs one number per key and is easy to build, for example with Redis INCR and EXPIRE.

    Its weak spot is the edge. A caller can send a full window’s worth just before a boundary and another just after. Each window sees only its own share, so both batches pass: twice the limit in a fraction of a second.

    Requests, last 5 snowClient A · 1/srequests from one caller0 of 50 of 50 of 50 of 50 of 5Fixed window: 0 of 5 usedOne counter for the window 0–1 s. It resets to zero in 1.00 s.
    Allowed
    0
    429s
    0
    Most in any 1 s
    0

    Click any square to follow that one request.

    5 requests per 1-second window. Dashed lines are window boundaries; the count above each window is how many it let through.
      Try this. Press “Burst at the window edge”. Five arrive just before a boundary and five just after. Each window lets its own five through (one slot may already be used by the steady request), and the red box marks the span where 10 got through within one second: twice the limit. Compare “Send 10 at once” in the middle of a window: five at most pass.

      A fixed window limits each window, not each second. Worst case, a caller gets twice the limit in a short span.

      03 Sliding window log

      To fix the edge, stop using clock windows. Keep a log of when each allowed request happened. For a new request, drop timestamps older than one window, count what is left, and allow if it is under the limit. The window now slides with every request, so there is no edge to exploit.

      The cost is memory. The log holds one timestamp per allowed request, per key. At 1,000 requests a minute per key that is up to 1,000 entries for each key. In Redis this is often a sorted set: add the time, remove old ones, count.

      Requests, last 5 snowClient A · 1/srequests from one callerlast 1 sSliding log: 0 of 5 in the last 1 sIt keeps one timestamp per allowed request. The log is empty.−1 snow
      Allowed
      0
      429s
      0
      Most in any 1 s
      0
      Timestamps stored
      0

      Click any square to follow that one request.

      The shaded band is the last second: the log. Each mark under the timeline is one stored timestamp.
      Algorithm
        Try this. Press “Burst at the window edge”. Five pass, then the rest are red until the oldest timestamp leaves the band. “Most in any 1 s” never goes over 5. Switch to Fixed window and press it again to see the difference. Raise the limit to 20 and watch “Timestamps stored” grow with it.

        The sliding log is exact, and its memory grows with the limit. Fine for small limits, costly for large ones.

        04 Sliding window counter

        A middle way keeps just two counters: this window’s and the last one’s. It assumes last window’s requests were spread evenly and counts the part of them that still falls inside a window ending now.

        Thirty percent into the current window, the sliding window still covers 70% of the last one. With 5 last window and 2 so far, the estimate is 5 × 0.7 + 2 = 5.5. If allowing one more would take the estimate over the limit, the answer is 429.

        Requests, last 5 snowClient A · 2/srequests from one caller0 of 50 of 50 of 50 of 50 of 5Sliding counter: estimate 0.0 of 5Last window's 0 × 100% still in view + this window's 0 = 0.0. Two numbers, no log.limit 5
        Allowed
        0
        429s
        0
        Most in any 1 s
        0
        Numbers stored
        2

        Click any square to follow that one request.

        Purple is last window's count, weighted by how much still overlaps; green is this window's count.
        Algorithm
          Try this. Press “Burst at the window edge” a few times. “Most in any 1 s” lands at 5, 6 or 7, never 10. It is an estimate, so it can be off by a little either way. Watch the purple part shrink as the window moves on.

          Two numbers per key, close to exact. Cloudflare reported that this kind of estimate was wrong on a tiny fraction of requests in its own traffic, which is why it is a common default.

          05 Token bucket

          A token bucket holds up to a set number of tokens, its capacity. Tokens drip in at a steady refill rate. Each request takes one token; with none left, 429. Two knobs, two meanings: the refill rate is the long-run average you allow, and the capacity is the biggest burst you will accept after a quiet spell.

          That matches how people use APIs. A page load fires ten calls at once, then nothing for a while. A token bucket lets the burst through and still holds the average. It needs two numbers per key: the token count and when it was last refilled, so the refill is worked out on each request rather than by a timer.

          Requests, last 5 snowClient A · 1/srequests from one callerToken bucket: 10.0 of 10 tokensIt refills 2 per second up to 10. Each request spends one token; with none left, 429.
          Allowed
          0
          429s
          0
          Allowed, last 1 s
          0

          Click any square to follow that one request.

          Capacity 10, refilling 2 a second. The client sends 1 a second, so the bucket stays full.
            Try this. Press “Send 15 at once”. Nine or ten pass, one for each token in the bucket, and the rest get 429. Then the bucket refills at 2 a second. Raise the client to 6 a second: after the bucket empties, only about 2 a second get through, whatever the client sends.

            Token bucket: capacity is the burst, refill rate is the average. Most API gateways use it or something close to it.

            06 Leaky bucket

            A leaky bucket is a queue with a small hole. Requests go into the bucket and leave through the hole at a fixed pace, one every half second at 2 a second, however they arrived. If the bucket is full, a new request is turned away.

            Where the token bucket lets a burst through at once, the leaky bucket spreads it out. That protects a service that cannot take bursts at all, such as a partner API with a strict per-second limit, or an old database. The cost is waiting: a request at the back of the bucket waits for everyone in front of it.

            Requests, last 5 snowClient A · 1/srequests from one callerLeaving the bucket · 2/swhen each request is let through to the serviceLeaky bucket: 0 of 6 waitingIt lets one out every 500 ms, evenly. When it is full, 429.out
            Allowed
            0
            429s
            0
            Added wait
            0 ms

            Click any square to follow that one request.

            Top lane: when requests arrive. Bottom lane: when they leave the bucket, one every 0.5 seconds.
              Try this. Press “Send 12 at once”. Six wait (amber), one may leave at once, and the rest get 429. In the bottom lane they leave evenly spaced, and “Added wait” climbs. Make the bucket bigger: fewer 429s, longer waits.

              Leaky bucket for a smooth output, token bucket for allowing bursts. NGINX’s limit_req is a leaky bucket; its burst setting is the bucket size.

              07 More than one server

              Real services run many copies behind a load balancer. If each copy keeps its own counter, each only sees its share of a caller’s traffic. With three servers and a limit of 10 a second, a caller gets up to 30, three times the limit, and it gets worse as you scale out.

              There are three common answers:

              • A shared counter. Every server checks the same store, usually Redis. Exact, but every request now waits for a network round trip, and the store becomes something that can fail.
              • Split the limit. Each of three servers allows a third. No round trip, but it only works if traffic is spread evenly.
              • Sync now and then. Each server counts locally and swaps totals with the store every so often. No round trip per request, and the overshoot is bounded by how long servers go between syncs.
              Requests, last 5 snowServer 1requests the load balancer sent here0 of 10 this windowServer 2requests the load balancer sent here0 of 10 this windowServer 3requests the load balancer sent here0 of 10 this window0 of 100 of 100 of 100 of 100 of 10No shared stateEach server counts alone, so 3 servers allow 3 × 10 = 30 per window, not 10.
              Allowed, last 1 s
              0
              429s
              0
              Added wait
              0 ms

              Click any square to follow that one request.

              One client sends 18 a second through a round-robin load balancer. The limit is 10 a second for the whole service.
              Counter
                Try this. With one counter per server, almost nothing is red, about 18 a second get through and the count over each window reads well past 10. Switch to Shared store: exactly 10 a window, but “Added wait” shows the round trip every request pays. Switch to Synced: most windows let a few more than 10 through, allowed by servers that had not heard the latest total. Drag “Sync every” down to shrink the overshoot.

                A limit is only as good as its count. Decide which you can afford: a round trip on every request, or a known amount of overshoot.

                08 What clients should do with a 429

                A 429 is a request to slow down. What callers do next decides whether the limiter calms things down or makes them worse.

                • Retry at once, in a loop. Every retry is another request, most are rejected again, and the load on the limiter multiplies. That is a retry storm.
                • Retry exactly at Retry-After. Better, but everyone who was told “come back at 3 seconds” arrives at once, and most get turned away again.
                • Wait at least Retry-After, then back off with jitter. Each failure doubles the wait, and a random part spreads callers out. Give up after a few tries.
                Requests, last 5 snowClient A · 3/srequests from one callerClient B · 3/srequests from one caller0 of 80 of 80 of 80 of 80 of 8Fixed window: 0 of 8 usedOne counter for the window 0–1 s. It resets to zero in 1.00 s.
                Attempts, last 1 s
                0
                New requests, last 1 s
                0
                Busiest 0.1 s
                0
                Gave up
                0

                Click any square to follow that one request.

                Two clients, 6 requests a second between them, and a limit of 8. Hollow squares are retries.
                On 429
                  Try this. Press “Spike” with “Retry at once”: client A’s lane fills with red retries, attempts reach the hundreds and requests start to give up. Client B did nothing wrong, but its requests now lose the race for each window too. Reset, pick Retry-After and spike again: retries land in tall columns right at each window boundary. Pick “Backoff + jitter”: retries spread out, the busiest moment is far smaller and nobody gives up.

                  Send Retry-After from the server, and in the client, honour it, add exponential backoff with jitter and cap the attempts. The payments system on this site shows a retry storm against a provider’s limit.

                  09 Rate limiting in real tools

                  You rarely build a limiter from scratch. A rough map of where they live:

                  ToolAlgorithmWhere the count livesGood for
                  API gatewaysMostly token bucket, set as a rate and a burst (Amazon API Gateway, Kong, Envoy)Per API key or plan; Kong and Envoy can count locally or in a shared RedisPer-customer quotas on a public API
                  NGINX limit_reqLeaky bucket; burst sets the queue, nodelay lets a burst through at onceShared memory on one NGINX serverProtecting one site or upstream, by IP or key
                  CloudflareRate limiting rules count requests per period for a key such as the IPAt Cloudflare’s edge, before traffic reaches youStopping abuse and floods early
                  Redis librariesFixed or sliding window, token bucket, GCRA (redis-cell, rate-limiter-flexible, Upstash Ratelimit)One Redis shared by every app server, kept atomic with Lua or a moduleExact limits across many app servers

                  Check the current docs before you choose: defaults, counting periods and where counts are kept change between products and plans.

                  10 Check yourself

                  1. An API allows 100 requests a minute with a fixed window counter. What is the most a client can get through in about two seconds?

                  2. You want clients to average 10 requests a second but allow short bursts of up to 50. Which limiter fits?

                  3. Four servers sit behind a round-robin load balancer. Each runs its own limiter of 100 a second. How much can one client get?

                  4. Your clients retry a 429 immediately, in a loop. A short spike arrives. What happens?

                  5. A downstream partner API must never see more than 5 requests a second, evenly spaced. Your traffic is bursty. What do you put in front of it?

                  Next partCDNs