The setup
The application is a long-lived, multi-tenant Django monolith on PostgreSQL: quote and policy flows, background pollers that talk to partner APIs, CRM screens and internal dashboards. Nothing was down, but the database spent a lot of time on a long tail of queries nobody had looked at in years.
I ran the clean-up: pulled the data, filed one ticket per query, and split the work across the team. Five of us shipped 29 pull requests over two weeks and closed all 48 query tickets, plus one for moving dashboard reads to a replica and one for a caller that should not have been running the query at all. I wrote or co-wrote seven of those PRs. This note is about what we learned, not who fixed what.
Step 1: rank by total time, not by the slowest run
The input was a pgBadger report from the primary. The instinct is to sort by the slowest single query. We sorted by total time instead: duration × number of runs.
That changed the list completely. The top item never had a slow run. It was a retention job deleting old rows in 1,000-row chunks: 4,829 runs, 8 h 50 min of database time in the report window. A lookup that took 5 minutes in a single run, and never again, ranked far lower.
Every ticket title carried the query shape, the total time and the run count, for example events: latest by product + tracker (1h05m total, 912 runs). That made the priority obvious without opening the ticket, and it let people pick work in order.
Rule of thumb: before writing a fix, run EXPLAIN (ANALYZE, BUFFERS) on a replica for the exact query from the log, and put the numbers in the PR. The plan, not the ORM code, tells you what is actually slow.
Pattern 1: ORDER BY … DESC LIMIT 1 that scans the whole table
The most common shape was "latest row for this thing":
Event.objects.filter(ticket_id=t).order_by("-created_on", "-id").first()
On PostgreSQL 13+, the planner often chooses to walk the created_on index backwards, with an Incremental Sort, and stop at the first row that matches the filter. That is fast when a match is near the top. When the ticket has no matching row, it walks the entire index. Same query, same plan, milliseconds or minutes depending on the data.
Two fixes, depending on how many rows the filter returns:
- Small result set: drop
ORDER BYandLIMIT, let Postgres use the index on the filter column, and pick the newest row in Python. It sounds backwards, but fetching 40 rows and callingmax()beats scanning millions. - Hot path with a fixed filter: add a partial index that matches the filter and the order, so the "latest" lookup is an index-only scan. One of these took a 26-second cold query down to an index read.
Pattern 2: the LIMIT 21 that Django adds to .get()
This one was new to most of us. Django's .get() adds LIMIT 21 so it can report "more than 20 objects returned". On a JSONB containment filter:
Payment.objects.get(payload__contains={"reference": ref})
the LIMIT can tip the planner from the GIN index on payload to a sequential scan, betting it will find a match early. It did not: up to 50.6 s for one payment callback. The fix was a small helper that runs the same filter without LIMIT and raises DoesNotExist / MultipleObjectsReturned exactly as .get() does, plus an explicit guard so an empty value never loads every row.
Pattern 3: load everything, filter in Python
Several background pollers checked the status of pending inspections with a partner API. Each one loaded every transaction for that partner in the lookback window, all columns, including large JSON payloads, and then skipped almost all of them in a Python loop.
The fix moved the filter into SQL with EXISTS:
pending = Inspection.objects.filter(transaction=OuterRef("pk"), status="PENDING")
Transaction.objects.filter(insurer=i, created_on__gte=since).filter(Exists(pending))
Measured at 31 ms on production data. The rewrite also fixed a real bug: the old version used an inner join, so a transaction with two pending inspections came back twice and was polled twice, which in one flow created a duplicate record. EXISTS returns each row once.
Pattern 4: one query per row
A report computed "most frequent IP address" for each quote with a separate GROUP BY query per quote, about 3.1 s each. We built the whole map once, 500 trackers per query, on the replica. Classic N+1, just with an aggregate instead of a foreign key.
Pattern 5: missing or misconfigured indexes
About a third of the tickets were plain missing indexes on columns used for date ranges and lookups. Two details mattered more than the indexes themselves:
- Build them concurrently. Every index went in with
AddIndexConcurrently(CREATE INDEX CONCURRENTLY) in its own non-atomic migration, so inserts on busy tables were never blocked during the build. - Check write-heavy GIN indexes. Inserts into a large request-log table took 1.3 to 4 s now and then. By default a GIN index collects new entries in a 4 MB pending list, and the insert that overflows the list merges it into the main index before returning. Autovacuum would only do that merge after tens of millions of inserts, so ordinary inserts paid for it. Setting
fastupdate = offon that index is a metadata change with no rebuild, and each insert now writes its own entries directly.
Pattern 6: don't run the query at all
Some of the best fixes deleted work:
- a quote-failure lookup ran on every results poll, up to 21 times per quote, even when the page showed no failure reasons; now it is skipped in that case,
- a state list that rarely changes was cached instead of recomputed per request,
- a payment-status check kept polling for 25 hours after the payment had completed; the fix was in the caller, not the query.
Moving dashboards to the read replica
Internal admin and support pages ran heavy read-only queries on the primary. We moved 30 admin pages and 5 support pages to the replica with a view decorator, and the details were where the risk was:
- The decorator loads the user, session and permissions from the primary before switching, so a fresh login or a revoked permission is never delayed by replica lag.
- Pages that write, and pages read right after a write (upload status, edit pages, success pages), stay on the primary. Otherwise a user saves something and does not see it.
- An existing "force this read to a database" helper used to clear the routing when it finished, which silently sent the rest of a replica view back to the primary. It now restores whatever was active before.
Summary
| Symptom | Cause | Fix |
|---|---|---|
| "Latest row" query fast for some ids, minutes for others | Backward index scan when nothing matches | Drop ORDER BY/LIMIT and pick in Python, or a partial index |
.get() on JSONB is slow, .filter() is fast | Django's LIMIT 21 flips the plan to a seq scan | Filter without LIMIT, keep .get() semantics |
| Poller reads huge rows and skips most | Filtering in Python | EXISTS in SQL, select only what the loop reads |
| Report runs the same query per row | N+1 aggregate | One batched query, on the replica |
| Slow inserts on a JSON log table | GIN fastupdate flushes | Turn fastupdate off on that index |
| Heavy reads on the primary | Dashboards never routed | Replica decorator, auth from primary, writes stay put |
What I would do again
- One ticket per query shape, with total time and run count in the title. It turned a vague "the DB is slow" into a queue anyone could pick from.
- Numbers in the PRs. Plans and timings made reviews about evidence, not ORM style.
- Look at the caller before the query. The cheapest query is the one that does not run.
- Spread the work. Five people now recognise these patterns on sight, which lasts longer than any single index.