Bertie White found that one query accounted for roughly a third of the work on incident.io’s Postgres replica. It answered a simple question: who’s on call right now? The query already used an index, but it still read and sorted a layer’s history to find the latest entry.
- The obvious fix worked in testing. A new B-tree index put the schedule identifiers and start time in order. On synthetic data, query time and the number of pages touched both fell by roughly 100×.
- Production kept choosing the old index. White traces that choice to the planner treating related schedule identifiers as independent. It expected one row, making the old index look cheap.
- The rewrite matched the index order. White compared the identifiers and start time as a single tuple. Postgres could scan the B-tree backward and stop at the first candidate. An outer check still verified that the entry belonged to the right group and hadn’t ended.
Across two comparable 3.5-day windows, average query time fell from 44 ms to 0.26 ms. The query’s share of measured database time on the replica went from 33.8% to 0.3%.
Check the production query plan after adding an index. A test can show how fast the new plan runs; production tells you whether the planner will pick it.