Simple Rate Limiter (Cache Based)
A snippet showing how to throttle actions with a simple cache-based limiter.
# models.py
from django.db import models
class Action(models.Model):
key = models.CharField(max_length=100)
at = models.DateTimeField(auto_now_add=True)
# admin.py
from django.contrib import admin
from .models import Action
@admin.register(Action)
class ActionAdmin(admin.ModelAdmin):
list_display = ("key","at")
# Result (utils.py)
from django.core.cache import cache
def is_rate_limited(user_id, limit=5, window=60):
key = f"rl:{user_id}"
count = cache.get(key, 0) + 1
if count == 1: cache.set(key, count, timeout=window)
else: cache.incr(key)
return count > limit
Explanation:
- Use cache keys per user/action to count within a time window.
-
Tune
limitandwindowfor your use case; consider IP + user keys.
- Category Utilities & Miscellaneous
- Total Views 818
- Last Modified 03 July, 2026
- Tags #rate limit #security #cache #utilities
Previous snippet
Build Absolute URLs in Code
Next snippet