Python

Building a Production-Ready Rate Limiter in Python with Redis and FastAPI

Imagine you're building a FastAPI application that exposes APIs for user authentication, dashboards, payments, or AI-powered features. Everything works fine…

D
DevByteTechnical Author
Published
22 min read2 views
Building a Production-Ready Rate Limiter in Python with Redis and FastAPI

Imagine you're building a FastAPI application that exposes APIs for user authentication, dashboards, payments, or AI-powered features. Everything works fine during development, but after deployment, one endpoint starts receiving thousands of requests within a few seconds.

Some requests come from legitimate users. Others might come from automated scripts, bots, or clients that retry failed requests too aggressively.

Without any protection, your application could waste database connections, consume unnecessary CPU, exhaust third-party API quotas, or become unavailable to other users.

This is where rate limiting becomes useful.

Rate limiting controls how frequently a client can access a resource within a defined period. For example, you might allow 100 requests per minute for a general API endpoint while limiting login attempts to five requests per minute per client.

You could implement these limits directly in Python, but that approach becomes problematic when your application runs across multiple workers or server instances.

A shared data store such as Redis solves this problem by allowing multiple application instances to coordinate their request counts.

In this guide, we'll build a rate limiter using Python, FastAPI, and Redis. We'll explore different rate-limiting algorithms, implement an atomic Redis-backed solution, return appropriate HTTP responses, and cover the security and operational details that matter in production.

1. What Is Rate Limiting?

Rate limiting is a technique used to restrict the number of requests a client can make during a particular period.

For example, suppose an API has the following rule:

Allow a maximum of 100 requests per minute per authenticated user.

If a user sends 80 requests during that minute, the requests can continue normally. If the user sends another 30 requests, some of those requests will exceed the configured limit.

The application can reject requests that exceed the limit with HTTP status code 429 Too Many Requests.

Rate limiting is commonly used to protect:

  • Authentication endpoints from excessive login attempts.

  • Public APIs from abusive traffic.

  • AI endpoints that have expensive inference costs.

  • Payment and transaction APIs from repeated requests.

  • Database-heavy endpoints from excessive load.

  • Third-party integrations from exceeding provider quotas.

However, rate limiting isn't a replacement for authentication, authorization, input validation, or protection against distributed denial-of-service attacks.

It is one layer in a broader application security strategy.

Rate Limiting vs. Throttling

These terms are sometimes used interchangeably, but they can describe different behaviors.

Rate limiting defines how many requests are allowed within a particular period.

Throttling can refer more broadly to controlling request throughput, including slowing down requests rather than rejecting them.

For this tutorial, we'll focus on rate limiting that rejects requests exceeding a configured allowance.

2. Why Use Redis Instead of an In-Memory Dictionary?

Let's start with a simple implementation.

from time import time

request_counts = {}


