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.
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.
Navigate to your PostgreSQL log directory and examine recent log entries for CRITICAL or FATAL errors that coincide with connection issues:
# 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.
Configure TCP keepalive settings in postgresql.conf to detect stale connections before network components close them:
# 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 keepalivesThen reload the configuration:
sudo systemctl reload postgresql
# or
sudo -u postgres psql -c "SELECT pg_reload_conf();"Check current timeout settings and adjust them to values suitable for your application:
-- 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 = 600000Match these values to your application's expected query duration and session behavior.
Connection pooling prevents connection exhaustion and provides automatic recovery from stale connections:
# 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 pgbouncerConfigure your application to connect to PgBouncer (port 6432) instead of PostgreSQL directly.
Ensure PostgreSQL listens on the correct network interfaces in postgresql.conf:
# 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 postgresqlAlso verify pg_hba.conf allows connections from your client IP.
Add exponential backoff retry logic to handle transient connection failures:
// 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));
}
}
}If the issue persists after checking logs and configuration, investigate network-level problems:
# 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.pcapLook for patterns of connection resets or unexpected closure from network devices.
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.
ERROR: syntax error at end of input
Syntax error at end of input in PostgreSQL
Bind message supplies N parameters but prepared statement requires M
Bind message supplies N parameters but prepared statement requires M in PostgreSQL
Multidimensional arrays must have sub-arrays with matching dimensions
Multidimensional arrays must have sub-arrays with matching dimensions
ERROR: value too long for type character varying
Value too long for type character varying
insufficient columns in unique constraint for partition key
How to fix "insufficient columns in unique constraint for partition key" in PostgreSQL