Question: How do you configure the connection limit in PostgreSQL?


PostgreSQL allows configuration of the maximum number of concurrent connections to the database. This setting is crucial for preventing excessive use of system resources and ensuring stable performance.

Setting Connection Limits

The primary way to set the connection limit in PostgreSQL is through the max_connections setting in the postgresql.conf file. This parameter determines the total number of concurrent connections that the server can support.

# Open the PostgreSQL configuration file nano /etc/postgresql/12/main/postgresql.conf

Inside the configuration file, find the max_connections line and set your desired limit:

max_connections = 100

After making this change, you will need to restart the PostgreSQL server for the changes to take effect.

# Restart PostgreSQL service sudo systemctl restart postgresql

Connection Limits per Role

In addition to the global connection limit, PostgreSQL allows setting connection limits on a per-role basis using the CONNECTION LIMIT clause in the CREATE ROLE or ALTER ROLE commands.

For example, to create a new role with a specific connection limit:


Or to modify an existing role:


These settings can be particularly useful for managing resource usage in environments with multiple users or applications.

Monitoring Connections

To monitor current connections and see how close you are to reaching the connection limit, you can run a query on the pg_stat_activity system view:

SELECT count(*) AS active_connections FROM pg_stat_activity;

This query will return the number of active connections currently being used by PostgreSQL.

By understanding and configuring the connection limits appropriately, you ensure efficient use of resources and maintain the stability and performance of your PostgreSQL server.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book
Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.