def is_rate_limited(client_id: str) -> bool:
    current_time = int(time() // 60)

    key = f"{client_id}:{current_time}"

    request_counts[key] = request_counts.get(key, 0) + 1

    return request_counts[key] > 100

This example counts requests by client and minute. It illustrates the basic idea, but it isn't suitable for a production service.

There are several problems.

Problem 1: Each Process Has Its Own Counter

Suppose your FastAPI application runs four worker processes.

Each process maintains its own request_counts dictionary. A user could make 100 requests through each worker and potentially exceed the intended limit.

The application has no shared source of truth.

Problem 2: Memory Can Grow Indefinitely

The dictionary creates new keys as different clients make requests. Unless old keys are removed, the dictionary continues growing.

A long-running application could accumulate a large number of expired counters.

Problem 3: Concurrent Requests Can Cause Problems

When requests arrive concurrently, a counter update must be handled carefully. More complex read-modify-write sequences can produce incorrect results when multiple operations overlap.

Problem 4: Restarting the Application Resets Everything

An in-memory dictionary disappears when the process restarts.

That means clients may regain their entire request allowance after a restart, even if they have already exceeded their intended limit.

Why Redis Helps

Redis is an in-memory data store that supports fast operations on counters, expiration, and atomic scripting.

Using Redis gives multiple FastAPI workers access to shared rate-limit state.

It also allows us to expire counters automatically, reducing the need to maintain old entries manually.

For a distributed application, Redis provides a much better foundation than process-local dictionaries.

3. Choosing a Rate-Limiting Algorithm

Before writing the implementation, it's worth understanding the main algorithms.

Different algorithms have different trade-offs. The best choice depends on whether you want simplicity, smooth traffic distribution, precise accounting, or burst handling.

Fixed Window Counter

The fixed-window algorithm divides time into fixed intervals.

For example, a limit of 100 requests per minute creates a new counter every minute.

Requests between 10:00:00 and 10:00:59 share one counter. Requests beginning at 10:01:00 use another.

Advantages:

  • Simple to implement.

  • Low memory usage.

  • Efficient with Redis counters and expiration.

Disadvantage:

Clients can send a burst near the end of one window and another burst immediately after the next window begins.

For example, a client might send 100 requests at 10:00:59 and another 100 at 10:01:00.

The client could therefore send 200 requests within a very short period despite a nominal limit of 100 per minute.

Sliding Window Log

The sliding-window-log algorithm records individual request timestamps.

For each request, it removes timestamps outside the allowed period, counts the remaining entries, and decides whether the new request is allowed.

Advantages:

  • Accurate enforcement over a rolling time window.

  • Avoids the fixed-window boundary problem.

Disadvantages:

  • Stores more data because each request may require a timestamp entry.

  • Requires additional Redis operations or scripting.

  • Can become expensive for high-volume endpoints.

Sliding Window Counter

A sliding-window counter combines the current fixed-window count with the previous window's count.

It estimates the number of requests in the rolling period using the proportion of the previous window that overlaps the current period.

This reduces boundary effects without storing every individual request.

Advantages:

  • More memory-efficient than a full request log.

  • Provides a useful approximation of rolling-window traffic.

Disadvantages:

  • The result is an estimate rather than an exact count of requests within the rolling window.

Token Bucket

The token-bucket algorithm maintains a bucket of tokens that refill at a configured rate.

Each request consumes a token. If no token is available, the request is rejected until the bucket refills.

For example, a bucket might hold 20 tokens and refill at five tokens per second.

This permits short bursts while controlling the average request rate.

Token buckets are useful for APIs that need controlled bursts rather than strict fixed-window limits.

Which Algorithm Will We Use?

For this tutorial, we'll implement a Redis-backed fixed-window counter using an atomic Lua script.

It's a good starting point because it is easy to understand, efficient, and suitable for many API use cases.

We'll also discuss its limitations and how you can evolve the design if your application needs rolling-window precision or controlled bursts.

4. Project Setup

Let's create a small FastAPI application.

Our project structure will look like this:

rate-limiter/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── limiter.py
│   └── config.py
├── requirements.txt
├── .env
└── docker-compose.yml

We'll use:

  • Python for application logic.

  • FastAPI for HTTP endpoints.

  • Redis for shared request counters.

  • redis-py for communication with Redis.

  • pydantic-settings for configuration management.

  • Docker Compose for local Redis development.

Install the Dependencies

Create a virtual environment:

python -m venv .venv

Activate it on macOS or Linux:

source .venv/bin/activate

On Windows, use:

.venv\Scripts\activate

Create a requirements.txt file:

fastapi
uvicorn[standard]
redis
pydantic-settings

Install the packages:

pip install -r requirements.txt

For a real deployment, pin and test dependency versions rather than relying indefinitely on unbounded package specifications.

5. Start Redis with Docker Compose

If Redis isn't already installed, Docker is a convenient way to run it locally.

Create a docker-compose.yml file:

services:
  redis:
    image: redis:7
    command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD}
    environment:
      REDIS_PASSWORD: ${REDIS_PASSWORD}
    ports:
      - "127.0.0.1:6379:6379"
    volumes:
      - redis_data:/data
    healthcheck:
      test:
        [
          "CMD-SHELL",
          "redis-cli -a \"$${REDIS_PASSWORD}\" ping | grep -q PONG"
        ]
      interval: 5s
      timeout: 3s
      retries: 5

volumes:
  redis_data:

This configuration binds Redis to the local loopback interface rather than exposing it on every network interface.

The volume allows Redis data to persist across container recreation, subject to the configured persistence behavior.

Create a .env file:

REDIS_PASSWORD=replace_with_a_long_random_password
REDIS_URL=redis://:replace_with_a_long_random_password@127.0.0.1:6379/0

Replace the example password in both values with the same strong random secret.

Start Redis:

docker compose up -d

Check the container:

docker compose ps

Important: This setup is intended for local development. For production, use a managed Redis service or a properly secured Redis deployment with network isolation, access controls, TLS where appropriate, secret management, and monitoring.

Also, don't commit .env files containing real credentials to Git.

6. Configure the FastAPI Application

Create app/config.py:

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    redis_url: str

    model_config = SettingsConfigDict(
        env_file=".env",
        extra="ignore",
    )


settings = Settings()

FastAPI doesn't require a particular configuration library, but centralizing configuration makes applications easier to maintain.

Now create the Redis connection in app/limiter.py.

We'll use an asynchronous Redis client because our FastAPI endpoints will be asynchronous.

import redis.asyncio as redis

from app.config import settings


redis_client = redis.from_url(
    settings.redis_url,
    decode_responses=True,
    socket_connect_timeout=2,
    socket_timeout=2,
    health_check_interval=30,
    max_connections=100,
)

This creates a Redis connection pool through which application requests can share connections.

The connection limits and timeouts should be chosen based on the expected traffic, Redis capacity, and deployment configuration.

For example, if each worker has its own pool of up to 100 connections, four workers could potentially create up to 400 pooled connections. Account for all application instances when configuring Redis capacity.

We'll add a shutdown function later so the client can be closed cleanly.

7. Build an Atomic Redis Rate Limiter

Now comes the important part.

A rate limiter needs to perform several operations:

  1. Read the current request count.

  2. Decide whether the request is allowed.

  3. Increment the counter if appropriate.

  4. Set or maintain the expiration time.

If these operations are performed independently, concurrent requests can interfere with one another.

Redis Lua scripts allow us to execute the counter check and update atomically on the Redis server.

Let's create the implementation in app/limiter.py.

import redis.asyncio as redis

from app.config import settings


redis_client = redis.from_url(
    settings.redis_url,
    decode_responses=True,
    socket_connect_timeout=2,
    socket_timeout=2,
    health_check_interval=30,
    max_connections=100,
)


RATE_LIMIT_SCRIPT = """
local current = redis.call("GET", KEYS[1])

if not current then
    redis.call("SET", KEYS[1], 1, "EX", ARGV[1])
    return {1, tonumber(ARGV[1])}
end

current = tonumber(current)

if current >= tonumber(ARGV[2]) then
    local ttl = redis.call("TTL", KEYS[1])

    if ttl < 0 then
        redis.call("EXPIRE", KEYS[1], ARGV[1])
        ttl = tonumber(ARGV[1])
    end

    return {0, ttl}
end

current = redis.call("INCR", KEYS[1])

local ttl = redis.call("TTL", KEYS[1])

return {1, ttl}
"""


async def check_rate_limit(
    key: str,
    limit: int,
    window_seconds: int,
) -> tuple[bool, int]:
    result = await redis_client.eval(
        RATE_LIMIT_SCRIPT,
        1,
        key,
        window_seconds,
        limit,
    )

    allowed = bool(result[0])
    retry_after = max(0, int(result[1]))

    return allowed, retry_after

Let's understand what the script does.

First Request

If the key doesn't exist, the script creates it with a value of 1 and sets an expiration.

For a 60-second window, the key expires after 60 seconds.

Requests Within the Limit

If the counter is below the configured limit, the script increments it and allows the request.

Requests That Exceed the Limit

When the current count has reached the limit, the script rejects the request without incrementing the counter.

It also returns the remaining key lifetime so the application can tell the client how long to wait before retrying.

Why Is the Script Atomic?

Redis executes a Lua script without interleaving other Redis commands while that script runs.

That means concurrent application requests cannot simultaneously read the same counter value and independently decide to increment it outside the script.

The check and increment happen as one atomic operation.

This is much safer than writing the logic as separate GET, Python comparison, and INCR calls.

Why Do We Set an Expiration?

Without expiration, old counter keys could remain in Redis indefinitely.

Expiration allows Redis to remove keys automatically after their windows end.

For this fixed-window implementation, the expiration is established when the first request creates the counter. Subsequent requests do not extend the window.

One limitation is that the script assumes the counter contains a valid integer. Application code should generate consistent keys and avoid unrelated code writing incompatible values to the same Redis namespace.

8. Create a Reusable FastAPI Rate-Limiting Dependency

We don't want to repeat rate-limiting logic in every endpoint.

FastAPI dependencies allow us to centralize this behavior.

Create or extend app/limiter.py with the following code:

import math

from fastapi import HTTPException, Request, status


async def enforce_rate_limit(
    request: Request,
    client_id: str,
    limit: int = 100,
    window_seconds: int = 60,
) -> None:
    key = f"rate-limit:v1:{client_id}"

    allowed, retry_after = await check_rate_limit(
        key=key,
        limit=limit,
        window_seconds=window_seconds,
    )

    if not allowed:
        retry_after = max(1, retry_after)

        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail="Rate limit exceeded. Please try again later.",
            headers={
                "Retry-After": str(retry_after),
            },
        )

This helper raises an HTTP 429 response when the request exceeds the limit.

The Retry-After header tells the client how many seconds to wait before trying again.

The math import isn't needed in this particular implementation, so you can omit it. We can also remove the unused request argument because this function receives an explicit client identifier. A cleaner final version is:

from fastapi import HTTPException, status


async def enforce_rate_limit(
    client_id: str,
    limit: int = 100,
    window_seconds: int = 60,
) -> None:
    key = f"rate-limit:v1:{client_id}"

    allowed, retry_after = await check_rate_limit(
        key=key,
        limit=limit,
        window_seconds=window_seconds,
    )

    if not allowed:
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail="Rate limit exceeded. Please try again later.",
            headers={
                "Retry-After": str(max(1, retry_after)),
            },
        )

We'll use this cleaner version in the endpoint.

9. Apply Rate Limiting to FastAPI Endpoints

Create app/main.py:

from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI, Request

from app.limiter import enforce_rate_limit, redis_client


@asynccontextmanager
async def lifespan(app: FastAPI):
    await redis_client.ping()

    try:
        yield
    finally:
        await redis_client.aclose()


app = FastAPI(lifespan=lifespan)


async def limit_by_client_ip(request: Request):
    client_ip = request.client.host if request.client else "unknown"

    await enforce_rate_limit(
        client_id=f"ip:{client_ip}",
        limit=100,
        window_seconds=60,
    )


@app.get(
    "/api/data",
    dependencies=[Depends(limit_by_client_ip)],
)
async def get_data():
    return {
        "message": "Request successful",
        "data": ["Python", "FastAPI", "Redis"],
    }


@app.get("/health")
async def health_check():
    return {
        "status": "ok",
    }

Run the application:

uvicorn app.main:app --reload

Test the endpoint:

curl -i http://127.0.0.1:8000/api/data

You should receive a successful response while the request remains within the configured limit.

After the limit is reached, additional requests should receive HTTP 429.

The /health endpoint isn't rate-limited by this dependency. In a production application, consider whether health endpoints should be public, private, or restricted at the network or infrastructure layer.

Important Note About Proxy Headers

The example reads the IP address from request.client.host.

If your application runs behind a reverse proxy or load balancer, this may be the proxy's IP address rather than the original client address.

You should configure trusted proxy handling appropriately and ensure forwarded headers are accepted only from trusted infrastructure.

Never blindly trust arbitrary X-Forwarded-For values supplied by clients. Otherwise, an attacker may change the apparent client IP and bypass an IP-based limit.

10. Use Different Limits for Different Endpoints

A real application rarely needs the same limit everywhere.

A public read-only endpoint might allow 100 requests per minute, while a login endpoint needs a much stricter policy.

You can create separate dependencies.

from fastapi import Depends, FastAPI, Request

from app.limiter import enforce_rate_limit


app = FastAPI()


async def general_api_limit(request: Request):
    client_ip = request.client.host if request.client else "unknown"

    await enforce_rate_limit(
        client_id=f"general:{client_ip}",
        limit=100,
        window_seconds=60,
    )


async def login_rate_limit(request: Request):
    client_ip = request.client.host if request.client else "unknown"

    await enforce_rate_limit(
        client_id=f"login:{client_ip}",
        limit=5,
        window_seconds=60,
    )


