The Analogy: The Motorway On-Ramp Metering Light
On a busy motorway the on-ramps carry metering lights -- a small signal at the top of the slip road that turns green for a fraction of a second, releasing one car onto the mainline, then red again. It does not care who you are or where you are going; it governs only the rate at which cars are allowed to merge. When traffic is light the meter stays green; when the mainline fills up it lengthens the red so cars trickle on slowly and a queue forms on the ramp. The metering light is a rate limiter; each green pulse is an allowed request; the red hold is throttling; the queue on the ramp is requests waiting or being turned away; the mainline is the service you are protecting.
The meter exists because the motorway has finite capacity, and if every ramp dumped its full flow at once the mainline would seize into a jam that serves nobody -- the fast lane grinds down to the speed of the slowest merge. By admitting cars at a controlled rate the meter keeps the mainline flowing faster overall, even though each driver waited a few seconds at the ramp. Rate limiting a service is the same trade: a request held back or refused protects the throughput and stability of the whole system, so one aggressive client cannot starve everyone else. The limit is not punishment; it is the price of a mainline that keeps moving.
Each ramp has its own meter with its own count, so a jam building at one entrance does not throttle a quiet one across town -- the limit is applied per entrance, the way a good limiter counts per client rather than globally. And the meter must answer "how many in the last minute," which means it needs a memory of recent arrivals. A meter that simply flips green and red on a dumb fixed timer, ignoring how many cars actually came, either lets a platoon flood through or holds up an empty ramp. Counting over a rolling recent window is what makes the rate honest.
The failure that quietly defeats a meter is resetting the count on a hard clock tick. Suppose the meter releases three cars per ten-second window and wipes its tally to zero at the top of each window. A clever driver waits until the last second of one window, sends three cars through, and at the very start of the next window sends three more -- six cars merge within about two seconds, double the intended rate, because the reset boundary sat between them. The meter's paperwork says "three per window" and every window obeyed it; the road still got the burst it was built to prevent. Counting has to slide with real time, not jump to zero on a boundary, or the limit is only an average with a hole punched in it.
Syntax or Core Structure
A rate limiter sits in front of your views, counts requests per client, and rejects the ones over the allowance with HTTP 429. The smallest honest version is a before_request hook backed by a counter. Here that counter is an in-process dict, and the client is identified by its address.
from flask import Flask, jsonify, abort, request
app = Flask(__name__)
LIMIT = 3
hits = {} # client key -> count in the current window
@app.before_request
def rate_limit():
key = request.remote_addr or "anon" # one bucket per client
hits[key] = hits.get(key, 0) + 1
if hits[key] > LIMIT:
abort(429) # Too Many Requests
@app.get("/ping")
def ping():
return jsonify(ok=True)
client = app.test_client()
codes = [client.get("/ping").status_code for _ in range(5)]
print("codes:", codes)
Output:
codes: [200, 200, 200, 429, 429]
The limiter runs in before_request, so it fires on every request before any view. It keys a counter by client, increments it, and aborts with 429 once the count passes the limit: the first three pings returned 200, the fourth and fifth returned 429 because that client had spent its allowance. The whole scheme lives in a plain dict, which is fine for one process -- but that dict is exactly the piece that must move to a shared store the moment you run more than one worker.
Technical Depth: Windows, Buckets, and Where the Counter Lives
Choosing a counting algorithm
| Algorithm | How it counts | Burst behaviour | Cost |
|---|---|---|---|
| Fixed window | Requests per clock-aligned window | Allows up to 2x the limit across a boundary | Cheapest: one counter per window |
| Sliding log | Timestamp of every request, count the last N seconds | Exact, no boundary burst | Stores every timestamp; heaviest |
| Sliding window counter | Weighted blend of current and previous window | Smooths the boundary at low cost | One or two counters |
| Token bucket | Tokens refill at a steady rate, each request spends one | Allows a controlled burst up to bucket size | One number plus a timestamp |
The fixed window is the easiest to write and the easiest to fool. The sliding log is exact but keeps a timestamp per request, which is memory you may not want. The token bucket is the usual production default: it permits a deliberate short burst up to the bucket capacity and then enforces a steady average rate, which matches how real clients actually behave. The next two demonstrations show the fixed window's flaw and the token bucket's fix.
Fixed window and its boundary burst
The cheapest limiter buckets requests into clock-aligned windows and counts per window. It is also the one an attacker games with the boundary trick from the analogy. This model uses an integer clock so the effect is exact and reproducible.
LIMIT = 3
buckets = {} # (key, window_number) -> count
def fixed_window(key, now, size=10):
w = now // size # which fixed window this timestamp falls in
slot = (key, w)
buckets[slot] = buckets.get(slot, 0) + 1
return buckets[slot] <= LIMIT
# 3 requests at the tail of window 0, then 3 at the head of window 1:
# only three seconds apart, but they land in different windows.
times = [8, 9, 9, 10, 10, 11]
allowed = [fixed_window("ip", t) for t in times]
print("allowed:", allowed)
print("passed in a 3-second span:", sum(allowed))
Output:
allowed: [True, True, True, True, True, True]
passed in a 3-second span: 6
All six requests were allowed even though the limit is three, because the boundary at t = 10 reset the counter. Window 0 (t = 8, 9, 9) reached three, and window 1 (t = 10, 10, 11) started a fresh count from zero, so a burst straddling the boundary sails through at double the intended rate. Every window individually obeyed the limit and the service still took twice the load.
Token bucket: capping the burst
A token bucket holds up to capacity tokens and refills at a steady rate. Each request spends one token; an empty bucket means refusal. Because tokens never exceed the capacity, no boundary trick can accumulate a double burst.
class TokenBucket:
def __init__(self, capacity, refill_per_sec):
self.capacity = capacity
self.tokens = capacity
self.refill = refill_per_sec
self.last = 0
def allow(self, now):
# add tokens for the time elapsed, never above capacity
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.refill)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
bucket = TokenBucket(capacity=3, refill_per_sec=1)
times = [0, 0, 0, 0, 1, 2] # four instant hits, then one per second
allowed = [bucket.allow(t) for t in times]
print("allowed:", allowed)
print("passed:", sum(allowed))
Output:
allowed: [True, True, True, False, True, True]
passed: 5
The bucket starts full with three tokens. The first three instant requests each spend one and pass; the fourth finds the bucket empty and is refused -- the burst is capped at the capacity, which the fixed window failed to do. After that one token refills per second, so the requests at t = 1 and t = 2 each find a fresh token and pass. The burst is bounded and the steady rate is enforced, with no boundary to exploit.
The 429 response and Retry-After
The correct status for a throttled request is 429 Too Many Requests. A well-behaved limiter also sends a Retry-After header telling the client how many seconds to wait, so honest clients back off instead of hammering. Return a small JSON body explaining the limit, never leak the limiter's internal counters, and make sure the limit check runs before any expensive work -- a limiter that first does the database query it was meant to prevent has protected nothing.
The real tool (illustrative)
In production you reach for Flask-Limiter rather than hand-rolling the counter. It attaches limits to routes with a decorator, parses human strings like "5 per minute," and -- critically -- takes a storage_uri so the counter lives in a shared store instead of one process's memory:
# app.py -- flask-limiter (illustrative; needs the package and a shared store)
from flask import Flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
app = Flask(__name__)
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["200 per day", "50 per hour"],
storage_uri="redis://localhost:6379", # shared across all workers
)
@app.post("/login")
@limiter.limit("5 per minute") # a tighter limit on a sensitive route
def login():
...
The storage_uri is the line that matters most, and the one most often left at its in-memory default. With an in-memory store each worker process counts on its own; point it at Redis or Memcached and every worker shares one window. The real-world example below shows exactly why that default is dangerous.
Real World Example: A Login Throttle That Multiplies Behind a Load Balancer
Brute-force protection on a login endpoint locks an account after a few consecutive failures. The version below keeps its failure counter in a per-process dict -- the same easy default as the syntax example. It works perfectly in one process, so it passes every test on a developer's machine. Then we run it the way production runs it: two workers behind a load balancer, with the same attacker's requests spread across both.
from flask import Flask, request, jsonify, abort
USERS = {"ada": "correct horse"}
MAX_FAILS = 3
def make_worker():
app = Flask(__name__)
fails = {} # per-process state: each worker gets its own
@app.post("/login")
def login():
body = request.get_json()
u, p = body["user"], body["password"]
if fails.get(u, 0) >= MAX_FAILS:
abort(429) # locked out after too many failures
if USERS.get(u) == p:
fails[u] = 0 # a success clears the counter
return jsonify(ok=True)
fails[u] = fails.get(u, 0) + 1
return jsonify(ok=False), 401
return app.test_client()
def attempt(client, pw):
r = client.post("/login", json={"user": "ada", "password": pw})
return r.status_code
# one worker: three wrong tries, then the account is locked
w1 = make_worker()
single = [attempt(w1, "nope") for _ in range(4)]
print("single worker:", single)
# a load balancer spreads the SAME attacker across two workers,
# each keeping its own private counter
wA, wB = make_worker(), make_worker()
spread = [attempt(wA, "nope"), attempt(wB, "nope"),
attempt(wA, "nope"), attempt(wB, "nope"),
attempt(wA, "nope"), attempt(wB, "nope")]
print("two workers :", spread)
print("wrong guesses allowed before any lockout:", spread.count(401))
Output:
single worker: [401, 401, 401, 429]
two workers : [401, 401, 401, 401, 401, 401]
wrong guesses allowed before any lockout: 6
The endpoint reads the credentials, checks whether the account is already locked, and only then compares the password. A wrong password increments the per-user counter, a correct one clears it, and once the counter reaches MAX_FAILS the endpoint aborts 429 without even checking the password. On paper this is textbook brute-force protection, and in a single process it behaves exactly as written.
Walk the output. In one worker the three wrong guesses returned 401 and the fourth was locked out with 429 -- exactly three failures tolerated, as configured. Then the same attacker's six guesses were spread across two workers. Each worker saw only three of them, none reached its own MAX_FAILS, and all six returned 401: the attacker got six guesses and never tripped a single lockout.
The reason is that each worker built its own fails dict when make_worker ran, and nothing joins them. A load balancer distributing requests round-robin hands each worker a fraction of the attacker's traffic, so the effective limit is MAX_FAILS times the number of workers. Four workers means twelve guesses before a lockout; autoscaling to ten means thirty. The protection weakens in exact proportion to how far you scale out, and it resets to zero on every deploy because a fresh process starts with an empty dict.
The genuine flaw is that the limiter's state is process-local while the application is multi-process. No tuning of MAX_FAILS fixes it, because the number that actually governs the attacker is MAX_FAILS times the worker count -- a figure you do not set and that changes as you scale. The fix is to move the counter out of the process into a store every worker shares, Redis or Memcached, so all workers increment one counter per account. That is exactly what Flask-Limiter's storage_uri configures, and why leaving it at the in-memory default turns a correct-looking limiter into decorative code. The same rule governs any per-instance state behind a security decision: if the decision must hold across the fleet, the state cannot live in one instance's memory.
Common Mistakes
- Keeping the counter in process memory behind multiple workers. Each worker counts alone, so the real limit is your configured limit times the worker count, and it resets on every deploy. Use a shared store.
- Using a fixed window for a hard ceiling. An attacker doubles the rate across the reset boundary. Use a sliding window or a token bucket when the limit must genuinely hold.
- Rate limiting after the expensive work. A limiter that first runs the query or the login check it was meant to prevent has protected nothing. Check the limit first.
- Returning the wrong status. Throttled requests are 429, not 403 or 500; clients and proxies treat 429 specially, including honouring
Retry-After.
- Omitting
Retry-After. Without it, well-behaved clients cannot back off correctly and retry blindly, adding to the load you are trying to shed.
- Keying only on IP address. Many users share one NAT or proxy address, so an IP limit punishes a whole office for one abuser. Combine IP with account or API key where you can.
- Keying account lockout only on the username. An attacker who floods someone else's username can lock that victim out at will -- a denial of service. Track failures per (account, source) and prefer throttling to a hard lock.
- Trusting a client-supplied identifier. Limiting on a header the client sets, or on
X-Forwarded-Forwithout a trusted proxy, lets the attacker rotate identities and evade the limit entirely.
- Leaking limiter internals. Returning the current count, the reset time, or which rule fired hands an attacker a map for tuning their attack. Return a generic message.
Best Practices
- Store rate-limit state in a shared backend such as Redis or Memcached, so all workers enforce one limit rather than one each.
- Prefer a token bucket or sliding window over a fixed window whenever the ceiling must genuinely hold under a determined client.
- Check the limit before any expensive or sensitive work, in a
before_requesthook or a decorator that runs ahead of the view body.
- Respond with 429 and a
Retry-Afterheader, plus a short generic body that never exposes internal counters.
- Set tighter limits on sensitive routes (login, password reset, token issue) than on read-only ones, layering per-route limits on a global default.
- Combine identifiers -- IP plus account or API key -- and never key a limit on a value the client can freely change.
- Throttle rather than hard-lock where you can, and when you must lock, key on (account, source) so one user cannot lock out another.
- Reach for a maintained library like Flask-Limiter instead of hand-rolling, and monitor your 429 rate to catch both attacks and limits set too tight.
Practice Exercises
- The syntax example's counter is a module-level dict. Explain what happens to the effective limit when the app runs under four Gunicorn workers, and name the specific change that fixes it.
- Given a fixed-window limiter of "10 per minute," construct the exact sequence of request times that lets a client send 20 requests in just over one second, and state which algorithm removes the loophole.
- A login endpoint locks an account after five failures keyed on the username alone. Describe the denial-of-service this enables against an innocent user, and redesign both the key and the response to prevent it.
- Design rate limits for a public API with a free tier and a paid tier. Specify the identifier, the algorithm, the limit per tier, the response on breach, and where the counter is stored, and justify each choice.