The related-news panel on Statpro, my sports stats site, was failing quietly. The panel lists news stories related to the one you are reading, and it gets them from a single database function. Most calls worked. About 266 times every 24 hours, one Postgres function hit its statement timeout, and it never failed loudly enough for me to notice.
The ORDER BY disagreed with the index
The function sorted its results with published_at DESC, id DESC. In Postgres that puts NULLs first. The indexes on the news feed table were built DESC NULLS LAST. That mismatch sounds like trivia, and it changes the whole plan. The planner can no longer walk the index in order, so it gathers the entire join set, sorts it, and only then hands back the first page.
On one panel that meant roughly 45,000 buffer pages touched per call, where a buffer page is one small chunk of table data Postgres reads. Each story also has to pass a check that it's allowed to show. The planner guessed that check would match one row, so it never saw the cost coming.
I kept the evidence in the migration itself, as a comment at the top of the rewritten function. The code 57014 is the Postgres error for a cancelled statement, which is what a statement timeout produces. The "joined verification predicates" are those allowed-to-show checks.
-- prod saw ~266 statement timeouts (57014) per 24h. The prior body ordered by
-- published_at DESC, id DESC (NULLS FIRST) while the feed indexes are DESC NULLS LAST,
-- and the joined verification predicates misestimated to one row, so every call
-- touched ~45k buffers.
Three changes in the new body
- Walk the index newest-first, so the plan becomes "stop when the page is full" instead of "sort everything".
- Verify each candidate with a per-row
EXISTS (... OFFSET 0). TheOFFSET 0stops Postgres from folding that check into the joins, so it runs one candidate at a time and stops early instead of validating the whole candidate set. - For stories about other players at the same position, look only at a fixed number of the newest stories in the league, so the worst case has a known size.
The two-minute check
When a query is slow in a way that surprises me, I now compare the null ordering in its ORDER BY with the null ordering of the index it should use. It takes two minutes.
The same night I split player game-log reads in two to dodge a related timeout, and scoped single-prop lookups (a prop is a bet on one player's stat in one game) to that prop's own betting lines, the over/under numbers set for it. Both follow the same rule: stop paying for rows nobody sees.