I used to think that once I added the right index, the query would get fast and stay fast.
Then one day, log_impression, the RPC that logs every image impression on PixEarn, started throwing this error in production:
57014: canceling statement due to statement timeout
Every scroll, open, or search click calls this RPC. It checks whether the impression is a duplicate, inserts it, and updates a counter. Depending on the device, it handles batches of 5 to 35.
At the time, this RPC was getting around 5.5 million calls a month.
When I checked pg_stat_statements, the average was around 200 to 300ms. But some calls were taking more than 7 seconds.
Once a call crossed statement_timeout, Postgres cancelled it. The caller got a 500 response, and the impression didn't get recorded.
But analytics.impressions already had an index on ref_id and a composite index on (ref_id, created_at DESC).
My first thought was, I already have the index that matches this query. Why is this still happening?
What I thought was going on
The query filters by ref_id first, which is also the first column in the composite index.
I assumed Postgres would use ref_id to find the image's impressions, then use created_at to check whether the same viewer had seen it in the last 5 minutes.
That seemed to work while the table was small.
But the first issue I found was somewhere else.
A nightly rollup job was scanning impressions by date across all images. The composite index started with ref_id, so it couldn't efficiently serve that query. This is the leftmost prefix rule: the order of the columns matters when using a composite index.
So I added standalone created_at indexes for that job.
It helped the rollup, but the RPC was still timing out.
The RPC already filtered by ref_id first. I still needed to check what happened to created_at after that.
Where it actually broke
Inside log_impression, a SECURITY DEFINER function, I had this check to avoid duplicate impressions:
filtered_images AS (
SELECT vi.ref_id
FROM valid_images vi
WHERE NOT EXISTS (
SELECT 1
FROM analytics.impressions ie
WHERE ie.ref_id = vi.ref_id
AND ie.come_from = p_from
AND (ie.actor_id = _user_id OR ie.anon_id = p_anon_id)
AND now() < ie.created_at + interval '5 minutes'
)
)The idea was simple.
If the same viewer had already logged an impression for this image, from the same source, in the last 5 minutes, skip it. A page reload shouldn't turn one view into five.
The ref_id check was working properly. But this line was the problem:
now() < ie.created_at + interval '5 minutes'I was adding 5 minutes to created_at before comparing it with now().
Because of that expression, Postgres couldn't use created_at as the time boundary in the index scan.
So Postgres found the rows for that ref_id, then went through the image's history until it found a matching impression or reached the end.
Most of the time, there was no recent duplicate. So it checked the whole history before deciding to insert a new impression.
With a hundred rows, that wasn't a big problem.
But the table had grown to around 5.9 million rows. Popular images had a long history of impressions, and the RPC was handling around 5.5 million calls a month.
The index was there. But the way I wrote the condition didn't let Postgres use created_at to limit that work.
The rewrite
-- Before
now() < ie.created_at + interval '5 minutes'
-- After
ie.created_at > now() - interval '5 minutes'The condition still meant the same thing. I just moved the calculation to the other side.
now() gives a fixed value for the comparison. With created_at alone, Postgres could use the index to check only the rows within the last 5 minutes.
That was the part I had missed.
I had checked whether the index existed. But I hadn't checked whether the query let Postgres use it properly.
The indexes I added alongside it
CREATE INDEX IF NOT EXISTS idx_ie_actor_dedup
ON analytics.impressions (ref_id, come_from, actor_id, created_at)
WHERE actor_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_ie_anon_dedup
ON analytics.impressions (ref_id, come_from, anon_id, created_at)
WHERE anon_id IS NOT NULL;The duplicate check also uses come_from and the viewer's identity. For logged-in users, it uses actor_id. For anonymous users, it uses anon_id. Only one applies per call.
The old composite index only covered ref_id and created_at. Even after rewriting the condition, Postgres still needed to read the table rows to check the other fields.
These indexes cover all four columns needed for each check. They are partial indexes because a row only has one identity field set, never both.
I also added DISTINCT to the valid_images CTE after someone raised duplicate IDs as a possible bug during review.
But after checking the schema, I realised that image_id was already the primary key. Repeated IDs in the input array couldn't produce duplicate rows there.
So DISTINCT didn't fix anything. I left it in, but it wasn't part of what solved the timeout.
Why CONCURRENTLY, and why it's annoying
The table was still receiving live writes while I worked on the fix.
At around 5.5 million RPC calls a month, I couldn't ignore what would happen while building the indexes.
A plain CREATE INDEX would block writes for the whole build. On a small table, I might not notice it much. But on this table, it could cause another outage.
So I used CREATE INDEX CONCURRENTLY to keep writes going during the build.
It takes longer, and if the build fails partway, it can leave an invalid index behind. But I needed the table to keep accepting writes.
The retry loop that made it worse
While checking this, I also found a problem in the client.
Whenever flushImpressions failed, it put the entire batch back into the buffer. There was no limit:
} catch (err) {
impressionBufferRef.current = [...batch, ...impressionBufferRef.current];
}Once the RPC started timing out, the failed batch went back into the buffer. New impressions kept coming in, so the next flush became bigger.
That put even more load on the same RPC that was already struggling.
One timeout was making the next attempt worse.
So I added two limits:
const MAX_IMPRESSION_BATCH_SIZE = 40;
const MAX_IMPRESSION_RETRIES = 3;Each flush could send a maximum of 40 IDs. After 3 failures, the batch was dropped instead of being added back again.
The slow query was one problem. The retry loop was adding more work every time that query failed.
How I actually checked this was fixed
I didn't want to decide that everything was fixed after one EXPLAIN ANALYZE run.
log_impression does real inserts and an upsert. So when running it directly, I needed BEGIN; ... ROLLBACK; to avoid keeping those writes.
And even then, one run in an empty session wouldn't show what happens when many calls arrive together against millions of rows. It could show the query plan, but I also needed to check real traffic.
So after deploying the fix, I checked pg_stat_statements again. This was the same tool that had shown the 200 to 300ms average and spikes past 7 seconds.
It helped me check whether that pattern was still happening under real traffic. But the statistics alone couldn't explain why something got faster. I had already understood that part by reading the query.
The first 90 minutes of clean traffic were encouraging.
But I still wanted to watch a full day, including busy and quiet periods, before calling the issue closed.
What's still not fixed
The RPC also updates a per-image counter:
INSERT INTO analytics.metrics_summary (ref_id, impressions)
SELECT ref_id, 1 FROM inserted
ON CONFLICT (ref_id) DO UPDATE
SET impressions = analytics.metrics_summary.impressions + 1,
last_updated_at = now()This works under normal traffic. But when an image becomes popular or goes viral, many viewers try to update the same row at the same time.
One transaction holds the lock, and the others updating that ref_id have to wait.
That waiting time also counts towards statement_timeout. So a transaction can get cancelled while waiting for the lock, even if the query itself doesn't have much work to do.
I haven't shipped a fix for this yet. Rewriting the time condition doesn't solve the row lock problem.
My plan is to log the impression during the request, then let a periodic batch job update the counts. I already use that pattern for other rollups.
But as of writing this, it's still a plan.
Takeaways
Looking back, the query hadn't changed. The number of rows had.
The same query that seemed fine on a small table became a problem as the data grew.
I also learned that seeing an index in EXPLAIN isn't enough. Postgres can use one part of an index while still checking far more rows than I expected because another condition can't use it.
And the problem didn't stay in the database. The client kept retrying failed batches without a limit, which added more load every time something went wrong.
Now, when I check a slow query, I look at how the query uses the index, how much data it needs to check, and what the caller does when it fails.
