Skip to the fix
PHPSolvedThe fix first, then the reason

Newest fixes

Radovan Sykora in MySQL, PHP | | 7 min

MySQL server has gone away (2006) and lost connection (2013): the causes

MySQL error 2006 means the connection was closed before your query arrived: check idle timeout, packet size and server restarts, in that order, then reconnect.

An unplugged network cable on a concrete floor beside a wall socket
On this page
  1. 2006, 2013, 4031 and 1153
  2. Cause 1: the connection sat idle
  3. Cause 2: the packet was too big
  4. Cause 3: the server went away for real
  5. Less common, quick to rule out

Three questions find nearly every case. Ask them in this order.

  1. Was the connection idle before it failed? Then the server closed it after wait_timeout. Reconnect in the program.
  2. Was the statement large? Then it was bigger than max_allowed_packet. Raise the limit on the server, or send smaller pieces.
  3. Did the server restart? Then look for the crash, the out of memory kill or the planned restart in the logs.

One query answers the third question and gives you the settings for the other two:

sql
SELECT VARIABLE_VALUE AS uptime_seconds
FROM performance_schema.global_status WHERE VARIABLE_NAME = 'Uptime';

SHOW GLOBAL VARIABLES WHERE Variable_name IN
  ('wait_timeout', 'interactive_timeout', 'max_allowed_packet',
   'net_read_timeout', 'net_write_timeout');

SHOW GLOBAL STATUS LIKE 'Aborted_%';

If the uptime is shorter than the time since the error, the server went down and everything else is secondary.

2006, 2013, 4031 and 1153

CodeWho reports itMeaning
2006Your program's libraryThe statement could not be sent, the connection was already closed
2013Your program's libraryThe statement was sent, the answer never came back complete
4031The server, 8.0.24 and laterDisconnected because of inactivity
1153The serverThe packet was bigger than max_allowed_packet
2020Your program's libraryThe answer was bigger than its own packet limit

The MySQL manual page on this error defines the first two. In practice which one you see depends on the library as much as on the cause. Killing a connection in the middle of a SELECT SLEEP(8) gave 2013 in the mysql program and 2006 in PHP, which has its own driver, mysqlnd. So don't build a diagnosis on the number alone.

Cause 1: the connection sat idle

The default wait_timeout is 28800 seconds, eight hours, and an administrator can set it as low as one second. A web request never reaches it. Queue workers, cron jobs that call a slow API in the middle, and scripts that spend minutes creating a file all do. Here is the whole failure in miniature, with the timeout set to one second for a single session:

phpran on PHP 8.2.8
<?php
$socket = getenv('LAB_SOCKET') ?: null;

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
set_error_handler(function ($level, $message) {
    echo "notice from driver: $message\n";
    return true;
});

$db = new mysqli('localhost', 'root', '', '', null, $socket);
$db->query('SET SESSION wait_timeout = 1');
sleep(3);                         // the slow work between two queries

try {
    $db->query('SELECT 1');
} catch (mysqli_sql_exception $e) {
    echo $e->getCode(), ': ', $e->getMessage(), "\n";
}
real output
notice from driver: Packets out of order. Expected 1 received 0. Packet size=145
2006: MySQL server has gone away

The odd "Packets out of order" line is worth recognising, because it's often searched for on its own. MySQL 8.0.24 and later sends a farewell message, error 4031, before it closes an idle connection. PHP 8.2 reads that message where it expected the reply to its query, and complains about the order. The mysql program prints the message itself:

output
ERROR 4031 (HY000) at line 3: The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior.

If you see the packets warning together with 2006, you have an idle timeout, and you can stop looking at packet sizes.

Two timeouts, one of them yours

interactive_timeout applies to programs that ask for it at connect time with the CLIENT_INTERACTIVE option. Everything else gets wait_timeout. According to the server variable reference the session value of wait_timeout is copied from one of the two global values when the connection starts. That explains a common confusion: SHOW VARIABLES LIKE 'wait_timeout' typed into a console can show a number your PHP script never gets. Ask from the script.

