pg.ddx.io  pgsql-admin@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: hubert depesz lubaczewski <depesz@depesz.com>
To: Ron <ronljohnsonjr@gmail.com>
Cc: pgsql-admin@lists.postgresql.org
Subject: Re: PostgreSQL(v9.6.5) not releasing old/inactive IDLE connections
Date: Wed, 8 Dec 2021 13:23:16 +0100
Message-ID: <20211208122316.GB28627@depesz.com> (raw)
In-Reply-To: <7ab7add9-9c1b-3842-e4eb-f78107964db3@gmail.com>
References: <OS3PR01MB581659FF3F8020F174751B4BA76F9@OS3PR01MB5816.jpnprd01.prod.outlook.com>
	<7ab7add9-9c1b-3842-e4eb-f78107964db3@gmail.com>

On Wed, Dec 08, 2021 at 01:23:32AM -0600, Ron wrote:
> I set up a cron job that regularly kills old idle connections.
> SELECT pg_terminate_backend(pid)
> FROM pg_stat_activity
> WHERE datname = 'databasename'
>   AND pid <> pg_backend_pid()
>   AND state = 'idle'
>   and extract(epoch from (current_timestamp - query_start)) > 20*60 -- 20
> minutes
> ;

Two notes:
1. it's better to use state_change and not query_start. For example, if
   I'd start 2 hours query, 3 hours ago, then "now" it would still have
   query_start at (now() - 3 hours), despite the fact that it would be
   idle only for 1 hour.
2. doing calculations in epoch is bad idea. it can become your muscle
   memory, and it will cause problems with indexing. instead:
       and state_change < current_timestamp - '20 minutes'::interval

depesz





view thread (5+ messages)

Message-ID: <20211208122316.GB28627@depesz.com>
Permalink:  ../20211208122316.GB28627@depesz.com/
Also on:    postgresql.org/message-id/20211208122316.GB28627@depesz.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-admin@postgresql.org
  Cc: depesz@depesz.com, ronljohnsonjr@gmail.com, pgsql-admin@lists.postgresql.org
  Subject: Re: PostgreSQL(v9.6.5) not releasing old/inactive IDLE connections
  In-Reply-To: <20211208122316.GB28627@depesz.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox