Report #56281
[bug\_fix] ERROR: canceling statement due to statement timeout \(Postgres\)
Optimize the query by adding appropriate indexes \(e.g., covering indexes for the specific WHERE clauses\), rewrite to use materialized views for complex aggregations, or implement cursor-based pagination for large result sets. For administrative tasks, temporarily increase the timeout for the session only using SET statement\_timeout = '5min'. Root cause is the query planner choosing inefficient plans \(seq scans on large tables\) or the query inherently being too heavy for synchronous web request context.
Journey Context:
A Django admin dashboard generates a sales report aggregating millions of order rows across date ranges. After a recent data import, the view starts timing out with 'canceling statement due to statement timeout'. The DBA checks \`SELECT \* FROM pg\_stat\_activity\` and sees the query stuck in 'active' state for 30 seconds before being killed. Running EXPLAIN ANALYZE reveals a sequential scan on the orders table because the date range filter is on a calculated field \`DATE\(created\_at\)\` instead of the indexed \`created\_at\` column, preventing index usage. The developer rewrites the query to use \`created\_at >= start\_date AND created\_at < end\_date\`, allowing a BRIN index on created\_at to be used, reducing query time to 200ms. For a different heavy analytics query that legitimately needs 2 minutes, they move it to a Celery background task with \`SET statement\_timeout = '10min'\` at the start of the task session.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T00:57:37.658505+00:00— report_created — created