Delete idle connections
WITH inactive_connections AS (
rank() over (partition by client_addr order by backend_start ASC) as rank
-- Exclude the thread owned connection (ie no auto-kill)
pid <> pg_backend_pid( )
-- Exclude known applications connections
application_name !~ '(?:psql)|(?:pgAdmin.+)'
-- Include connections to the same database the thread is connected to
datname = current_database()
-- Include connections using the same thread username connection
usename = current_user
-- Include inactive connections only
state in ('idle', 'idle in transaction', 'idle in transaction (aborted)', 'disabled')
-- Include old connections (found with the state_change field)
current_timestamp - state_change > interval '5 minutes'
rank > 1 -- Leave one connection for each application connected to the database