Last reviewed: November 25, 2026
The first time I took MySQL server has gone away seriously was on a queue worker in one of our Laravel ERP modules. It built a large export, called a slow outside API in the middle, and then tried to save the result. The export worked on my machine every time. On the server it failed now and then with SQLSTATE[HY000]: General error: 2006 MySQL server has gone away, and only on the nights when the API was slow. Restarting the worker "fixed" it until the next slow night.
The message sounds like the database crashed. Usually it did not. Error 2006 is the client telling you that the connection it was holding is no longer there. Something closed it: the server's idle timer, a query that was too big to accept, a restart, or someone running KILL. Your job is to find out which, because each one has a different fix.
For this article I reproduced each cause on a throwaway MySQL 8.4.13 container with PHP 8.4 and PDO on a Linux box. The error messages and log lines below are copied from that test. Where something comes from documentation or framework source rather than my own test, I say so.
A two-minute diagnosis
Before changing any setting, collect three facts. Run these in a MySQL shell connected to the same server your app uses:
SELECT @@GLOBAL.wait_timeout, @@GLOBAL.interactive_timeout, @@GLOBAL.max_allowed_packet;
SHOW GLOBAL STATUS LIKE 'Uptime';
SHOW GLOBAL STATUS LIKE 'Aborted_clients';On my test box (started with --wait-timeout=10 --max-allowed-packet=1M so the errors happen quickly) the output was:
@@GLOBAL.wait_timeout @@GLOBAL.interactive_timeout @@GLOBAL.max_allowed_packet
10 28800 1048576
Uptime 76
Aborted_clients 4How to read it:
- A small Uptime (seconds) right after the errors means the server restarted. Every connection opened before that restart is dead.
- A rising Aborted_clients means the server is closing connections it considers broken or idle.
wait_timeouttells you how long a non-interactive connection (your app) may sit idle. The default is 28800 seconds (8 hours), but managed databases and shared hosts often set it much lower.
Then look at the server error log. This is the most useful step and the one most people skip. With log_error_verbosity set to 3, MySQL writes a note for every connection it aborts, with the reason in brackets:
SET GLOBAL log_error_verbosity = 3; -- then reproduce the error
# on the server (or docker logs <container>)
grep 'Aborted connection' /var/log/mysql/error.log[Note] [MY-015123] [Server] A connection from `root`@`%` was closed by the server due to a timeout
in the communication layer (vio:1, packet:0) 10 seconds after the last command started.
Currently configured wait_timeout is 10 seconds.
[Note] [MY-010914] [Server] Aborted connection 15 to db: 'app' user: 'root' host: '172.17.0.1'
(The client was disconnected by the server because of inactivity.).
[Note] [MY-010914] [Server] Aborted connection 17 to db: 'app' user: 'root' host: '172.17.0.1'
(Got a packet bigger than 'max_allowed_packet' bytes).The text in brackets is your cause. The rest of this guide is organised around it.
Cause 1: the connection sat idle longer than wait_timeout
This is the one I see most in PHP apps: queue workers, cron scripts, import commands and anything that opens a connection, does slow non-database work, and then comes back to the database. MySQL does not ping your app. When the idle time passes wait_timeout it closes its side of the socket, and your app only finds out on the next query.
Here is the smallest reproduction I could write. The server's wait_timeout is 10 seconds and the script sleeps for 12:
<?php
$pdo = new PDO('mysql:host=127.0.0.1;port=3307;dbname=app', 'root', 'secret',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
sleep(12);
foreach ([1, 2] as $n) {
try { $pdo->query("SELECT 1"); echo "q$n ok\n"; }
catch (PDOException $e) { echo "q$n: ", $e->getMessage(), PHP_EOL; }
}q1: SQLSTATE[HY000]: General error: 4031 The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior.
q2: SQLSTATE[HY000]: General error: 2006 MySQL server has gone awayThat first line surprised me. On MySQL 8.0.24 and later the server sends error 4031 just before it drops an idle connection, so the first query after the timeout reports 4031 and every query after that reports 2006. On older servers and on MariaDB you go straight to 2006 (or 2013, "Lost connection to MySQL server during query"). If your error tracker shows a mix of 4031 and 2006, it is the same problem.
Fix 1a: reconnect once, outside a transaction
The durable fix is to treat a lost connection as normal and reconnect. The rule I follow: retry once, and never in the middle of a transaction, because the earlier statements of that transaction are already gone with the old connection. This wrapper is tested on the same box:
<?php
function connect(): PDO {
return new PDO('mysql:host=127.0.0.1;port=3307;dbname=app', 'root', 'secret',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
}
function isLostConnection(PDOException $e): bool {
// 2006 gone away, 2013 lost during query, 4031 idle disconnect (8.0.24+)
return in_array($e->errorInfo[1] ?? null, [2006, 2013, 4031], true);
}
function runQuery(PDO &$pdo, string $sql, array $args = []) {
try {
$st = $pdo->prepare($sql); $st->execute($args); return $st;
} catch (PDOException $e) {
if (!isLostConnection($e) || $pdo->inTransaction()) throw $e;
echo "lost connection ({$e->errorInfo[1]}), reconnecting once...\n";
$pdo = connect();
$st = $pdo->prepare($sql); $st->execute($args); return $st;
}
}
$pdo = connect();
sleep(12);
$v = runQuery($pdo, "SELECT 42")->fetchColumn();
echo "result: $v\n";lost connection (4031), reconnecting once...
result: 42Fix 1b: raise wait_timeout for that session only
If a specific script legitimately idles for a while, raise the timeout for its own connection instead of for the whole server. Tested:
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET SESSION wait_timeout = 600',
]);
// session wait_timeout = 600
// after 12s: still connectedOn PHP 8.5 the same constant is also available as \Pdo\Mysql::ATTR_INIT_COMMAND (from the PHP docs; my test ran on 8.4). I would not raise the global wait_timeout to days just to hide this. Idle connections hold memory and count against max_connections, and on managed services you often cannot change it anyway.
Fix 1c: in Laravel, keep long-running workers honest
This part comes from Laravel's source and docs, not my box test. Laravel already reconnects and retries a query when the error message matches a lost connection, and its list of messages includes both "server has gone away" and the 4031 inactivity text. It skips the retry when a transaction is open (Illuminate\Database\Connection::handleQueryException rethrows if transactions >= 1). So the cases that still break are:
- Jobs that open a
DB::transaction(), then call a slow API inside it. Move the slow call outside the transaction. - Workers on very old Laravel versions whose message list does not include 4031. Upgrade, or call
DB::reconnect()at the start of a job that you know waits a long time. - Workers that live for days. Run them with limits so Supervisor restarts them cleanly:
php artisan queue:work --max-time=3600 --max-jobs=500.
If those jobs then fail for other reasons, my guide to fixing Laravel failed jobs walks through retrying and inspecting them.
Cause 2: the query was bigger than max_allowed_packet
The second common cause is a single statement or row that is larger than the server's max_allowed_packet: a bulk INSERT with thousands of rows, a base64 image stored in a column, or a dump file with long extended inserts. The server refuses the packet and drops the connection. On my 1 MB test server, inserting a 2 MB string through PDO gave:
PDOException: SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes
next query: SQLSTATE[HY000]: General error: 2006 MySQL server has gone awayNotice the second line. If your code catches the first exception and carries on (a loop over import rows, for example), what reaches your logs is 2006, and the real cause is one line above it. Importing the same row from a SQL file with the mysql client failed with ERROR 1153 (08S01) at line 2.
Fix 2a: raise it on the server, and make it stick
SET PERSIST max_allowed_packet = 67108864; -- 64 MB, survives restarts
SELECT @@GLOBAL.max_allowed_packet; -- 67108864I restarted the container after this and the value stayed, with performance_schema.variables_info showing its source as PERSISTED. Two details that tripped me up while testing:
SET GLOBAL max_allowed_packet = 64Mfails withERROR 1232 (42000): Incorrect argument type. TheMsuffix works inmy.cnfand on the command line, not inSET. Use bytes or64*1024*1024.SET SESSION max_allowed_packetfails withERROR 1621: the session value is read-only. The new global value only applies to new connections, so restart PHP-FPM or your workers after changing it.
If you manage the config file instead, put it under [mysqld]:
[mysqld]
max_allowed_packet = 64MFix 2b: raising the client flag alone does nothing
I tried mysql --max-allowed-packet=64M app < big.sql while the server was still at 1 MB, and got the same ERROR 1153. The client and server limits both apply; the smaller one wins. Raise the server value first, then the client value for mysql and mysqldump if your rows are larger than the client default.
Fix 2c: send smaller pieces
A bigger limit is fine for imports, but if application code builds giant statements, chunk them. Insert 500 rows at a time instead of 50,000, and store files on disk or object storage with only the path in MySQL. That also keeps the request from running into PHP's maximum execution time.
Cause 3: the server restarted, was killed, or killed you
Any connection opened before a restart is dead after it. I reproduced this by restarting the container while a PHP script held an open connection; its next query returned General error: 2006 MySQL server has gone away. Running KILL <connection id> from another session produced exactly the same message.
Check, in this order:
SHOW GLOBAL STATUS LIKE 'Uptime';If it is small, the server restarted. Find out why before anything else.- The kernel log for the out-of-memory killer:
sudo dmesg -T | grep -i -E 'killed process|out of memory'. A MySQL process killed by the OOM killer looks like a random 2006 storm in the app. - The MySQL error log just before the restart, for crash or shutdown messages.
- Any tool that kills long queries: a monitoring agent,
pt-killor a DBA cron script that runs KILL. Ask before assuming nobody runs one.
If the database is in Docker, also check that it is not in a restart loop. If the app cannot reconnect at all afterwards and you see "Connection refused" instead, that is a different problem; I covered it in Laravel SQLSTATE connection refused.
Less common causes worth checking
These are written from documentation and past production incidents, not reproduced on the test box:
- Proxies and load balancers with shorter idle timeouts than MySQL, such as ProxySQL, HAProxy, a cloud load balancer, or a NAT gateway. The server log shows nothing because the server never closed the connection. Set the app's reconnect logic anyway, and keep the proxy idle timeout longer than your longest idle gap.
- Forked processes sharing a connection. If a PHP or Python process opens a connection and then forks, two processes write to one socket and the server drops it. Open connections after the fork.
- Persistent connections (
PDO::ATTR_PERSISTENT) handing a stale connection to a new request. Most apps do not need them; turning them off removes a whole class of these errors. - net_read_timeout / net_write_timeout on very slow networks or when streaming huge result sets. Usually you see 2013 rather than 2006 here.
Common mistakes
- Setting
wait_timeoutto a week on the server. It hides the error, holds idle connections open, and does nothing for proxies or restarts. - Retrying inside a transaction. The first half of the transaction was lost with the old connection, so a retry of the last statement saves half a unit of work.
- Retrying forever in a loop. If the server is down, a tight retry loop just fills your logs. Retry once, then fail and let the queue retry later.
- Raising
max_allowed_packeton the client only, or withSET SESSION, and wondering why nothing changed. - Not restarting PHP-FPM or queue workers after changing global variables, so old connections keep the old limits.
- Reading only the app log. The MySQL error log tells you the cause in one line.
Questions I get asked
What is the difference between error 2006 and 2013?
Both mean the connection is gone. 2006 ("MySQL server has gone away") usually means it was already closed when you sent the query. 2013 ("Lost connection to MySQL server during query") usually means it died while the query was running. The causes overlap, and the server error log is how you tell them apart.
What does error 4031 mean?
On MySQL 8.0.24 and later it is the server saying it closed your connection because it was idle longer than wait_timeout. In my test the first query after the timeout got 4031 and the next one got 2006.
Should I just increase wait_timeout?
For one long script, raise it for that session. For the whole server, keep a sensible value and make the app reconnect. A larger global timeout is not a fix for restarts, packet limits or proxies.
How big should max_allowed_packet be?
Big enough for your largest legitimate row or statement, with some margin. 64 MB covers most apps; the MySQL 8.4 default is already 64 MB, so if yours is smaller, someone set it on purpose or a host did.
Does Laravel reconnect automatically?
Yes, for a single query outside a transaction, when the error message matches its lost-connection list. Inside DB::transaction() it throws, by design.
About the author. Muhammad Wilayat Shah is a senior full-stack engineer and team lead based in Islamabad, with 13+ years shipping ERP and SaaS products with Laravel, Node.js, React and Next.js on MySQL, PostgreSQL and Linux. He wrote this after one too many "just restart the worker" fixes for MySQL server has gone away. More at wilayats.com/about.
Last reviewed: November 25, 2026




Comments
Join the discussion. Replies load on demand, up to 5 levels.
0 threads
No comments yet
Be the first to start the conversation.