PYTHON

Implement API Rate Limiting with Redis in Flask

Protect your Flask API from abuse and brute-force attacks by implementing effective rate limiting using Redis, ensuring fair access and stability.

from flask import Flask, jsonify, request
import redis
import time

app = Flask(__name__)

# Connect to Redis
# For production, use environment variables for host, port, db, etc.
redis_client = redis.Redis(host='localhost', port=6379, db=0)

# Rate limiting configuration
RATE_LIMIT_DURATION = 60 # seconds
RATE_LIMIT_REQUESTS = 10 # requests per duration

def rate_limit(key, duration, requests):
    """
    Applies a simple fixed-window rate limit.
    Returns True if allowed, False if rate limited.
    """
    current_time = int(time.time())
    window_start = current_time // duration
    key_name = f"rate_limit:{key}:{window_start}"

    # Increment the counter for this window
    count = redis_client.incr(key_name)

    # Set expiration for the key if it's new, to clean up old windows
    if count == 1:
        redis_client.expire(key_name, duration)

    return count <= requests

@app.route('/api/data')
def get_data():
    user_ip = request.remote_addr # Or use a user ID if authenticated
    if not rate_limit(user_ip, RATE_LIMIT_DURATION, RATE_LIMIT_REQUESTS):
        return jsonify({"message": "Too many requests. Please try again later."}), 429

    return jsonify({"message": "Here is your data!"})

@app.route('/api/status')
def get_status():
    # This endpoint might have a different rate limit or no rate limit
    return jsonify({"status": "OK"})

if __name__ == '__main__':
    app.run(debug=True)
How it works: This Flask snippet demonstrates how to implement a basic API rate limiting mechanism using Redis. It defines a `rate_limit` function that uses a fixed-window counter approach: for a given `key` (e.g., user's IP address or authenticated user ID), it increments a Redis counter within a specific time `duration`. If the request count exceeds the allowed `requests` for that duration, it rejects the request with a 429 Too Many Requests status. Redis's `INCR` command and `EXPIRE` command are used for atomic increments and automatic cleanup of old rate limit windows, making it efficient for high-concurrency scenarios.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs