Skip to main content

A flexible and efficient rate limiting library for Django applications

Project description

Django Smart Ratelimit

CI PyPI version Downloads Python Versions Django Versions License

A high-performance rate limiting library for Django. Protects your APIs from abuse with atomic Redis operations, multiple algorithms, circuit breaking, and full async support -- optimized for distributed systems.

Key Features

  • Sync and Async -- Dual-mode support with native @ratelimit and @aratelimit decorators
  • Enterprise Reliability -- Built-in circuit breaker, automatic failover, and fail-open strategies
  • Multiple Algorithms -- Token bucket, sliding window, fixed window, and leaky bucket
  • Flexible Backends -- Redis (recommended), async Redis, in-memory, MongoDB, Memcached, Django ORM (database), or custom backends
  • Precise Control -- Rate limit by IP, user, header, or any custom callable
  • Shadow Mode -- Evaluate and log decisions without enforcing them for safe, zero-risk rollouts (docs)
  • Cost-Based (Weighted) Limiting -- Charge expensive requests more of the budget via a per-request cost (docs)
  • CIDR Allow/Deny Lists -- IPv4/IPv6 allowlists and denylists from inline CIDRs, files, or URL feeds (docs)
  • DRF Throttle Adapter -- Drop-in BaseThrottle classes for Django REST Framework (docs)
  • Observability -- Prometheus /metrics, OpenTelemetry spans and metrics, and structured JSON logging (docs)
  • Type-Safe Enums -- Optional Algorithm and RateLimitKey enums for autocomplete and typo-proof config
  • Configurable Proxy Trust -- RATELIMIT_TRUSTED_PROXIES for spoof-resistant client IP extraction behind load balancers (new in v3.1)
  • Adaptive Rate Limiting -- Dynamic limits based on CPU, memory, latency, time-of-day, and custom load indicators
  • Dynamic Rules -- Define and change limits at runtime from the Django admin, no redeploy (docs)
  • User-Aware Limiting -- Per-user tiers, Django-group mapping, temporary overrides, and API-key tiers (docs)
  • Analytics & Alerting -- Event logging, a staff dashboard, offender reports, and email/webhook alerts (docs)
  • Geographic & Multi-Tenant -- Per-country rates and per-tenant quotas (geo, tenants)
  • GraphQL -- Graphene middleware and a Strawberry extension with query-complexity weighting (docs)

Quick Start

Installation

pip install django-smart-ratelimit[redis]

Basic Usage

from django_smart_ratelimit import ratelimit

@ratelimit(key='ip', rate='5/m', block=True)
def login_view(request):
    return authenticate(request)

Keys and algorithms accept plain strings, or the RateLimitKey and Algorithm enums if you prefer autocomplete and a typo-proof contract. The two are interchangeable:

from django_smart_ratelimit import ratelimit
from django_smart_ratelimit.enums import Algorithm, RateLimitKey

@ratelimit(key=RateLimitKey.USER_OR_IP, rate='5/m', algorithm=Algorithm.TOKEN_BUCKET)
def login_view(request):
    return authenticate(request)

Async Support

from django_smart_ratelimit import aratelimit

@aratelimit(key='user', rate='100/h', block=True)
async def api_view(request):
    return await process(request)

Class-Based Views

Apply the decorator to a method with Django's method_decorator:

from django.utils.decorators import method_decorator
from django.views import View

from django_smart_ratelimit import ratelimit


class LoginView(View):
    @method_decorator(ratelimit(key='ip', rate='5/m', block=True))
    def post(self, request):
        return authenticate(request)

Configuration

Add to your Django settings:

RATELIMIT_BACKEND = 'redis'
RATELIMIT_REDIS = {'host': 'localhost', 'port': 6379, 'db': 0}
# Or point at a Redis URL instead of host/port:
# RATELIMIT_REDIS = {'url': 'redis://localhost:6379/0'}

# Optional: enable structured logging
RATELIMIT_LOGGING = {
    'ENABLED': True,
    'FORMAT': 'json',  # "json" or "text"
}

# Optional: enable Prometheus metrics
RATELIMIT_PROMETHEUS = {
    'ENABLED': True,
}

If RATELIMIT_BACKEND is unset, the in-memory backend is used by default.

Documentation

Full documentation is hosted on Read the Docs:

Topic Description
Full Documentation Start here for the complete guide
Installation Optional extras: Redis, MongoDB, DRF, Prometheus, OpenTelemetry
Decorator API Every argument, including shadow mode and cost-based limiting
Migration Guide Steps for upgrading from django-ratelimit
Algorithms Deep dive into token bucket, sliding window, and more
Backends Redis, async Redis, memory, MongoDB, and the Django ORM database backend
Configuration Advanced settings, CIDR lists, proxy trust, and circuit breakers
Dynamic Rules Runtime, admin-editable rate-limit rules
User Tiers Tiers, groups, per-user overrides, and API-key tiers
Analytics Event logging, dashboard, offender reports, and alerting
Geographic / Multi-Tenant / GraphQL Per-country, per-tenant, and GraphQL limiting
Deployment Running in production behind proxies and load balancers
Design Philosophy Architecture decisions and comparison with alternatives

Compatibility

Supported Versions
Python 3.9, 3.10, 3.11, 3.12, 3.13, 3.14
Django 3.2, 4.2, 5.0, 5.1, 5.2, 6.0

Contributing

Contributions are welcome. Please see CONTRIBUTING.md for details on how to submit pull requests, report issues, and set up your development environment.

Community and Support

Sponsors

Support the ongoing development of Django Smart Ratelimit:

Sponsor

License

This project is licensed under the MIT License. See the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_smart_ratelimit-4.12.1.tar.gz (518.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_smart_ratelimit-4.12.1-py3-none-any.whl (229.5 kB view details)

Uploaded Python 3

File details

Details for the file django_smart_ratelimit-4.12.1.tar.gz.

File metadata

  • Download URL: django_smart_ratelimit-4.12.1.tar.gz
  • Upload date:
  • Size: 518.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for django_smart_ratelimit-4.12.1.tar.gz
Algorithm Hash digest
SHA256 bf89f5b904efa00cf238592eb3e33a1d0a73d60b3e1b54458800a8da8a507c0d
MD5 387dec8e0aab805c4ca89dd865f2fd04
BLAKE2b-256 fff817f498f178c27ef509e775daa9d286942c2ff836ea3eb0b4c14b873e8ea5

See more details on using hashes here.

File details

Details for the file django_smart_ratelimit-4.12.1-py3-none-any.whl.

File metadata

File hashes

Hashes for django_smart_ratelimit-4.12.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9dcfee14ab32b002bfb0c22ada5c3aec8f7080d9b591759497e4654d1604dcdf
MD5 a1b1fc4fc3a6a560080f904d45f93c5a
BLAKE2b-256 da8e23c9e568e4691ec68934acc586873a3e5dd3f92c07263fc635703a89649c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page