// notes · postgresql

Clearing 48 slow Postgres queries in two weeks

How five engineers worked through every slow query in a large Django monolith: how we picked the order, the six patterns behind most of them, and why the fix was often in Python, not in an index.

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:

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:

Pattern 6: don't run the query at all

Some of the best fixes deleted work:

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:

Summary

SymptomCauseFix
"Latest row" query fast for some ids, minutes for othersBackward index scan when nothing matchesDrop ORDER BY/LIMIT and pick in Python, or a partial index
.get() on JSONB is slow, .filter() is fastDjango's LIMIT 21 flips the plan to a seq scanFilter without LIMIT, keep .get() semantics
Poller reads huge rows and skips mostFiltering in PythonEXISTS in SQL, select only what the loop reads
Report runs the same query per rowN+1 aggregateOne batched query, on the replica
Slow inserts on a JSON log tableGIN fastupdate flushesTurn fastupdate off on that index
Heavy reads on the primaryDashboards never routedReplica decorator, auth from primary, writes stay put

What I would do again