Re: Deleting idle connections

From: Sándor Daku <daku(dot)sandor(at)gmail(dot)com>
To: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Deleting idle connections
Date: 2025-02-25 09:02:56
Message-ID: CAKyoTgZuJe10da9uiG3_V5jZpD_JNw4U3bibn+AiU1=mdOgxOA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, 25 Feb 2025 at 00:12, Ron Johnson <ronljohnsonjr(at)gmail(dot)com> wrote:

> On Mon, Feb 24, 2025 at 5:50 PM Yongye Serkfem <yserkfem(at)gmail(dot)com> wrote:
>
>> Hi Everyone!
>> I am having a series of idle connections and unable to delete them with a
>> single command. Any help in realizing this would be greatly appreciated.
>>
>
> This will kill idle connections older than two hours:
> select pid, pg_terminate_backend(pid)
> from pg_stat_activity
> where state = 'idle'
> and (EXTRACT(epoch FROM now() - backend_start))/3600.0 > 2;
>
> Be warned that it might kill more than you want. Add more WHERE
> predicates as filter.
>
> --
> Death to <Redacted>, and butter sauce.
> Don't boil me, I'm still alive.
> <Redacted> lobster!
>

You could use the state_change timestamp to be sure that the idle
connection is in that state for long enough to be considered really idle.
You can catch and terminate otherwise actively working connections
momentarily in the idle state, if you are not careful enough.

Regards,
Sándor

In response to

Browse pgsql-general by date

  From Date Subject
Next Message sivapostgres@yahoo.com 2025-02-25 12:02:43 Re: Corruption of few tables
Previous Message Sakshi Behl 2025-02-25 06:51:46 PgSQL - SIEM Integration