PG中的statement_timeout、lock_timeout、idle_in_transaction_session_timeout、idle_session_timeout等常用的 timeout 参数
Tags: idle_session_timeoutidle_in_transaction_session_timeoutlock_timeoutstatement_timeouttimeout参数PostgreSQLPG
简介
最近在浏览 guc_table.c
时注意到 PostgreSQL 有很多与超时相关的参数可供用户设置,在这些参数中,介绍最常用的参数:
- statement_timeout: Sets the maximum allowed duration of any statement.
- idle_in_transaction_session_timeout: Sets the maximum allowed idle time between queries, when in a transaction.
- idle_session_timeout: Sets the maximum allowed idle time between queries, when not in a transaction.
statement_timeout
在PG 9.4中就提供了。
PostgreSQL 中长事务往往会带来一些问题,比如 table bloat(由于旧版本记录不能及时回收)、占用资源(锁、内存)等,因此有些实例会设置一个合理的 statement_timeout 来自动杀死运行时间过长的查询。
1 2 3 4 5 | postgres=# set session statement_timeout = '10s'; SET postgres=# select pg_sleep(1000); ERROR: canceling statement due to statement timeout postgres=# |
但这个参数对于 idle in transaction
的 session 不起作用,比如:
1 2 3 4 5 6 7 8 9 10 11 12 | postgres=# set application_name = 'pg-x'; SET postgres=# set session statement_timeout = '10s'; SET postgres=# create table t1(id int); CREATE TABLE postgres=# insert into t1 values(1),(2); INSERT 0 2 postgres=# begin; BEGIN postgres=*# update t1 SET id=2 where id=1; UPDATE 1 |
开启事务但一直不 commit,该 session 一直处于 idle in transaction
状态,在另一个客户端查询:
1 2 3 4 5 | postgres=# select pid, application_name, xact_start, query_start, state from pg_stat_activity where application_name='pg-x'; pid | application_name | xact_start | query_start | state --------+------------------+-------------------------------+-------------------------------+--------------------- 201736 | pg-x | 2023-10-14 16:09:10.389653+00 | 2023-10-14 16:10:17.354243+00 | idle in transaction (1 row) |
statement_timeout
(integer
)