Common causes
- A single statement or row is larger than max_allowed_packet, typical when importing dumps with large BLOBs or extended INSERTs
- A long-running PHP worker or queue job kept a connection idle past wait_timeout (default 28800 seconds, often lowered by hosts)
- mysqld crashed or was killed by the Linux OOM killer and restarted
- A query ran longer than a proxy, load balancer or host limit and the connection was cut
- A forked process or persistent connection reused a socket that had been closed
- net_read_timeout or net_write_timeout was too short for a slow network or very large result set
How to fix it
- Check whether MySQL restarted. Run SHOW GLOBAL STATUS LIKE 'Uptime'; and look at the error log (/var/log/mysql/error.log) and dmesg | grep -i oom. A short uptime or OOM entry means the server died, so look at memory, not timeouts.
- Raise max_allowed_packet. Check SHOW VARIABLES LIKE 'max_allowed_packet'; and raise it to 64M or 256M under [mysqld] in my.cnf. For imports also pass mysql --max_allowed_packet=256M, since the client has its own limit.
- Handle idle connections. For workers and daemons, reconnect when a query fails or open a new connection per job. Raising wait_timeout only delays the problem for processes that idle for hours.
- Split very large imports. Re-export the dump with mysqldump --net-buffer-length=1M (or --skip-extended-insert) so each INSERT is smaller than max_allowed_packet.
- Look for slow queries. Enable the slow query log and find statements that run for minutes. Adding an index or batching the work often removes the timeout.
- Restart and verify. Restart with sudo systemctl restart mysql (or mariadb) and confirm the new values with SHOW VARIABLES. On shared hosting ask the provider, since you cannot change server variables yourself.
my.cnf ([mysqld] section)
[mysqld]
max_allowed_packet = 256M
wait_timeout = 28800
net_read_timeout = 120
net_write_timeout = 120 How to stop it happening again
- Reconnect on failure in long-running workers instead of holding one connection forever
- Keep max_allowed_packet the same on the server and on clients that import dumps
- Monitor memory so mysqld is not OOM-killed, and size innodb_buffer_pool_size to the RAM you have
- Store large files on disk or object storage instead of in BLOB columns