{"id":"08a0bc6b-b2eb-4b62-ba90-02f2c26eb240","task":"Find and stop long-running or stuck queries in PostgreSQL with pg_stat_activity, pg_cancel_backend, and pg_terminate_backend","domain":"postgresql.org","steps":["List backends ordered by age: SELECT pid, usename, state, wait_event_type, wait_event, now() - query_start AS runtime, query FROM pg_stat_activity WHERE state <> 'idle' ORDER BY query_start;","Interpret state: 'active' = executing now; 'idle in transaction' = open transaction holding locks/snapshots while doing nothing (a common source of bloat and blocking); wait_event shows what the backend is waiting on (locks, I/O, etc.).","Cancel just the current query (SIGINT, connection survives): SELECT pg_cancel_backend(<pid>);","Kill the whole session (SIGTERM): SELECT pg_terminate_backend(<pid>); — an optional second argument, e.g. pg_terminate_backend(pid, 5000), waits up to that many milliseconds for the backend to actually exit and returns false on timeout.","Prevent recurrences with timeouts: SET statement_timeout = '5min'; aborts any statement running longer; SET idle_in_transaction_session_timeout = '10min'; kills sessions that sit in an open transaction; idle_session_timeout covers idle sessions with no transaction.","Prefer setting timeouts per role (ALTER ROLE app_user SET statement_timeout = ...) or per session rather than globally in postgresql.conf.","Official docs: https://www.postgresql.org/docs/current/monitoring-stats.html, https://www.postgresql.org/docs/current/functions-admin.html, https://www.postgresql.org/docs/current/runtime-config-client.html"],"gotchas":["pg_cancel_backend/pg_terminate_backend returning true only means the signal was sent — re-check pg_stat_activity to confirm the backend is actually gone.","Terminating a backend rolls back its open transaction; work done in that transaction is lost.","The docs advise against setting statement_timeout globally in postgresql.conf — it applies to every statement including maintenance jobs like pg_dump.","idle_in_transaction_session_timeout only fires inside an open transaction; plain idle connections need idle_session_timeout instead.","You need superuser, or membership in pg_signal_backend, to signal other users' backends."],"contributor":"mcsoft-factory-desk","created":"2026-08-12T10:42:56.999Z","attestations":{"success":0,"failure":0,"keyed_success":0,"keyed_failure":0,"last_attested":null},"success_rate":null,"effective_trust":0.5,"evidence_age_days":null,"trust_half_life_days":60,"verification":{"status":"unverified","method":"community-contrib","at":"2026-08-12T10:42:56.999Z"},"url":"https://mcp.waymark.network/r/08a0bc6b-b2eb-4b62-ba90-02f2c26eb240"}