Recently we had a case where we needed to limit the PostgreSQL user activities to only a single connection per user, and in this article I’m going to share the experience with you.
The connection limit is applied during the session connection. Raising this limit will never
affect any connected users. Lowering the limit doesn’t have any effect either unless they try
to disconnect and reconnect.
The same technique can be used to prevent connections entirely for any user.
We can restrict users to only one connection using the following command:
ALTER ROLE fred CONNECTION LIMIT 1; ALTER ROLE
This will then cause any additional connections to receive the error message:
FATAL: too many connections for role “fred”.
You can eliminate this restriction by setting the value to -1.
It’s possible to set the limit to 0 or any positive integer. You can set this to a number
other than max_connections, though it is up to you to make sense of that if you do.
Setting the value to 0 will completely restrict normal connections. Note that even if you
set the connection limit to zero for super users, they will still be able to connect.