按角色和数据库设置 statement_timeout / lock_timeout
PostgreSQL会话命令
-- Application role: short queries, short lock waits, a limit on forgotten transactions
ALTER ROLE web_app SET statement_timeout = '30s';
ALTER ROLE web_app SET lock_timeout = '5s';
ALTER ROLE web_app SET idle_in_transaction_session_timeout = '10min';
-- Let the reporting role run longer, only in this database
ALTER ROLE report_app IN DATABASE mydb SET statement_timeout = '15min';
-- Show configured role/database settings
SELECT coalesce(r.rolname, '(all)') AS role,
coalesce(d.datname, '(all)') AS database,
s.setconfig
FROM pg_db_role_setting s
LEFT JOIN pg_roles r ON r.oid = s.setrole
LEFT JOIN pg_database d ON d.oid = s.setdatabase
ORDER BY 1, 2;
-- Revert
ALTER ROLE web_app RESET lock_timeout;作用
在角色(以及可选的数据库)级别持久设置超时参数,使每类负载在不改动全局设置的情况下以自己的限制运行。
适用场景
用于防止失控查询耗尽资源、DDL/锁队列使应用卡死,以及被遗忘的事务造成膨胀。
注意
设置只对新会话生效;请回收连接池中的现有连接。用户可以在其会话中用 SET 覆盖该值;这不是安全边界。不要在 postgresql.conf 中全局设置 statement_timeout:pg_dump、VACUUM 和 CREATE INDEX 等维护作业也会被取消。优先级:角色+数据库 > 角色 > 数据库 > postgresql.conf。