Scenario
intermediate
Slow API Endpoint: N+1 Query Problem
Fix a Django REST endpoint responding in 8 seconds for 500 users by eliminating N+1 queries with annotate() and prefetch_related().
The Situation
Senior Python developer / backend engineering interviews
Context: A Django REST API endpoint that lists all users and their order counts is responding in 8 seconds for 500 users. The database has proper indexes. How would you fix it?
# SLOW — N+1 queries (1 query for users + 1 query per user for orders)
class UserListView(APIView):
def get(self, request):
users = User.objects.all() # Query 1: SELECT * FROM users
result = []
for user in users:
result.append({
"id": user.id,
"name": user.name,
"order_count": user.orders.count() # Query 2...501: SELECT COUNT(*)
})
return Response(result)
# FAST — Single query with annotation
from django.db.models import Count
class UserListView(APIView):
def get(self, request):
users = User.objects.annotate(
order_count=Count('orders') # Single JOIN — one query total
).values('id', 'name', 'order_count')
return Response(list(users))
# Alternatively, prefetch_related for complex nested data:
users = User.objects.prefetch_related('orders').all()
for user in users:
# orders already loaded in 2 queries total, not N+1
count = len(user.orders.all())
Debugging tool:
# Django Debug Toolbar or django-silk shows query count
from django.db import connection
def get_query_count():
return len(connection.queries)
# Or log all queries during development
import logging
logging.getLogger('django.db.backends').setLevel(logging.DEBUG)
What You Learned
- Spotting N+1 queries
- annotate() vs prefetch_related()
- Measuring query counts
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form