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.
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.
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:
# 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.logLook 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.
Ensure PostgreSQL is actually running and accepting connections.
# 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 5432If the server crashed, restart it:
# On Linux with systemd
sudo systemctl restart postgresql
# Or with manual startup
pg_ctl -D /path/to/data/directory startMany 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:
# 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:
# /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 upAfter editing postgresql.conf, reload the server:
sudo systemctl reload postgresqlOverly aggressive timeout settings can close connections prematurely. Review these settings:
-- 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 issuesBe 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.
Network issues between your client and server can cause unexpected disconnections.
# 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
Tools like PgBouncer or Supabase can reconnect automatically if the underlying connection fails.
# 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 mydbConnection poolers hide temporary disconnections from your application by handling reconnection automatically.
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:
openssl s_client -connect host:5432 -showcertsSELinux/AppArmor: On hardened Linux systems, security policies may be blocking connections. Check audit logs and adjust policies if needed.
insufficient columns in unique constraint for partition key
How to fix "insufficient columns in unique constraint for partition key" in PostgreSQL
ERROR 42501: must be owner of table
How to fix "must be owner of table" in PostgreSQL
trigger cannot change partition destination
How to fix "Trigger cannot change partition destination" in PostgreSQL
SSL error: certificate does not match host name
SSL error: certificate does not match host name in PostgreSQL
No SSL connection
No SSL connection to PostgreSQL