Skip to main content

Flask-Limit

Build Documentation image image image image

A lightweight, high-performance rate-limiting extension for Flask applications. Flask-Limit protects your API endpoints from brute-force attacks and abuse by restricting how many requests a client can make within a given time window.


Features

  • Flexible Backends: In-memory store for development; Redis for distributed production deployments.
  • ⚙️ Route-Level & Global Controls: Set global limits or override rules on individual routes.
  • 🔌 Auto-Registering Extensibility: Add custom storage backends (MongoDB, DynamoDB, Postgres) simply by subclassing Limiter.
  • 🛠️ Customizable Responses: Customize rate-limit exceeded responses globally or per endpoint.
  • 🏷️ Standard HTTP Headers: Automatically injects X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers.

Installation

Install the base package using pip:

pip install flask-limit

Optional Extras

To use third-party storage backends, install the corresponding extra:

# Redis Backend
pip install flask-limit[redis]

# All Backends
pip install flask-limit[all]

Configuration

Configure default behaviors using standard Flask app.config keys:

Config Key Default Value Description
RATELIMIT_LIMIT 100 Default maximum requests allowed per window.
RATELIMIT_PERIOD 60 Default window duration in seconds.
RATELIMIT_KEY_PREFIX "ratelimit" Prefix prepended to backend tracking keys.
RATELIMIT_REDIS_URL "redis://localhost:6379/0" Redis connection URL when using the redis backend.
RATELIMIT_RESPONSE None Application-level fallback for rate limit exceeded responses.

Quickstart

1. In-Memory Backend (Single Process)

Ideal for local testing and single-worker setups:

from flask import Flask, jsonify
from flask_limit import RateLimiter

app = Flask(__name__)
app.config["RATELIMIT_LIMIT"] = 50
app.config["RATELIMIT_PERIOD"] = 60

# Initialize with default memory backend
limiter = RateLimiter(app, limiter="memory")

# Uses application defaults (50 requests / 60s)
@app.route("/api/users")
@limiter.rate_limit
def get_users():
    return jsonify({"users": []})

# Route-specific override (5 requests / 10s)
@app.route("/api/login", methods=["POST"])
@limiter.rate_limit(limit=5, period=10)
def login():
    return jsonify({"status": "authenticated"})

2. Redis Backend (Production / Multi-Worker)

Required for multi-worker environments (Gunicorn, uWSGI) or distributed servers:

from flask import Flask, jsonify
from flask_limit import RateLimiter

app = Flask(__name__)
app.config["RATELIMIT_REDIS_URL"] = "redis://localhost:6379/0"

# Initialize with Redis backend
limiter = RateLimiter(app, limiter="redis")

@app.route("/api/data")
@limiter.rate_limit(limit=100, period=60)
def get_data():
    return jsonify({"data": "ok"})

Customizing Exceeded Limit Responses

When a client hits a rate limit, Flask-Limit returns a 429 Too Many Requests status code. You can customize the response at the application or route level.

Application-Wide Response

Assign a function or response tuple to RATELIMIT_RESPONSE in app.config:

from flask import jsonify
from flask_limit.types import RateLimitInfo

def custom_limit_exceeded(info: RateLimitInfo):
    return jsonify({
        "error": "rate_limit_exceeded",
        "retry_after_seconds": info.reset,
        "max_allowed": info.limit
    }), 429

app.config["RATELIMIT_RESPONSE"] = custom_limit_exceeded

Route-Level Response Override

Pass a callable or tuple directly to the @limiter.rate_limit decorator:

@app.route("/api/strict")
@limiter.rate_limit(
    limit=2,
    period=60,
    response=("Custom 429: Too many requests on this endpoint.", 429)
)
def strict_route():
    return jsonify({"status": "ok"})

Custom Backends

Creating a custom storage backend is seamless. Simply inherit from Limiter and define a name in the class header—Flask-Limit will register it automatically!

from flask_limit.limiters import Limiter

class MemcachedRateLimit(Limiter, name="memcached"):

    @classmethod
    def from_app(cls, app):
        # Build your backend instance using app config
        return cls(server=app.config["MEMCACHED_SERVER"])

    def is_allowed(self, key: str, limit: int, period: int):
        # Return tuple: (allowed: bool, remaining: int, reset: int)
        return True, limit - 1, period

    def cleanup(self, key=None):
        pass

# Use your new custom backend immediately!
limiter = RateLimiter(app, limiter="memcached")

Documentation

For full API references, architecture guides, and Sphinx docs, check out the Documentation in the repository.


License

This project is licensed under the MIT License.

Release files for flask-limit 3.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flask-limit 3.0.0
File Size Uploaded
flask_limit-3.0.0.tar.gz 710.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for flask-limit 3.0.0
File Interpreter ABI Platform
flask_limit-3.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 720.6 kB

Release files / flask_limit-3.0.0.tar.gz

Download URL flask_limit-3.0.0.tar.gz
Size 710.4 kB
Tags Source
SHA-256 checksum
How to use checksums
48301d6431a8eaab5e1945ce8837a7a4d69504c86d8446296ad91efc868143ed
BLAKE2b-256 checksum
How to use checksums
c5892e892b5f973428eb52de89c2d59b13bd5d68c5ea6384065703c216748a0a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 19, 2026.

Transparency log

Release files / flask_limit-3.0.0-py3-none-any.whl

Download URL flask_limit-3.0.0-py3-none-any.whl
Size 10.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8cfbc57470666df28cf8a8e6135ee5fa48fd50c350e19fb308db9c45ad1624e1
BLAKE2b-256 checksum
How to use checksums
cdba13a03a8eca229788143454273ad9a7bb57250e470a0c3b8b7455727b50c8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 19, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

3.0.0 This release

2 release files

2.0.5

1 release file

2.0.4

1 release file

2.0.3

1 release file

2.0.2

1 release file

2.0.1

1 release file

2.0

1 release file

1.0.5

1 release file

1.0.4

1 release file

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page