Full answer
Pagination
An unpaginated list endpoint works with 50 rows and fails with 500,000. Set a default in REST_FRAMEWORK:
PageNumberPagination:?page=3. Simple; each page runsCOUNT(*)plusOFFSET, both slow on huge tables.LimitOffsetPagination:?limit=20&offset=40. Same OFFSET cost.CursorPagination: an opaque cursor encodes the position (for example the lastcreatedvalue). No count, no OFFSET, stable even when new rows arrive, but needs a unique, indexed ordering and does not allow jumping to page 37.
Set max_page_size so clients cannot ask for a million rows.
Throttling
AnonRateThrottle(by IP),UserRateThrottle(by user),ScopedRateThrottle(per endpoint,throttle_scope = "uploads").- Rates like
"100/hour"inDEFAULT_THROTTLE_RATES. Exceeding them returns 429 with aRetry-Afterheader. - Throttle state lives in the Django cache. With several servers, use Redis, otherwise each process counts separately.
- DRF throttling is a fairness tool, not DDoS protection. Put coarse rate limits at the proxy or CDN too.
- Behind a proxy, set
NUM_PROXIESso DRF picks the real client IP fromX-Forwarded-For.
Serializer performance
- Nested serializers and
SerializerMethodFieldoften hide one query per row. Useselect_related/prefetch_relatedinget_queryset()and test withassertNumQueries. - Annotate counts in SQL (
Count("loans")) instead ofobj.loans.count()per row. - For read-heavy endpoints,
values()plus a plain serializer, or caching, can cut serialisation time a lot. - Return only fields the client needs; consider separate list and detail serializers.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.core.cache import cache
from django.db import connection, models
from django.db.models import Count
from django.test.utils import CaptureQueriesContext
from django.urls import path
from rest_framework import generics, serializers
from rest_framework.pagination import CursorPagination
from rest_framework.test import APIClient
from rest_framework.throttling import AnonRateThrottle
settings.CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
class Member(models.Model):
name = models.CharField(max_length=40)
joined = models.IntegerField(unique=True)
class Meta:
app_label = "school"
class Loan(models.Model):
member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name="loans")
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Member)
editor.create_model(Loan)
for i in range(1, 8):
m = Member.objects.create(name=f"member{i}", joined=i)
Loan.objects.bulk_create([Loan(member=m) for _ in range(i % 3)])
class MemberSerializer(serializers.ModelSerializer):
loan_count = serializers.IntegerField(read_only=True)
class Meta:
model = Member
fields = ["name", "loan_count"]
class ByJoined(CursorPagination):
ordering = "joined"
page_size = 3
class FivePerMinute(AnonRateThrottle):
rate = "5/min"
class MemberList(generics.ListAPIView):
serializer_class = MemberSerializer
pagination_class = ByJoined
throttle_classes = [FivePerMinute]
authentication_classes = []
permission_classes = []
def get_queryset(self):
return Member.objects.annotate(loan_count=Count("loans"))
urlpatterns = [path("members/", MemberList.as_view())]
settings.ROOT_URLCONF = __name__
c = APIClient()
with CaptureQueriesContext(connection) as ctx:
page1 = c.get("/members/").json()
print([m["name"] for m in page1["results"]], [m["loan_count"] for m in page1["results"]])
print("queries for one page:", len(ctx.captured_queries))
page2 = c.get(page1["next"]).json()
print([m["name"] for m in page2["results"]])
codes = [c.get("/members/").status_code for _ in range(4)]
r = c.get("/members/")
print(codes, r.status_code, "Retry-After:", r.headers.get("Retry-After") is not None)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires djangorestframework. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['member1', 'member2', 'member3'] [1, 2, 0] queries for one page: 1 ['member4', 'member5', 'member6'] [200, 200, 200, 429] 429 Retry-After: True
Key points
- Paginate every list endpoint and cap page size
- CursorPagination avoids COUNT and OFFSET on large tables
- Throttles need a shared cache across servers
- Throttling is fairness, not DDoS protection
- Prefetch and annotate to avoid per-row queries in serializers
Common mistakes
- Shipping list endpoints without pagination
- Using page number pagination with COUNT(*) on a table with tens of millions of rows
- Relying on local-memory throttle state with several servers
- Calling .count() or a related lookup per row inside a serializer
Follow-ups
- How does CursorPagination encode its position?
- How would you rate limit a login endpoint more strictly than the rest?
- How do you find which serializer field causes extra queries?
Tips
- Compare the three paginators with their costs
- Mention 429 and Retry-After
- Show the annotate-instead-of-per-row-count fix