Reconnect instead of raising the timeout

A worker that runs for days needs to survive a server restart too, and no timeout value covers that. mysqli won't do it for you. The PHP manual says of mysqli::ping that the reconnect feature was removed in PHP 8.2, and that the function itself is deprecated from 8.4. PDO on the same driver raises the same 2006. A small wrapper is enough:

phpran on PHP 8.2.8
<?php
$dsn = 'mysql:' . (getenv('LAB_SOCKET') ? 'unix_socket=' . getenv('LAB_SOCKET') : 'host=localhost');

final class Db
{
    private ?PDO $pdo = null;

    public function __construct(private string $dsn, private string $user, private string $pass) {}

    private function connect(): PDO
    {
        return $this->pdo ??= new PDO($this->dsn, $this->user, $this->pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ]);
    }

    public function run(string $sql, array $params = []): PDOStatement
    {
        try {
            return $this->attempt($sql, $params);
        } catch (PDOException $e) {
            $lost = in_array($e->errorInfo[1] ?? 0, [2006, 2013, 4031], true);
            if (!$lost || $this->pdo?->inTransaction()) {
                throw $e;
            }
            $this->pdo = null;                 // drop the dead connection
            return $this->attempt($sql, $params);
        }
    }

    private function attempt(string $sql, array $params): PDOStatement
    {
        $stmt = @$this->connect()->prepare($sql);
        @$stmt->execute($params);
        return $stmt;
    }
}

$db = new Db($dsn, 'root', '');
$db->run('SET SESSION wait_timeout = 1');
$before = $db->run('SELECT CONNECTION_ID()')->fetchColumn();
sleep(3);
$after = $db->run('SELECT CONNECTION_ID()')->fetchColumn();
echo $before === $after ? "same connection\n" : "reconnected\n";
real output
reconnected

Two details keep this safe. It refuses to retry inside a transaction, because the server rolled the earlier statements back when the connection closed, and repeating only the last one would write half of the work. And it retries once, so a server that is down produces an error rather than a loop. With 2013 there is one more doubt: the statement may have been executed before the answer got lost. Only retry writes that can be repeated without harm.

New connections also lose session state. The manual's page on automatic reconnection lists what goes: active transactions are rolled back, temporary tables are dropped, session variables return to the global values, and locks taken with GET_LOCK() are released. So anything you set after connecting belongs in connect(). The same page has a warning for code that uses locks. If the network dropped the line and the server hasn't noticed yet, the old session may still be running and still holding its locks, and the new connection waits for them.

For a job with one slow step, the cheaper answer is to close the connection before the step and open it afterwards.

Cause 2: the packet was too big

A statement travels as one packet, and the server refuses one above max_allowed_packet, 64 MB by default in MySQL 8.0. The next block sends 68 MB:

phpran on PHP 8.2.8
<?php
$socket = getenv('LAB_SOCKET') ?: null;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'root', '', '', null, $socket);

$limit = $db->query('SELECT @@max_allowed_packet')->fetch_row()[0];
echo 'limit ', $limit / 1024 / 1024, " MB\n";

$blob = str_repeat('x', 68 * 1024 * 1024);
foreach (["SELECT LENGTH('$blob')", 'SELECT 1'] as $sql) {
    try {
        $db->query($sql);
    } catch (mysqli_sql_exception $e) {
        echo strlen($sql), ' bytes: ', $e->getCode(), ' ', $e->getMessage(), "\n";
    }
}
real output
limit 64 MB
71303185 bytes: 1153 Got a packet bigger than 'max_allowed_packet' bytes
8 bytes: 2006 MySQL server has gone away

Look at the second line of errors. The harmless SELECT 1 is the one that reports 2006, because the server closed the connection after refusing the large statement. If your code ignores the first error, the log only ever shows the second, and it points at the wrong query. The manual's page on packets that are too large describes this sequence, and adds that some programs report a lost connection instead of 1153.

Raising the limit happens on the server:

ini
[mysqld]
max_allowed_packet=128M

