
This is how we took a single query from using 34% of our DB cpu time to just 0.3%, all in the gaps between doing what we were supposed to be doing.
I joined incident.io's Reliability Engineering team 5 weeks ago (at the time of writing). One of the things that came up as a non-P0 reliability concern was that the CPU on the main DB's replica was a little higher than we were entirely comfortable with.
We are a Postgres shop, and I’m personally far from a Postgres expert, but have dabbled with trying to improve DB performance before. My expectations were relatively low, aware that even if I could spot something I wouldn't necessarily have the context to be able to fix it.
However, in the modern world where compile time has been replaced with agent thinking time, there's always the ability to find a 10-minute gap to take a look at something, and thus I had acquired a side quest: to cut DB CPU time, and battle a great foe (Postgres' query planner).
Finding the Culprit(s)
I quickly found several existing dashboards, which covered many of the most obvious performance considerations: the rate of sequential scans, traffic within the expected range, queries with high average execution times.
There were a few early candidates for what could be contributing and there was a small period of time where I had convinced myself that it was the processing of the WAL struggling to keep up. However, I then read that Postgres WAL processing is single threaded and therefore has a pretty hard ceiling on how much of a 64-core machine it can use.
Query insights revealed a nice and obvious smoking gun: one query was taking up 5x more CPU time than any other. However, our query insights are sampled, so this could be a sampling artifact rather than true signal.
The Target
I took a proper look at the query and it was as follows:
SELECT e.*
FROM unnest(?::text[], ?::text[], ?::text[], ?::text[])
AS groups(organisation_id, schedule_id, rotation_id, layer_id)
CROSS JOIN LATERAL (
SELECT se.* FROM schedule_entries se
WHERE se.organisation_id = groups.organisation_id
AND se.schedule_id = groups.schedule_id
AND se.rotation_id = groups.rotation_id
AND se.layer_id = groups.layer_id
AND se.start_at < ?
ORDER BY se.start_at DESC
LIMIT 1
) e
WHERE e.end_at > ?This query is touching the following entity types:
- Organisations: the very top level, represents one of our customers/tenants.
- Schedules: which represent an on call rota, e.g. Engineering on call
- Rotations: a part of the schedule with its own handover pattern and working hours, e.g. "weekly, Monday 09:00".
- Layers: a place for redundancy within a rotation, e.g. always have 2 engineers on call.
- Schedule entries: the user responsible for the given layer at given times.
This query ultimately boils down to "who's on call for this layer of a rotation right now". The CROSS JOIN LATERAL allows us to answer this question multiple times for different rotation layers at once.
After finding a trace, I found an example of a bad input. In this instance the query had taken 229ms, an order of magnitude higher than the average for this query (26ms).
The input itself didn't raise any alarms. It was for a larger organisation (as could be expected), but it was not an abnormally large array (38 groups).
We export pg_stat_statements regularly (a fact I didn't know at this point in the original investigation) so we can pull some pretty gnarly stats to see what the impact of this query is. Over a 3.5-day window, we can see:
| Node | Calls | Time | Share of node | ms/call | Buffers/call | Rows/call |
|---|---|---|---|---|---|---|
| Our query | 22.97M | 280.7h | 33.8% | 44.0 | 8,359 | 6.5 |
| Our most called query | 169.0M | 1.5h | 0.2% | 0.03 | 4 | 1.0 |
Comparing this to our most called query, which is very well optimised, we can see the difference is quite large. ~175x more CPU time being used, the average time per call is ~1500x higher. We can see the impact of reading the entire history for a layer in the number of buffers hit. Rather than just reading the buffers which contain the information we need we have to read 1000s to find the relevant record.
There is also a graph which shows us DB work for different flows at different times in (one of my favourite units) seconds/second. This shows the impact of this one query visually. The orange section is our query and the area of that section dwarfs any other.

Running an Explain on the query for the known bad input highlights the cause:
Nested Loop
-> Function Scan on groups
-> Subquery Scan on e Filter: end_at > now()
-> Limit
-> Sort (start_at DESC)
-> Index Scan using schedule_entries_no_overlapping_ranges_rotation_layer
Index Cond: schedule_id, rotation_id, layer_id
Filter: organisation_id, start_at < now()Although it was using an index, and avoiding triggering an alert on sequential scans, the index being used did not include organisation_id and more critically it was missing start_at. So to resolve the question “who's on call for this layer of a rotation right now” we read the entire history of a layer before finding the newest record and returning only that. This inefficient query structure is the direct cause of the large number of buffers being hit, and because a large amount of data to be sorted through, the high latency of the query.
Unbeknownst to me this had been the great shame/bane of our Infra Tech Lead, Ben, for some time.
The Fix is Easy (except it won't work)
The obvious fix is to add an index on the 5 columns. The table is not super wide (only 10 columns), so the index would be a significant fraction of the table's size. But the table is not even in our top 20 biggest, so this is totally acceptable for the potential performance gains.
CREATE INDEX CONCURRENTLY idx_schedule_entries_org_schedule_rotation_layer_start_at
ON schedule_entries (organisation_id, schedule_id, rotation_id, layer_id, start_at);Which importantly contains both the start_at, as well as the organisation_id.
Now back to the start: as a newbie, I wanted to collect really solid evidence that this would in fact solve the problem. Fortunately, in this grand agentic era, quick experiments are easier than ever, so I did the following:
- Replicate my local test DB onto a new server.
- Get Claude to write a script which will populate the DB with dummy data.
- Run the query without the index, and achieve the same query plan.
- Add the index, see the new query plan.
Doing that we saw a roughly 100x improvement on both query time and the number of buffers hit.
After I consulted an Engineering Manager who worked in this space, Edd, to ensure I wasn't about to run into rakes hidden in the grass, we went ahead and merged.
The Triumphant Celebration for a Job Well Done
The first trace that hit that query had a latency of just drum-roll 16ms. With a previous average of 26ms this was hardly the 100x improvement I thought it might be. A query plan showed what I feared: the original index was still being used.
Nested Loop
-> Function Scan on groups
-> Subquery Scan on e Filter: end_at > now()
-> Limit
-> Sort (start_at DESC)
-> Index Scan using schedule_entries_no_overlapping_ranges_rotation_layer
Index Cond: schedule_id, rotation_id, layer_id
Filter: organisation_id, start_at < now()The Real Fix
In order to understand the real fix we need to understand how a Postgres query works. For a more detailed description, see The Path of a Query in the Postgres docs.
Postgres is Smart
A query is split into 2 major phases: Planning and Execution.
In the Planning phase, the query is analysed and Postgres tries to determine the best way to execute the query. This could involve the ordering of some complicated joins, selecting whether to use an index, and if so which one. The full plan is not run every time. Postgres caches the plans and reuses them to save these calculations.*
Now, Postgres is smart, it doesn't just look at the indexes available but it also looks at some stats on the table(s) the query is to be run on. For instance, the planner probably won't use an index for a query on a table with 1 row. It can use constraints on foreign keys to estimate the number of rows which would be returned from certain sections of queries to inform choices.
These stats often help find clever optimisations on how to run a query, and are the main driving force for index selection when running a query.
Postgres is Dumb… Sometimes
However, Postgres has to make some assumptions, and those can trip it up.
In our instance Postgres assumes layers, rotations, organisations, and schedules are independent. When calculating the Plan, it makes the assumption that only 1 row will be returned when selecting on (what it believes are) 4 independent columns. If that were true the existing index would (presumably) perform marginally better, so it is selected.
Postgres never learns, it keeps performing the query this way without ever revisiting the assumption that these columns are independent. You can update the statistics Postgres uses when planning these queries as an alternative to what was done below. However, by changing the shape of the query you can force Postgres into making better choices.
How to trick Postgres
In order to fix this we can tweak the query resulting in the following diff:
SELECT e.*
FROM unnest(?::text[], ?::text[], ?::text[], ?::text[])
AS groups(organisation_id, schedule_id, rotation_id, layer_id)
CROSS JOIN LATERAL (
SELECT se.* FROM schedule_entries se
- WHERE se.organisation_id = groups.organisation_id
- AND se.schedule_id = groups.schedule_id
- AND se.rotation_id = groups.rotation_id
- AND se.layer_id = groups.layer_id
- AND se.start_at < ?
- ORDER BY se.start_at DESC
+ WHERE (se.organisation_id, se.schedule_id, se.rotation_id, se.layer_id, se.start_at)
+ < (groups.organisation_id, groups.schedule_id, groups.rotation_id, groups.layer_id, ?)
+ ORDER BY se.organisation_id DESC, se.schedule_id DESC, se.rotation_id DESC, se.layer_id DESC, se.start_at DESC
LIMIT 1
) e
-WHERE e.end_at > ?
+WHERE e.organisation_id = groups.organisation_id
+ AND e.schedule_id = groups.schedule_id
+ AND e.rotation_id = groups.rotation_id
+ AND e.layer_id = groups.layer_id
+ AND e.end_at > ?
This change enforces a whole row lookup, rather than treating each field as separate we treat it as a whole entity, likewise, we compare all the values in our row at the end rather than just the end_at. This does not change the result of the query at all, but Postgres treats it differently.
The original index definition is:
ALTER TABLE ONLY public.schedule_entries
ADD CONSTRAINT schedule_entries_no_overlapping_ranges_rotation_layer
EXCLUDE USING gist (
schedule_id WITH =,
rotation_id WITH =,
layer_id WITH =,
tstzrange(start_at, end_at) WITH &&
)
WHERE ((rotation_id IS NOT NULL) AND (layer_id IS NOT NULL));It was a constraint added to avoid overlapping schedule times, rather than some query optimisation. Interestingly it is a GiST (Generalized Search Tree)-based index, ultimately sorted by the range of times between the start and end of a schedule. A GiST index groups elements into a tree where they are grouped into ranges of values, but the individual nodes are not stored in any order.
There is no defined order between those nodes, and due to overlaps (like 17-95 and 91-130 above) the tree may need multiple traversals to find all records with a given value.
This differs from a btree index, which sorts all the records from the top level field to the bottom level field. In our scenario, if the ids were between 0 and 100, every record with schedule_id 0 is before every record with schedule_id 1.
As a reminder the new index was:
CREATE INDEX CONCURRENTLY idx_schedule_entries_org_schedule_rotation_layer_start_at
ON schedule_entries (organisation_id, schedule_id, rotation_id, layer_id, start_at);GiST does not support row-based comparisons. Postgres can only use a row comparison as an index condition on a btree index, because the comparison needs the data to be completely sorted.
So, to recap: we found a suboptimal query and provided it with a new index to greatly improve the performance. However, we then found that the query planner did not want to use this index. So by using the properties of the relevant indexes, we changed the query to force the query planner to use the new one. After all that you can see confirmation below that we are now successfully using the new index 🥳 🎊 🥳.
Nested Loop (cost=0.70..2.56 rows=1)
-> Function Scan on groups
-> Subquery Scan on e
Filter: (groups.organisation_id = e.organisation_id) AND (groups.schedule_id = e.schedule_id)
AND (groups.rotation_id = e.rotation_id) AND (groups.layer_id = e.layer_id)
AND (e.end_at > now())
-> Limit
-> Index Scan Backward using idx_schedule_entries_org_schedule_rotation_layer_start_at
Index Cond: (ROW(organisation_id, schedule_id, rotation_id, layer_id, start_at)
< ROW(groups.organisation_id, groups.schedule_id, groups.rotation_id, groups.layer_id, now()))The Results and What's Next
But how much impact could it possibly have? 5x performance, 10x, the 100x postulated earlier?!
| Calls | Time | Share of node | ms/call | Buffers/call | Rows/call | |
|---|---|---|---|---|---|---|
| Before | 22.97M | 280.7h | 33.8% | 44.0 | 8,359 | 6.5 |
| After | 22.64M | 1.6h | 0.3% | 0.26 | 71 | 6.6 |
Looking over 3.5-day windows offset by a week before and after the change over a very similar number of queries we see:
- 175x less overall query time, from a 175x reduction of average query time
- 100x smaller share of the db’s cpu time
- 115x fewer buffers hit
The graph showing DB work for different flows at different times in seconds/second also shows the sharp decline.

This is just one improvement on one query. Through this, I have picked up several other lines of investigation, and there are likely other similar wins to be had.
This process has also been an excellent bit of exploratory work. It has taught me several things about Postgres (cough GiST indexes cough), as well as several things about our architecture and internal tooling.
So, was this side quest worth it?
Yes, 100%. Not just for the impact of the change made, but also for the learning opportunity it presented for me.
This sort of problem solving, working through a real example very iteratively with a human-in-the-loop model, uncovers small individual gaps in knowledge in a structure where those gaps can be closed very quickly. I have become a better engineer both through this work and through writing this blog post (you should also be writing more blog posts).
incident.io encourages this sort of curiosity, letting developers work with a high degree of autonomy and a large dollop of trust. I've found myself being given more scope than ever to do this (psst: if that's the way you would like to be working, we are hiring).
Working through these low-stakes problems, which can be done in the interstices of the main work, can't really fail. In the worst case, you produce no change, but you've become a better engineer working on something fun. But if you find a query that can free 10% of the CPU on a hot node, you may just make the Tech Lead of your Infra team a very happy man.
For Ben.
*There's some subtlety which means this statement isn't entirely correct: we also rely on our DB driver using prepared statements.

See related articles

We gave cloud agents a phone to QA
Our cloud agents now test mobile pull requests on cloud simulators and leave screenshots and a recording behind. The agent collects the evidence and a person decides whether the change is right.


How savepoints quietly throttled our Postgres queue
We 3.5x'd our peak capacity in one of the most performance critical systems we have; here's how we did it, featuring a journey through some Postgres internals.


Building Investigations: what it takes to build an AI SRE
We spent the last two years building Investigations, our AI SRE. In this post, go behind the scenes of the work done and why build vs. buy is one of the most important decisions engineering teams are making right now.

So good, you’ll break things on purpose
Ready for modern incident management? Book a call with one of our experts today.

We’d love to talk to you about
- All-in-one incident management
- Our unmatched speed of deployment
- Why we’re loved by users and easily adopted
- How we work for the whole organization



