← Back to Python, page 4

python-0077 · Hard senior

A Django or FastAPI endpoint is slow under load. Walk through how you would find and fix the cause as a senior engineer.

Start from measurements: per-endpoint latency percentiles and traces that split time between database, external calls and Python code. Most slow endpoints are slowed by queries (N+1 patterns, missing indexes), blocking calls inside async code, or serialisation of large payloads. Fix the dominant cost, add a regression test or budget, and re-measure under the same load.

Full answer
python
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript(
    "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);"
    "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER);")
con.executemany("INSERT INTO customers VALUES (?, ?)", [(i, f"c{i}") for i in range(5)])
con.executemany("INSERT INTO orders VALUES (?, ?)", [(i, i % 5) for i in range(20)])
count = {"n": 0}
con.set_trace_callback(lambda sql: count.__setitem__("n", count["n"] + 1))

orders = con.execute("SELECT id, customer_id FROM orders").fetchall()
names = [con.execute("SELECT name FROM customers WHERE id = ?", (cid,)).fetchone()[0] for _, cid in orders]
print("N+1 queries:", count["n"])

count["n"] = 0
orders = con.execute("SELECT id, customer_id FROM orders").fetchall()
ids = sorted({cid for _, cid in orders})
marks = ",".join("?" * len(ids))
lookup = dict(con.execute(f"SELECT id, name FROM customers WHERE id IN ({marks})", ids).fetchall())
names2 = [lookup[cid] for _, cid in orders]
print("batched queries:", count["n"], names == names2)

Output:

text
N+1 queries: 21
batched queries: 2 True

The run contrasts an N+1 access pattern with a batched one using an in-memory SQLite database, counting queries rather than timing them: 21 queries for 20 orders versus 2. The same counting approach works in tests for real services.

Investigation checklist:

  • Tracing (OpenTelemetry, APM): which spans dominate for slow requests?
  • Database: query counts per request, slow query logs, EXPLAIN for the worst query.
  • Async misuse: a blocking driver or time.sleep inside an async endpoint stalls the event loop for every request.
  • External calls: missing timeouts, sequential calls that could run concurrently.
  • Payloads: serialising thousands of rows; paginate and select only needed fields.
  • Workers: too few processes for CPU-bound work, or too many for the database's connection limit.

Then fix, add a query-count assertion or latency budget in CI, and confirm with a load test (for example locust) before and after.

python
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript(
    "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);"
    "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER);")
con.executemany("INSERT INTO customers VALUES (?, ?)", [(i, f"c{i}") for i in range(5)])
con.executemany("INSERT INTO orders VALUES (?, ?)", [(i, i % 5) for i in range(20)])
count = {"n": 0}
con.set_trace_callback(lambda sql: count.__setitem__("n", count["n"] + 1))

orders = con.execute("SELECT id, customer_id FROM orders").fetchall()
names = [con.execute("SELECT name FROM customers WHERE id = ?", (cid,)).fetchone()[0] for _, cid in orders]
print("N+1 queries:", count["n"])

count["n"] = 0
orders = con.execute("SELECT id, customer_id FROM orders").fetchall()
ids = sorted({cid for _, cid in orders})
marks = ",".join("?" * len(ids))
lookup = dict(con.execute(f"SELECT id, name FROM customers WHERE id IN ({marks})", ids).fetchall())
names2 = [lookup[cid] for _, cid in orders]
print("batched queries:", count["n"], names == names2)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Measure with traces and percentiles
  • Database access dominates most slow endpoints
  • Blocking calls stall async servers
  • Paginate and trim payloads
  • Guard fixes with tests and budgets

Common mistakes

  • Optimising Python code before checking queries
  • Load testing different scenarios before and after

Follow-ups

  • How would you detect blocking calls in asyncio?
  • How do you size worker processes?

Tips

  • Count queries per request