Restart, or set it at run time with an administrative account. The session value can't be changed at all:

sqlfails on purpose, MySQL 8.0.33
SET SESSION max_allowed_packet = 134217728;
real output
ERROR 1621 (HY000) at line 1: SESSION variable 'max_allowed_packet' is read-only. Use SET GLOBAL to assign the value

SET GLOBAL max_allowed_packet = 134217728; works, and reaches connections opened afterwards. Persistent connections and running workers keep the old value until they reconnect. The hard ceiling is 1 GB. The manual calls a higher value safe in terms of memory, because the extra space is allocated only when a long statement or row needs it.

MariaDB differs here. Its variable list gives a default of 16 MB on the server side, so a statement that MySQL 8.0 accepted can be refused after a move to MariaDB with no change in the application.

The limit exists a second time, on the receiving side. The mysql program accepts 16 MB by default, so a row of 20 MB ends in ERROR 2020 (HY000): Got packet bigger than 'max_allowed_packet' bytes until you start it with --max-allowed-packet=64M.

Some functions hit the same limit without any error. REPEAT('x', 70000000) returns NULL with warning 1301, "Result of repeat() was larger than max_allowed_packet", so check SHOW WARNINGS when a large value arrives empty.

Prepared statements don't get around it. A 68 MB string passed as a parameter was refused with 1153, and the same amount streamed in 1 MB pieces with send_long_data() was refused with 1105: the limit is applied to the finished parameter. For files of that size, store the file on disk and its path in the table.

Importing a dump

An extended INSERT in a dump can be one very long line. mysqldump keeps these near its net-buffer-length, about 1 MB in the 8.0.33 binary, but a single row with a large BLOB can't be split. Find the longest line before you import:

bash
awk '{ if (length($0) > max) max = length($0) } END { print max " bytes" }' dump.sql

Run it as LC_ALL=C awk ... so that it counts bytes, not characters. If the number is above the target's limit, raise the limit first. Two other ways out are in the mysqldump examples: dump the big table by itself, or use --skip-extended-insert so that each row gets its own statement. If the file goes through phpMyAdmin, PHP's own upload limits come into play before MySQL sees any of it.

Cause 3: the server went away for real

Compare the uptime with the time of the error. After a restart, the MySQL error log has the reason. Find it with:

sql
SELECT @@log_error, @@datadir;

On a Linux machine with systemd, the kernel's account of an out of memory kill is in the journal:

bash
journalctl -k --since "2 hours ago" | grep -i -E 'out of memory|oom|killed process'
journalctl -u mysql --since "2 hours ago"

The unit is called mysqld, or mysql on Debian platforms, and mariadb for MariaDB. When the kernel is the one ending the process, the fix is memory: a smaller innodb_buffer_pool_size, fewer PHP workers, or more RAM. Raising any timeout does nothing. If one query brings the server down each time it runs, keep the exact statement and check its tables with CHECK TABLE.

A KILL statement looks the same from the program's side, and an administrator's script may be doing it to long queries. Aborted_clients goes up by one for a killed connection and by one for an idle timeout, so a rising counter proves that connections are being cut without saying which way. The manual page linked at the top says that log_error_verbosity set to 3 logs some of these disconnections with their reason.

Less common, quick to rule out

A forked child. If a script forks after connecting, the child closes the shared connection when it exits. The parent's next query then fails with 2006, every time. Open a separate connection in each process, after the fork.

A read timeout in PHP. With MYSQLI_OPT_READ_TIMEOUT set to 1, a three second query failed with 2006 after one second. The matching php.ini setting, mysqlnd.net_read_timeout, is 86400 seconds by default, so look for code or configuration that lowers it. Find the php.ini in use before editing one.

Something between the two machines. A firewall or load balancer can drop idle TCP connections on its own schedule, with no word to either end. If it only happens to the remote database and the interval is shorter than wait_timeout, that's the suspect.

2013 at connect time. When the message mentions "reading authorization packet", the manual points at connect_timeout and a slow network, and Aborted_connects counts those attempts.

Same subject