How to fix server closed the connection unexpectedly in PostgreSQL

PostgreSQLINTERMEDIATEHIGHUpdated Dec 25, 2025ยท 418 views

PostgreSQL terminates connections unexpectedly due to server crashes, network timeouts, or configuration issues. Fix by checking server logs, enabling TCP keepalives, and verifying network stability.

Quick fix

Fixes server closed the connection unexpectedly

# Find your PostgreSQL log (varies by installation)
tail -f /var/log/postgresql/postgresql.log

# Or for systemd installations
journalctl -u postgresql -n 50 -f

# Or check the log_directory in your postgresql.conf
cat /path/to/postgresql/log/postgresql.log
  1. Check PostgreSQL server logs for crash reports
  2. Verify the server is running and listening
  3. Enable TCP keepalives to prevent network timeout
  4. Check and adjust timeout settings
postgresql โ€” error
# Find your PostgreSQL log (varies by installation)
tail -f /var/log/postgresql/postgresql.log
# Or for systemd installations
journalctl -u postgresql -n 50 -f
# Or check the log_directory in your postgresql.conf
cat /path/to/postgresql/log/postgresql.log
server closed the connection unexpectedly

What this error means

This error occurs when a PostgreSQL client's connection to the server drops without the client explicitly closing it. This means the server abruptly terminated the connection, leaving the client unable to send or receive data. The error can happen for several reasons: the server process crashed or was killed, network infrastructure (firewalls, load balancers) closed an idle connection, the client sent incompatible protocol data, or the server configuration forced the disconnection due to timeout settings. When this happens, your application loses its database connection mid-operation, which can corrupt transactions if you were in the middle of executing a query.

Typical symptoms

  • Queries fail with 'server closed the connection unexpectedly' message
  • Connection drops after the application has been idle for a few minutes
  • Database operations fail randomly without clear pattern
  • Errors appear in logs alongside timestamps when the connection died
  • Connection pools report sudden disconnections

Common causes

  1. Server process crashed or was forcibly terminated due to a bug, out-of-memory condition, or system issue
  2. Network component (firewall, load balancer, router) closed idle connections after a timeout period
  3. Incorrect or too-strict timeout settings on the server (statement_timeout, idle_in_transaction_session_timeout)
  4. Client sent malformed protocol data that the server couldn't parse
  5. Server was restarted or underwent maintenance without gracefully closing client connections
  6. Resource exhaustion (connections, memory) forcing the server to terminate connections

How to fix "server closed the connection unexpectedly"

1Check PostgreSQL server logs for crash reports

PostgreSQL logs will tell you if the server crashed. This is the first diagnostic step.

Look for FATAL, PANIC, or CRITICAL messages in your PostgreSQL log file:

bash
# Find your PostgreSQL log (varies by installation)
tail -f /var/log/postgresql/postgresql.log

# Or for systemd installations
journalctl -u postgresql -n 50 -f

# Or check the log_directory in your postgresql.conf
cat /path/to/postgresql/log/postgresql.log

Look for messages like:
- "server process was terminated abnormally"
- "Segmentation fault"
- "Out of memory"

If you find a crash, this is the root cause. You may need to file a bug report with PostgreSQL if this is reproducible, or upgrade to a newer version that has the fix.

2Verify the server is running and listening

Ensure PostgreSQL is actually running and accepting connections.

bash
# Check if PostgreSQL process is running
ps aux | grep postgres

# Try to connect directly
psql -U postgres -h localhost

# Or check if PostgreSQL is listening on the expected port
netstat -an | grep 5432
# or
ss -tuln | grep 5432

If the server crashed, restart it:

bash
# On Linux with systemd
sudo systemctl restart postgresql

# Or with manual startup
pg_ctl -D /path/to/data/directory start
3Enable TCP keepalives to prevent network timeout

Many network components (firewalls, NAT, load balancers) close idle TCP connections after 5-15 minutes. Enable keepalives to prevent this.

In your .env or connection string, add keepalive parameters:

bash
# In environment variable
DATABASE_URL="postgresql://user:password@host:5432/db?tcpKeepAlivesIdle=60&tcpKeepAlivesInterval=10&tcpKeepAlivesCount=5"

Or in postgresql.conf on the server side:

bash
# /etc/postgresql/15/main/postgresql.conf
tcp_keepalives_idle = 60        # seconds before first keepalive probe
tcp_keepalives_interval = 10    # seconds between probes
tcp_keepalives_count = 5        # number of probes before giving up

After editing postgresql.conf, reload the server:

bash
sudo systemctl reload postgresql
4Check and adjust timeout settings

Overly aggressive timeout settings can close connections prematurely. Review these settings:

sql
-- Check current settings
SHOW statement_timeout;
SHOW idle_in_transaction_session_timeout;
SHOW tcp_keepalives_idle;

-- Increase if too low (values in milliseconds, 0 = disabled)
SET statement_timeout = 300000;      -- 5 minutes instead of default
SET idle_in_transaction_session_timeout = 0; -- Disable if causing issues

Be careful with idle_in_transaction_session_timeout - if enabled and too short, it will terminate connections that are open but not actively executing queries. This is useful for cleanup but can break applications that keep transactions open between requests.

5Verify network connectivity and firewall rules

Network issues between your client and server can cause unexpected disconnections.

bash
# Test basic connectivity
ping -c 4 database-host

# Test port accessibility
nc -zv database-host 5432

# Check firewall rules (on server)
sudo ufw status
sudo firewall-cmd --list-all

# Capture network trace to see actual TCP disconnections
sudo tcpdump -i any -w /tmp/pg.pcap -f "host database-host and port 5432"

If you see connection resets or timeouts, work with your network admin to:
- Increase idle connection timeout in the firewall/load balancer
- Whitelist your client IP/subnet
- Disable aggressive connection pooling that closes idle connections

6Use connection pooling to survive disconnects

Tools like PgBouncer or Supabase can reconnect automatically if the underlying connection fails.

bash
# Install PgBouncer
sudo apt-get install pgbouncer

# Configure PgBouncer
cat > /etc/pgbouncer/pgbouncer.ini << EOF
[databases]
mydb = host=localhost port=5432 dbname=mydb

[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 25
EOF

# Start PgBouncer
sudo systemctl start pgbouncer

# Now connect through pgbouncer instead (usually localhost:6432)
psql -h localhost -p 6432 -U user -d mydb

Connection poolers hide temporary disconnections from your application by handling reconnection automatically.

Advanced notes

For production deployments, consider these advanced strategies:

Connection Pooling: Tools like PgBouncer (open source) or Supabase/RDS Proxy (managed) sit between your application and PostgreSQL, managing a pool of persistent connections. This shields your app from individual connection failures.

Read Replicas: If you can tolerate eventual consistency, route read queries to replicas. This distributes load and provides failover options if the primary becomes unreachable.

Monitoring: Set up alerts for sudden connection drops using pgAdmin, Datadog, or custom monitoring. Log all disconnection events to correlate with application errors.

Retry Logic: Implement exponential backoff in your application's database connection logic. Libraries like node-postgres and psycopg2 support this out of the box.

SSL/TLS Issues: If using SSL connections, certificate expiration or misconfiguration can cause abrupt disconnections. Check certificate validity with:

bash
openssl s_client -connect host:5432 -showcerts

SELinux/AppArmor: On hardened Linux systems, security policies may be blocking connections. Check audit logs and adjust policies if needed.

Frequently asked questions

What does "server closed the connection unexpectedly" mean?
This error occurs when a PostgreSQL client's connection to the server drops without the client explicitly closing it. This means the server abruptly terminated the connection, leaving the client unable to send or receive data. The error can happen for several reasons: the server process crashed or was killed, network infrastructure (firewalls, load balancers) closed an idle connection, the client sent incompatible protocol data, or the server configuration forced the disconnection due to timeout settings.
How do I fix "server closed the connection unexpectedly"?
PostgreSQL terminates connections unexpectedly due to server crashes, network timeouts, or configuration issues. Fix by checking server logs, enabling TCP keepalives, and verifying network stability.
What causes "server closed the connection unexpectedly"?
Server process crashed or was forcibly terminated due to a bug, out-of-memory condition, or system issue Network component (firewall, load balancer, router) closed idle connections after a timeout period Incorrect or too-strict timeout settings on the server (statement_timeout, idle_in_transaction_session_timeout)
Is the "server closed the connection unexpectedly" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading