How to fix Server closed the connection unexpectedly in PostgreSQL

PostgreSQLINTERMEDIATEMEDIUMUpdated Dec 26, 2025ยท 340 views

This error occurs when PostgreSQL terminates a connection abnormally, typically due to server crashes, network issues, idle timeouts, or firewall interference. Fix it by checking server logs, adjusting TCP keepalive settings, and configuring proper timeout values.

Quick fix

Fixes Server closed the connection unexpectedly

# Default log location (may vary by installation)
tail -100 /var/log/postgresql/postgresql.log

# Or check the log_directory setting in postgresql.conf
sudo -u postgres psql -c "SHOW log_directory;"
  1. Check PostgreSQL server logs for crash reports
  2. Enable TCP keepalive to prevent idle connection termination
  3. Review and adjust timeout settings for your workload
  4. Implement connection pooling with PgBouncer
postgresql โ€” error
# Default log location (may vary by installation)
tail -100 /var/log/postgresql/postgresql.log
# Or check the log_directory setting in postgresql.conf
sudo -u postgres psql -c "SHOW log_directory;"
Server closed the connection unexpectedly

What this error means

When PostgreSQL displays this error, it means the server terminated the database connection before or while processing your request. This typically happens because the server process crashed, was terminated by the OS, or the network layer forcibly closed the connection. The error message itself is generic and the root cause requires investigation of server logs, network conditions, and connection configuration.

Typical symptoms

  • Database connections drop after a period of inactivity (5-30 minutes)
  • Queries fail with "server closed the connection unexpectedly" message
  • Connection pool exhaustion when connections become stale
  • Application unable to execute queries on previously opened connections
  • Intermittent connection failures that resolve temporarily after reconnection

Common causes

  1. PostgreSQL server crashed or was terminated abnormally (signal 11/SIGSEGV)
  2. Network firewall or proxy closes idle connections after timeout
  3. Ill-configured network component terminates connections with no activity
  4. Server running out of memory, triggering OOM killer to terminate backend processes
  5. Stale connection objects from connection pools with broken underlying sockets
  6. Client timeout settings (statement_timeout, idle_in_transaction_session_timeout) closing connections
  7. Server not listening on external interfaces or connection parameters are incorrect

How to fix "Server closed the connection unexpectedly"

1Check PostgreSQL server logs for crash reports

Navigate to your PostgreSQL log directory and examine recent log entries for CRITICAL or FATAL errors that coincide with connection issues:

bash
# Default log location (may vary by installation)
tail -100 /var/log/postgresql/postgresql.log

# Or check the log_directory setting in postgresql.conf
sudo -u postgres psql -c "SHOW log_directory;"

Look for segmentation faults (signal 11), out of memory errors, or other backend process terminations that explain the connection loss.

2Enable TCP keepalive to prevent idle connection termination

Configure TCP keepalive settings in postgresql.conf to detect stale connections before network components close them:

bash
# Edit postgresql.conf
sudo nano /etc/postgresql/14/main/postgresql.conf

# Add or modify these settings
tcp_keepalives_idle = 60        # Send keepalive after 60 seconds idle
tcp_keepalives_interval = 10    # Send keepalive every 10 seconds
tcp_keepalives_count = 5        # Give up after 5 failed keepalives

Then reload the configuration:

bash
sudo systemctl reload postgresql
# or
sudo -u postgres psql -c "SELECT pg_reload_conf();"
3Review and adjust timeout settings for your workload

Check current timeout settings and adjust them to values suitable for your application:

sql
-- View current timeout settings
SHOW statement_timeout;
SHOW idle_in_transaction_session_timeout;
SHOW tcp_keepalives_idle;

-- Set via postgresql.conf or per-session
SET statement_timeout = '5min';           -- Query max duration
SET idle_in_transaction_session_timeout = '10min';  -- Max time in idle transaction

-- Or set globally in postgresql.conf
statement_timeout = 300000        # milliseconds
idle_in_transaction_session_timeout = 600000

Match these values to your application's expected query duration and session behavior.

4Implement connection pooling with PgBouncer

Connection pooling prevents connection exhaustion and provides automatic recovery from stale connections:

bash
# Install PgBouncer
sudo apt-get install pgbouncer

# Edit /etc/pgbouncer/pgbouncer.ini
[databases]
mydb = host=localhost port=5432 dbname=mydb

[pgbouncer]
pool_mode = transaction
max_client_conn = 100
default_pool_size = 25
server_idle_timeout = 600

# Start the service
sudo systemctl start pgbouncer

Configure your application to connect to PgBouncer (port 6432) instead of PostgreSQL directly.

5Verify server is listening on required interfaces

Ensure PostgreSQL listens on the correct network interfaces in postgresql.conf:

bash
# Check current configuration
sudo -u postgres psql -c "SHOW listen_addresses;"

# If connecting remotely, edit postgresql.conf
sudo nano /etc/postgresql/14/main/postgresql.conf

# Set to listen on all interfaces (or specific IP)
listen_addresses = '*'    # All interfaces
# listen_addresses = '127.0.0.1,192.168.1.100'  # Specific IPs

# Then reload
sudo systemctl reload postgresql

Also verify pg_hba.conf allows connections from your client IP.

6Implement retry logic in your application

Add exponential backoff retry logic to handle transient connection failures:

javascript
// Node.js example with node-postgres
const { Pool } = require('pg');

const pool = new Pool({
  host: 'localhost',
  port: 5432,
  database: 'mydb',
});

async function queryWithRetry(sql, params, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const client = await pool.connect();
      try {
        return await client.query(sql, params);
      } finally {
        client.release();
      }
    } catch (err) {
      if (attempt === maxRetries - 1) throw err;
      const delay = Math.pow(2, attempt) * 100; // exponential backoff
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}
7Investigate firewall and network configuration

If the issue persists after checking logs and configuration, investigate network-level problems:

bash
# Check if firewall is blocking connections
sudo ufw status
sudo firewall-cmd --list-all

# Ensure PostgreSQL port (5432) is allowed
sudo ufw allow 5432
# or
sudo firewall-cmd --add-port=5432/tcp --permanent

# Capture network traffic to diagnose connection issues
sudo tcpdump -i any -n 'port 5432' -w postgresql.pcap

# Analyze with Wireshark or similar tool
wireshark postgresql.pcap

Look for patterns of connection resets or unexpected closure from network devices.

Advanced notes

Server Crashes and Version Bugs: Some PostgreSQL versions have known bugs causing 100% reproducible server crashes with specific workloads. If you encounter consistent connection drops with a specific PostgreSQL version, check the official bug tracker and consider upgrading to a patched version.

Out of Memory Killer: On Linux systems, the OOM killer may terminate PostgreSQL backend processes when system memory is exhausted. Monitor memory usage with free -h and top, and consider increasing available memory or configuring swap space.

Idle Connection Handling: Different hosting providers handle idle connections differently. Render, Railway, and Azure Database for PostgreSQL may close idle connections after 15-30 minutes. PgBouncer or application-level keepalive is essential when using managed cloud databases.

Connection Pool Stale Connections: When using connection pools (e.g., Prisma Client, HikariCP), connections can become stale if the server closes them without the pool knowing. Set pool validation/test queries to detect and refresh stale connections automatically.

Frequently asked questions

What does "Server closed the connection unexpectedly" mean?
When PostgreSQL displays this error, it means the server terminated the database connection before or while processing your request. This typically happens because the server process crashed, was terminated by the OS, or the network layer forcibly closed the connection. The error message itself is generic and the root cause requires investigation of server logs, network conditions, and connection configuration.
How do I fix "Server closed the connection unexpectedly"?
This error occurs when PostgreSQL terminates a connection abnormally, typically due to server crashes, network issues, idle timeouts, or firewall interference. Fix it by checking server logs, adjusting TCP keepalive settings, and configuring proper timeout values.
What causes "Server closed the connection unexpectedly"?
PostgreSQL server crashed or was terminated abnormally (signal 11/SIGSEGV) Network firewall or proxy closes idle connections after timeout Ill-configured network component terminates connections with no activity
Is the "Server closed the connection unexpectedly" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading