Skip to main content

Introduction

In this tutorial, we’ll learn how to add rate limiting to a FastAPI application using Upstash Redis. Rate limiting is essential for controlling API usage and with Upstash Redis, you can easily implement rate limiting to protect your API resources. We’ll set up a simple FastAPI app and apply rate limiting to its endpoints. With Upstash Redis, we’ll configure a fixed window rate limiter that allows a specific number of requests per given time period.

Environment Setup

First, install FastAPI, the Upstash Redis client, the Upstash rate limiting package, and an ASGI server:

Database Setup

Create a Redis database using the Upstash Console or Upstash CLI, and export the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN to your environment:
You can also use python-dotenv to load environment variables from your .env file.

Application Setup

In this example, we will build an API endpoint that is rate-limited to a certain number of requests per time window. If the limit is exceeded (e.g., by making more than 10 requests in 10 seconds), the API will return an HTTP 429 error with the message “Rate limit exceeded. Please try again later.” Create main.py:
main.py

Running the Application

Run the FastAPI app with Uvicorn:
Run the test function to check the rate limiting:

Testing Rate Limiting

Here’s the output you should see when running the test function:

Code Breakdown

  1. Redis and Rate Limiter Setup:
    • We initialize a Redis client with Redis.from_env() using environment variables for configuration.
    • We create a rate limiter using Ratelimit with a FixedWindow limiter that allows 10 requests per 10 seconds. The prefix option is set to organize the Redis keys used by the rate limiter.
  2. Rate Limiting the Endpoint:
    • For the /expensive_calculation endpoint, the rate limiter is applied by calling ratelimit.limit(identifier).
    • The identifier variable uniquely identifies this rate limit. You could use user-specific identifiers (like user IDs) to implement per-user limits.
    • If the request exceeds the allowed limit, an HTTP 429 error is returned.
  3. Expensive Calculation Simulation:
    • The do_expensive_calculation function simulates a resource-intensive operation. In real scenarios, this could represent database queries, file processing, or other time-consuming tasks.

Benefits of Rate Limiting with Redis

Using Redis for rate limiting helps control API usage across multiple instances of your app, making it highly scalable. Redis’s in-memory storage provides fast access to rate-limiting data, ensuring minimal performance impact on your API.