Back to Tech Q&A
Tech Q&A

PostgreSQL Connection Issues

Dec 12, 2024
PostgreSQLDatabaseDevOpsConnection Pooling
Question

Why am I getting 'connection refused' errors in production?

Answer

This usually means your connection pool is exhausted. Check your max_connections setting and ensure you're properly releasing connections after use. Also verify that your database server is actually running and accepting connections on the expected port.

Question

How do I increase the connection pool limit?

Answer

In your pg_hba.conf, increase max_connections. Also consider using PgBouncer for connection pooling in high-traffic scenarios. PgBouncer sits between your app and PostgreSQL, managing connections more efficiently than your application can.

Question

What's a good max_connections value?

Answer

It depends on your RAM. A rough formula: (RAM in MB) / 25. So for 4GB RAM, around 160 connections is a safe starting point. But remember, each connection uses memory, so more isn't always better.

Question

How do I know if my connections are being leaked?

Answer

Run `SELECT count(*) FROM pg_stat_activity;` to see active connections. If this number keeps growing without going down, you have a leak. Check that you're calling pool.release() or closing connections in finally blocks.

Question

Should I use connection pooling in serverless?

Answer

Absolutely. Serverless functions can spawn many instances, each trying to open connections. Use a managed pool like PgBouncer, or use serverless-friendly databases like Neon that handle this automatically.