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 limit and window for your use case; consider IP + user keys.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.