@app.get(
    "/api/products",
    dependencies=[Depends(general_api_limit)],
)
async def list_products():
    return {"products": []}


@app.post(
    "/api/login",
    dependencies=[Depends(login_rate_limit)],
)
async def login():
    return {"message": "Login request accepted"}

The separate key prefixes prevent the general API counter from being shared with the login counter.

However, this example is only a demonstration of rate-limit configuration. A real login endpoint must also validate credentials, apply appropriate authentication controls, and avoid leaking sensitive information.

For authentication, it may be useful to combine IP-based limits with account-based limits and broader abuse detection.

Be careful with account-based limits: an attacker shouldn't be able to lock out another user's account simply by deliberately exhausting that user's allowance.

11. Rate Limit by Authenticated User Instead of IP

IP-based limits can be useful for public endpoints, but they have limitations.

Multiple legitimate users may share the same public IP address, particularly in offices, schools, mobile networks, and households.

Conversely, an attacker may distribute requests across many IP addresses.

For authenticated APIs, a user-based identifier can provide more predictable limits.

For example:

async def limit_by_user(
    request: Request,
    current_user=Depends(get_current_user),
):
    await enforce_rate_limit(
        client_id=f"user:{current_user.id}",
        limit=300,
        window_seconds=60,
    )

Here, get_current_user represents your application's existing authentication dependency. It must be implemented to validate the user's credentials or token before identifying the user.

This code also requires the relevant imports and a real get_current_user implementation before it can run.

In a production application, you might combine multiple policies:

  • Per-IP limits for broad abuse protection.

  • Per-user limits for authenticated API usage.

  • Per-endpoint limits for expensive operations.

  • Per-API-key limits for developer integrations.

  • Global limits to protect shared infrastructure.

The correct combination depends on the application's threat model and business requirements.

12. Return Useful Rate-Limit Headers

A good API should tell clients when they are being limited and, where appropriate, how long they should wait.

The Retry-After header is especially useful when a request has been rejected.

For example:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 24

{
  "detail": "Rate limit exceeded. Please try again later."
}

In this response, the client should wait approximately 24 seconds before retrying.

You can also expose headers such as:

  • RateLimit-Limit: the configured request allowance.

  • RateLimit-Remaining: the remaining allowance.

  • RateLimit-Reset: when the current window resets.

Header naming and semantics depend on the API's chosen standard and implementation. If you expose rate-limit headers, document them clearly and follow a consistent convention.

For the fixed-window algorithm, the script can be extended to return the current counter and window reset information.

One implementation detail matters: clients should not assume that a displayed remaining count is guaranteed to remain accurate after the response is sent. Other requests may consume the remaining allowance concurrently.

13. Handling Redis Failures

So far, our implementation assumes Redis is available.

Production systems need an explicit policy for what happens when Redis becomes unreachable.

Suppose a request reaches the rate limiter, but Redis is temporarily unavailable.

Should the API reject the request or allow it to continue?

There are two common approaches.

Fail-Closed

Reject requests when the rate limiter cannot verify the allowance.

This is appropriate when rate limiting protects a particularly sensitive resource, such as an expensive operation or an endpoint with strict usage controls.

The trade-off is that a Redis outage can affect API availability.

Fail-Open

Allow requests to continue when the rate limiter is unavailable.

This can preserve availability for lower-risk endpoints, but it means the application may temporarily process requests without enforcing the configured limit.

Neither policy is universally correct.

For example, an application with expensive AI inference endpoints may prefer to reject requests when shared rate-limit state is unavailable. A less sensitive public content endpoint may tolerate a temporary fallback policy.

Implement a Fail-Closed Dependency

The existing implementation will raise a Redis exception if Redis fails.

FastAPI will generally turn an unhandled exception into a server error, but we should handle this failure deliberately.

import logging

from fastapi import HTTPException, status
from redis.exceptions import RedisError

logger = logging.getLogger(__name__)


async def enforce_rate_limit(
    client_id: str,
    limit: int = 100,
    window_seconds: int = 60,
) -> None:
    key = f"rate-limit:v1:{client_id}"

    try:
        allowed, retry_after = await check_rate_limit(
            key=key,
            limit=limit,
            window_seconds=window_seconds,
        )
    except RedisError as exc:
        logger.exception("Rate limiter Redis operation failed")

        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Rate limiting service is temporarily unavailable.",
            headers={"Retry-After": "1"},
        ) from exc

    if not allowed:
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail="Rate limit exceeded. Please try again later.",
            headers={
                "Retry-After": str(max(1, retry_after)),
            },
        )

