[aryan@dev]
← cd ~/writing

Why Stacking Shared and Per-Actor DRF Throttles Causes Self-Inflicted DoS

How Django REST Framework's APIView.check_throttles() drains shared rate-limit buckets even when a stricter per-IP or per-phone throttle rejects the request, and the two-phase post-send fix.

On an OTP login endpoint, stacking multiple rate limits in Django REST Framework looks like standard defense in depth:

class RequestOTPView(APIView):
    throttle_classes = [
        PerIPOTPThrottle,        # e.g., 5/min per IP
        PerPhoneOTPThrottle,     # e.g., 3/min per phone
        PerTenantOTPThrottle,    # shared 20/hour SMS cap per storefront
    ]

In production, this exact configuration let a single abusive client lock out every legitimate customer on a storefront, even while the per-IP and per-phone throttles were actively rejecting the attacker’s requests.

What APIView.check_throttles() does

DRF evaluates throttle_classes in a loop:

def check_throttles(self, request):
    throttle_durations = []
    for throttle in self.get_throttles():
        if not throttle.allow_request(request, self):
            throttle_durations.append(throttle.wait())
    if throttle_durations:
        ...
        self.throttled(request, duration)

Two details combine into a bug:

  1. DRF does not short-circuit. It evaluates every throttle in throttle_classes so it can compute the maximum Retry-After duration across all failing throttles.
  2. SimpleRateThrottle.allow_request() mutates state on pass. When allow_request() returns True, it immediately calls throttle_success(), appending the current timestamp to the cache bucket without knowing whether a previous or subsequent throttle in the list rejected the request.

When a bot hammers a single storefront’s OTP endpoint from one IP, the sequence plays out like this:

Request 1..5  : PerIP PASS, PerPhone PASS/FAIL, PerTenant PASS (+5 hits)
Request 6..20 : PerIP FAIL (blocked!), PerPhone FAIL (blocked!),
                PerTenant PASS → throttle_success() STILL RECORDS +15 HITS!
Request 21    : Legitimate customer from a clean IP arrives
                → PerTenant bucket is at 20/20 → 429 Too Many Requests!

Every rejected spam request still drained the shared PerTenantOTPThrottle bucket. Reordering throttle_classes does not help, because check_throttles() iterates the entire list regardless of earlier failures.

Fix: decouple admission check from budget consumption

Per-actor throttles (PerIP, PerPhone) are fine in throttle_classes: if an attacker burns their own IP or phone bucket on rejected requests, they only hurt themselves.

A shared, cost-bearing quota (like a per-tenant hourly SMS cap) must never be decremented by a request that was rejected by another throttle, serializer validation, or an upstream error.

We pulled PerTenantOTPThrottle out of throttle_classes and split it into two explicit operations around the SMS dispatch:

  1. A read-only pre-check inside the view/service (after DRF throttles and payload validation succeed) to verify the tenant still has remaining SMS budget without mutating the counter.
  2. A post-send record_send() call that increments the tenant’s sliding window only when the SMS dispatch is accepted and sent.
# 1. Per-actor throttles stay in throttle_classes (self-contained blast radius)
class RequestOTPView(APIView):
    throttle_classes = [PerIPOTPThrottle, PerPhoneOTPThrottle]

    def post(self, request):
        phone = validate_phone(request.data)
        tenant = request.tenant

        # 2. Read-only check against shared quota (does not mutate cache)
        if not tenant_otp_budget.has_capacity(tenant.id):
            raise Throttled(wait=tenant_otp_budget.wait_seconds(tenant.id))

        # 3. Only actual sends consume shared budget
        sms_gateway.send_otp(phone=phone, tenant=tenant)
        tenant_otp_budget.record_send(tenant.id)
        return Response(status=status.HTTP_202_ACCEPTED)

Rule of thumb

Do not put a shared multi-user bucket in DRF’s throttle_classes alongside per-actor throttles. Because APIView.check_throttles() evaluates every throttle without short-circuiting and SimpleRateThrottle writes on pass, any rejected attacker can drain a shared bucket to zero. Keep per-actor limits in throttle_classes, and charge shared cost-bearing budgets only after validation, or after the side effect occurs.

Discussion

Comments

Loading…

Leave a note

Comments are moderated before appearing publicly.