Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 4 min read

Why Your Redis Rate Limiter Needs a Lua Script (FastAPI Example)

Keeping request counts in a Python dictionary works fine on your laptop, right up until you run more than one Uvicorn worker or spin up a second container. Suddenly every process has its own counter, and your rate limit

Keeping request counts in a Python dictionary works fine on your laptop, right up until you run more than one Uvicorn worker or spin up a second container. Suddenly every process has its own counter, and your rate limit is off by whatever number of workers you're running.

Moving that state into Redis solves the shared-counter problem. Still, if you wire it up using standard INCR and EXPIRE commands, you can accidentally lock users out of your API permanently.

Here is how to build a clean, atomic rate limiter in FastAPI using Redis and a short Lua script. All the code is also up on GitHub at itsmill/fastapi-redis-rate-limiter.

The INCR + EXPIRE Race Condition

Most first attempts at a Redis rate limiter look something like this:

# Don't ship this to production
count = await redis_client.incr(key)
if count == 1:
    await redis_client.expire(key, 60)

It looks harmless, but those are two separate network calls. If your FastAPI worker crashes or drops its connection right after INCR runsβ€”before EXPIRE ever firesβ€”that Redis key stays in memory forever with no TTL. Every future request from that IP sees a count higher than your limit and gets blocked until someone manually deletes the key.

Redis runs Lua scripts atomically on a single thread. Putting INCR, EXPIRE, and TTL inside one small Lua script guarantees they execute together in a single round-trip with zero race conditions.

Quick Local Setup

If you don't have Redis running locally yet, spin up an Alpine container with Docker:

docker run -d --name fastapi-redis -p 6379:6379 redis:7-alpine

Next, create a requirements.txt file with FastAPI, Uvicorn, and the async Redis client:

fastapi==0.115.6
uvicorn==0.34.0
redis==5.2.1

Set up a virtual environment and install them:

python -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate
pip install -r requirements.txt

Building the FastAPI Rate Limiter

Create main.py and add the Redis connection, the Lua script, and a dependency/helper function to check incoming requests:

import os
from fastapi import FastAPI, HTTPException, Request, Response, status
import redis.asyncio as redis

app = FastAPI(title="FastAPI Redis Rate Limiter")

REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
redis_client = redis.from_url(REDIS_URL, decode_responses=True)

# Atomic Lua script: increments counter and sets TTL on first request
RATE_LIMIT_LUA = """
local current = redis.call("INCR", KEYS[1])
if current == 1 then
    redis.call("EXPIRE", KEYS[1], ARGV[1])
end
local ttl = redis.call("TTL", KEYS[1])
return {current, ttl}
"""


async def check_rate_limit(
    request: Request,
    response: Response,
    max_requests: int = 5,
    window_seconds: int = 60,
) -> None:
    client_ip = request.client.host if request.client else "unknown"
    key = f"rate_limit:{request.url.path}:{client_ip}"

    try:
        current_count, ttl = await redis_client.eval(
            RATE_LIMIT_LUA, 1, key, window_seconds
        )
    except redis.RedisError as exc:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Rate limiter storage unavailable",
        ) from exc

    remaining = max(0, max_requests - int(current_count))
    response.headers["X-RateLimit-Limit"] = str(max_requests)
    response.headers["X-RateLimit-Remaining"] = str(remaining)

    if int(current_count) > max_requests:
        retry_after = max(1, int(ttl))
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail=f"Rate limit exceeded. Try again in {retry_after} seconds.",
            headers={
                "Retry-After": str(retry_after),
                "X-RateLimit-Limit": str(max_requests),
                "X-RateLimit-Remaining": "0",
            },
        )


@app.get("/api/data")
async def get_protected_data(request: Request, response: Response):
    await check_rate_limit(request, response, max_requests=5, window_seconds=60)
    return {"status": "ok", "message": "Request allowed within rate limit."}

What's Happening Under the Hood

  • Per-route keys: Using rate_limit:{request.url.path}:{client_ip} keeps counters isolated per endpoint. Spamming /api/data won't accidentally block a user from hitting /api/health or another route.
  • One network trip: redis_client.eval() sends the Lua script once, bumps the counter, attaches the 60-second expiration only when current == 1, and hands back both the current count and remaining TTL.
  • Helpful response headers: Even on 200 OK responses, clients get X-RateLimit-Limit and X-RateLimit-Remaining. Once they cross the threshold, they get a 429 Too Many Requests along with a Retry-After header so well-behaved clients know when to back off.
  • Handling Redis outages: Wrapping .eval() in try/except redis.RedisError returns a clean 503 instead of a messy unhandled traceback. (If you'd rather let traffic through during a Redis blip instead of blocking users, you can log the exception here and return earlyβ€”commonly called "failing open".)

Testing It with curl

Start the app:

uvicorn main:app --reload

Fire six requests in a row against /api/data:

for i in {1..6}; do
  curl -i -s [http://127.0.0.1:8000/api/data](http://127.0.0.1:8000/api/data) | grep -E "HTTP/|X-RateLimit|Retry-After|\{"
  echo "---"
done

Requests 1 through 5 return 200 OK with X-RateLimit-Remaining stepping down from 4 to 0. On the 6th hit, Redis rejects it:

HTTP/1.1 429 Too Many Requests
retry-after: 58
x-ratelimit-limit: 5
x-ratelimit-remaining: 0
{"detail":"Rate limit exceeded. Try again in 58 seconds."}

Two Gotchas Before Deploying

  1. Reverse proxies hide real IPs: Behind Nginx, Cloudflare, or an AWS ALB, request.client.host will just be your proxy's internal IPβ€”meaning one noisy user can trigger the rate limit for everyone. Start Uvicorn with --proxy-headers and --forwarded-allow-ips configured for your load balancer so FastAPI reads the real client IP.
  2. Fixed-window boundary spikes: Because this counter resets every 60 seconds on a fixed timer, someone can send 5 requests at second 59 and 5 more at second 61 (10 requests in 2 seconds). If you need strict smoothing across window edges, swap the simple counter for a sliding-window log using Redis Sorted Sets (ZADD + ZREMRANGEBYSCORE).
πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.