Full answer
A structured approach beats guessing.
- Confirm and scope the problem
- Is it every request or some? One endpoint or all? Since when? Correlate with deploys, data growth, traffic peaks and infrastructure changes.
- Look at percentiles (p50, p95, p99), not averages.
- Find where the time goes
- An APM or tracing tool (OpenTelemetry with a backend, Sentry Performance, Datadog, New Relic) breaks a request into database spans, HTTP calls, cache calls and Python time.
- Without APM: log query counts and time per request with a small middleware (as in the snippet), turn on PostgreSQL
pg_stat_statementsandlog_min_duration_statement, and use Django Debug Toolbar ordjango-silkagainst a staging copy with realistic data.
- Typical causes and fixes
- N+1 queries: a new field in a template or serializer touches a relation per row. Fix with
select_related/prefetch_related, and addassertNumQueriesto the test. - Missing index: data grew, the planner switched to a sequential scan. Check with
EXPLAIN ANALYZE; add an index (concurrently). - Unbounded results: a list page without pagination now shows 40,000 rows.
- External calls: an API that slowed down or timed out. Add timeouts, caching, or move to a background task.
- Cache problems: a key changed or the cache server was replaced, so everything is computed again.
- Locks: a migration or long transaction blocking writes. Check
pg_stat_activityandpg_locks. - Python work: heavy loops or serialization. Profile with
py-spy(safe on production processes) orcProfilelocally. - Resource limits: too few workers, CPU throttling, connection pool exhaustion.
- Fix and protect
- Change one thing at a time and measure again.
- Add a regression guard: query-count test, load test in CI, or an alert on p95 latency.
- Write a short incident note: cause, fix, and how it will be caught earlier next time.
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", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import logging
import time
from django.db import connection, models
from django.http import HttpResponse
from django.test import Client
from django.urls import path
logging.basicConfig(format="%(message)s", level=logging.INFO)
log = logging.getLogger("perf")
class QueryBudgetMiddleware:
"""Logs query count and database time per request; warns over budget."""
def __init__(self, get_response, budget=10):
self.get_response = get_response
self.budget = budget
def __call__(self, request):
stats = {"count": 0, "time": 0.0}
def wrapper(execute, sql, params, many, context):
start = time.perf_counter()
try:
return execute(sql, params, many, context)
finally:
stats["count"] += 1
stats["time"] += time.perf_counter() - start
with connection.execute_wrapper(wrapper):
response = self.get_response(request)
level = logging.WARNING if stats["count"] > self.budget else logging.INFO
log.log(level, "%s queries=%d over_budget=%s", request.path, stats["count"],
stats["count"] > self.budget)
response["X-Query-Count"] = str(stats["count"])
return response
class Teacher(models.Model):
name = models.CharField(max_length=40)
class Meta:
app_label = "school"
class Course(models.Model):
title = models.CharField(max_length=40)
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Teacher)
editor.create_model(Course)
t = Teacher.objects.create(name="Dr. Menon")
Course.objects.bulk_create([Course(title=f"Course {i}", teacher=t) for i in range(30)])
def slow_page(request):
return HttpResponse(", ".join(f"{c.title} by {c.teacher.name}" for c in Course.objects.all()))
def fixed_page(request):
qs = Course.objects.select_related("teacher")
return HttpResponse(", ".join(f"{c.title} by {c.teacher.name}" for c in qs))
urlpatterns = [path("slow/", slow_page), path("fixed/", fixed_page)]
settings.ROOT_URLCONF = __name__
settings.MIDDLEWARE = [f"{__name__}.QueryBudgetMiddleware"]
c = Client()
print("slow:", c.get("/slow/")["X-Query-Count"])
print("fixed:", c.get("/fixed/")["X-Query-Count"])
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. Log lines from the middleware go to stderr; stdout shows the query counts from the response header. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): slow: 31 fixed: 1
Key points
- Measure with percentiles and tracing before changing code
- Correlate with deploys and data growth
- Check N+1, missing indexes, unbounded lists, external calls, cache, locks
- Use EXPLAIN ANALYZE, pg_stat_statements, py-spy
- Add regression guards such as assertNumQueries and latency alerts
Common mistakes
- Optimising code before measuring where time goes
- Looking only at averages and missing slow p99 requests
- Testing on a tiny local database that hides missing indexes
- Fixing the symptom without adding a regression test or alert
Follow-ups
- How would you profile a production process without restarting it?
- What does EXPLAIN ANALYZE show that EXPLAIN does not?
- How would you prevent this regression from shipping again?
Tips
- Describe a method, not a single trick
- Name concrete tools at each step
- Close with how you would prevent a repeat