This example chooses a fail-closed policy: the protected request is rejected if Redis cannot evaluate the limit.

The Retry-After value on a 503 response is only a short retry hint, not a guarantee that Redis will recover within one second. You may prefer a different response policy based on your infrastructure.

Also, test Redis connection failures, timeouts, and pool exhaustion separately. Different failures can surface through different exception types, and an overall application error-handling strategy should account for them.

14. Testing the Rate Limiter

Rate-limiting code should be tested for correctness, not just for whether it returns a 429 response.

We need to verify that:

  1. Requests within the limit succeed.

  2. Requests beyond the limit are rejected.

  3. A rejected request includes Retry-After.

  4. A new window eventually allows requests again.

  5. Concurrent requests do not exceed the configured allowance.

  6. Redis failures follow the application's chosen policy.

Here is a simple test for the counter function using a dedicated test Redis instance.

import pytest

from app.limiter import check_rate_limit, redis_client


@pytest.mark.asyncio
async def test_rate_limit_counter():
    key = "test:rate-limit:user-123"

    await redis_client.delete(key)

    try:
        results = []

        for _ in range(4):
            results.append(
                await check_rate_limit(
                    key=key,
                    limit=3,
                    window_seconds=60,
                )
            )

        assert [allowed for allowed, _ in results] == [
            True,
            True,
            True,
            False,
        ]
    finally:
        await redis_client.delete(key)

Install the test dependencies:

pip install pytest pytest-asyncio

This test assumes the configured Redis instance is a dedicated test service and that the test runner is configured to support asynchronous tests.

Don't run destructive tests against a shared production Redis instance. Use a dedicated database or instance, unique test keys, and appropriate cleanup.

Test the HTTP Response

You can also test the endpoint with FastAPI's test client.

from fastapi.testclient import TestClient

from app.main import app


def test_api_rate_limit():
    with TestClient(app) as client:
        responses = [
            client.get("/api/data")
            for _ in range(101)
        ]

    assert all(
        response.status_code == 200
        for response in responses[:100]
    )

    assert responses[100].status_code == 429

    assert "Retry-After" in responses[100].headers

This test assumes a clean counter, no competing requests using the same client identity, and a test configuration that points to a dedicated Redis instance.

In practice, it is better to make rate-limit settings configurable in tests so you can use a small allowance and avoid generating unnecessary traffic.

For a complete test suite, also cover concurrent requests and Redis failures.

15. Production Considerations

A working rate limiter is only the starting point. Production traffic introduces additional challenges.

Use a Managed or Properly Secured Redis Deployment

For production, configure Redis with appropriate network isolation, authentication, TLS when required, monitoring, and resource limits.

Don't expose Redis directly to the public internet.

If Redis is shared with caching or other workloads, consider using a separate instance or carefully isolating rate-limit keys and capacity. Rate limiting should remain reliable even when unrelated application activity increases.

Set Appropriate Timeouts

A rate limiter that waits too long for Redis can increase API latency and tie up application resources.

Configure connection and operation timeouts based on your service's latency budget.

A timeout doesn't solve the underlying problem, but it prevents the application from waiting indefinitely.

Plan for High Traffic

Redis scripts execute atomically, which is useful for correctness. However, long-running scripts can delay other Redis operations.

Keep scripts short and avoid placing expensive work inside them.

Monitor command latency, Redis CPU usage, connection counts, and memory utilization.

Use Appropriate Key Design

Rate-limit keys should distinguish the relevant client and policy.

For example:

rate-limit:v1:ip:203.0.113.10
rate-limit:v1:user:12345
rate-limit:v1:api-key:client-abc

These examples illustrate naming conventions only. Avoid including sensitive credentials or raw authentication tokens in Redis keys.

If identifiers contain untrusted data, normalize or encode them consistently. For deployments using Redis Cluster, remember that multi-key scripts must satisfy the cluster's key-slot requirements.

Consider Redis Memory and Eviction

