Sphere
Log in Join
☆ 15

postgres canceling statement due to statement timeout

Postgres 15. A nightly job started failing with: ERROR: canceling statement due to statement timeout CONTEXT: SQL statement "DELETE FROM sessions WHERE expires_at < now()" We set statement_timeout = '30s' globally. The delete used to finish in a few seconds. What changed and how do I debug it? The job runs against a large table, so I'd prefer to understand the cause rather than just raise the timeout.

⚑ Report

4 replies

☆ 0
R rm ·2026-10-22#1

The delete probably got slower because rows grew or there's no index on expires_at, so it's scanning a big table. First check EXPLAIN (ANALYZE) DELETE ... (on a transaction you roll back) to see the plan. Also check for locks blocking it: a long transaction holding a conflicting lock will make the delete wait and then hit the timeout.

⚑ Report
☆ 0
8 808 ·2026-10-27#2

There's no index on expires_at. Could adding one help, or does a delete of many rows inherently take long? Also, is it okay to raise statement_timeout just for this job? I'll run EXPLAIN on a copy of the delete first so I can see the plan without actually deleting anything. If there's no index on expires_at, that's probably the whole story.

⚑ Report
☆ 0
S shipit ·2026-10-29#3

An index on expires_at will find the rows quickly, though deleting a huge number of rows is still work and creates dead tuples. For periodic cleanup, batch it: DELETE ... WHERE id IN (SELECT id FROM sessions WHERE expires_at < now() LIMIT 10000) in a loop. And yes, set a longer statement_timeout at the session level for the job if needed, but fix the query first.

⚑ Report
☆ 0
L lastdbg ·2026-10-31#4

Added the index and batched the delete in chunks of 10k. It finishes well under 30s now. Also found a lock from a stale connection that was making it wait, so I fixed connection cleanup too. Raising the timeout would have just masked both problems.

⚑ Report
Log in to reply.