Rate-limit keys expire, but a high-cardinality workload can still generate many active keys.

An attacker who can create many unique identifiers may increase memory consumption.

Use a sensible keying strategy, monitor key cardinality, and choose Redis capacity and eviction settings deliberately.

For strict enforcement, be careful with eviction policies that might remove active rate-limit counters. If counters disappear unexpectedly, clients may receive additional allowance.

Don't Trust IP Addresses Without a Proxy Strategy

Behind a reverse proxy, the apparent client address may be the proxy's address.

Configure trusted proxies correctly. Never use arbitrary client-provided forwarding headers as the sole source of identity.

Combine Rate Limiting With Other Controls

Rate limiting doesn't replace:

  • Authentication and authorization.

  • Request validation.

  • Abuse detection.

  • Web application firewall rules.

  • Connection limits.

  • Request body size limits.

  • Database query optimization.

  • Infrastructure-level DDoS protection.

These controls address different types of risk and work best together.

16. Fixed Window Limitations and When to Upgrade

Our implementation uses a fixed window that begins when the first request creates a counter key.

This is simple and efficient, but it has two important limitations.

First, it doesn't represent a continuously moving 60-second window. A client can make requests near the end of one window and then make more requests immediately after the next window begins.

Second, because the window starts with the first request, it isn't aligned to wall-clock minute boundaries.

These behaviors aren't necessarily bugs. They're properties of this particular algorithm.

If the application requires more precise control, consider a sliding-window counter, a sliding-window log, or a token bucket.

For example:

  • A public API with a generous allowance may work well with fixed windows.

  • An authentication endpoint may need additional controls beyond a simple request counter.

  • An AI inference endpoint may benefit from a token bucket that permits small bursts but limits average usage.

  • A billing-sensitive API may need both request limits and explicit usage accounting.

Choose the algorithm based on the behavior you want to guarantee, not just on implementation simplicity.

17. Improving the Design for a Real Application

The code in this guide provides the core of a Redis-backed fixed-window rate limiter, but a larger application will benefit from a few additional design decisions.

Make policies configurable.

Avoid hardcoding limits in many separate files. Centralize the policies so they can be changed and tested consistently.

Separate identity resolution from counter management.

One component should determine who the client is. Another should evaluate the corresponding rate-limit policy.

This makes it easier to support IP-based, user-based, and API-key-based limits.

Use observability.

Track metrics such as:

  • Total rate-limited requests.

  • Rate-limit decisions by endpoint.

  • Redis latency and errors.

  • Number of active rate-limit keys, where practical.

  • Application response latency.

  • Memory usage and connection pool saturation.

Avoid using raw IP addresses, user IDs, or API keys as unrestricted metric labels because high-cardinality labels can make monitoring expensive and may expose sensitive information.

Document the client behavior.

Tell API consumers what the limits mean, how to interpret 429 responses, and how to use Retry-After.

Plan for multiple application instances.

Make sure every instance uses the same intended Redis environment and compatible key format. Otherwise, the application may accidentally enforce different limits across deployments.

Test deployment and failure scenarios.

Verify behavior during Redis restarts, network interruptions, rolling deployments, and changes to rate-limit configuration.

These details often matter more in production than the basic counter implementation.

Conclusion

Rate limiting is an important part of building reliable APIs, particularly when endpoints are exposed to public traffic or perform expensive operations.

An in-memory dictionary can demonstrate the concept, but it doesn't provide shared state across workers, durable coordination, or automatic expiration.

Redis provides a practical foundation for distributed rate limiting. By combining Redis counters with an atomic Lua script, we can ensure that checking and incrementing a request counter happens as one operation.

FastAPI dependencies then make it straightforward to apply different policies to different endpoints. HTTP 429 responses and Retry-After headers help clients understand when they should retry, while explicit Redis failure handling makes the application's availability and security trade-offs clearer.

For production use, pay attention to proxy trust, identity selection, Redis timeouts, key cardinality, observability, and algorithm choice.

The key lesson is simple: a production-ready rate limiter is more than a request counter. It's a shared, atomic policy enforcement mechanism that must behave predictably under concurrent traffic and infrastructure failures.

Start with a clear policy, measure its impact, test it under realistic conditions, and evolve the implementation as your application's traffic and security requirements grow.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