Laravel

Fixing Laravel SQLSTATE[HY000] [2006] MySQL Server Has Gone Away


When executing heavy database imports, running long background queue jobs, or handling file uploads, Laravel may abruptly terminate with:

SQLSTATE[HY000] [2006] MySQL server has gone away
(SQL: select * from `jobs` where `queue` = default and `reserved_at` is null ...)

Unlike connection refused errors (which indicate the server is down or ports are closed), Error 2006 means a valid connection existed, but the MySQL server forcibly severed it mid-execution.


Quick Diagnostic Reference

Symptom / Execution Context Root Cause Fix
Long-running queue:work or daemon process MySQL closed the connection during idle time (wait_timeout) Step 1
Fails during file/blob inserts or huge batch insert() Payload exceeded MySQL’s packet ceiling (max_allowed_packet) Step 2
Connection dropped under AWS RDS, DigitalOcean, or Azure Cloud TCP keepalive drop on idle persistent connections Step 3
Crashing complex analytical queries or migrations Query execution exceeded net_read_timeout Step 4

Step 1: Fix Idle Queue Workers (wait_timeout)

Laravel queue workers (php artisan queue:work) run as long-lived daemons. By default, MySQL’s wait_timeout terminates any non-interactive connection that remains idle (often defaulting to 60–600 seconds on managed databases).

When a new job finally arrives, the worker tries to run a query on the stale socket, and MySQL aborts with 2006 Server has gone away.

1. Enable Reconnection on Queue Jobs

If a queue worker runs a job that performs lengthy third-party API calls before touching the database again, force Laravel to reconnect before running subsequent queries:

use Illuminate\Support\Facades\DB;

public function handle()
{
    // Long-running third-party HTTP or file processing
    $response = Http::timeout(180)->get('https://api.example.com/export');

    // Re-verify and reconnect the database connection before saving
    DB::reconnect();

    Transaction::create([
        'payload' => $response->json(),
    ]);
}

2. Restart Queue Workers Gracefully

Prevent persistent workers from sitting on aging TCP sockets indefinitely by enforcing maximum lifetime and job limits in your Supervisor configuration:

php artisan queue:work --max-time=3600 --max-jobs=500 --sleep=3 --tries=3

Step 2: Increase max_allowed_packet for Bulk Inserts

If Error 2006 occurs immediately when inserting large chunks of data, CSV imports, or base64 attachments, the data packet sent by PDO exceeds the MySQL daemon’s configured buffer limit.

Check Current Packet Size:

Connect to your database via terminal or GUI and run:

SHOW VARIABLES LIKE 'max_allowed_packet';

If the value is 4194304 (4MB) or 16777216 (16MB), large payloads will crash the connection.

The Fix:

Increase the packet size to 64M or 128M inside your MySQL configuration file (/etc/mysql/my.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf):

[mysqld]
max_allowed_packet=64M

Restart the MySQL service:

sudo systemctl restart mysql

Step 3: Prevent Cloud Load Balancer TCP Timeouts

Managed cloud databases (AWS RDS Aurora, DigitalOcean Managed DB, Azure Database for MySQL) terminate idle TCP sockets after a short firewall timeout.

To ensure your connection pool stays alive, pass PDO connection keepalives in config/database.php:

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => 'InnoDB',
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::ATTR_PERSISTENT => false, // Set to false to prevent stale persistent sockets in PHP-FPM
        PDO::ATTR_TIMEOUT => 5,
    ]) : [],
],

Step 4: Increase Network Read & Write Timeouts

When executing database operations that take minutes to finish (such as indexing millions of rows or running complex ETL migrations), the connection may time out while waiting for packets to transmit.

Increase the network buffers in your my.cnf or managed database parameter group:

[mysqld]
wait_timeout = 600
interactive_timeout = 600
net_read_timeout = 120
net_write_timeout = 120

Apply dynamically without restarting:

SET GLOBAL wait_timeout = 600;
SET GLOBAL interactive_timeout = 600;
SET GLOBAL net_read_timeout = 120;
SET GLOBAL net_write_timeout = 120;

Prevention Checklist

  1. Set --max-time=3600 on your background queue workers so daemon processes cycle fresh TCP connections regularly.
  2. Call DB::reconnect() after extended non-database delays inside heavy background jobs.
  3. Raise max_allowed_packet=64M if uploading files or batch-inserting large data collections.
  4. Keep PDO::ATTR_PERSISTENT => false under PHP-FPM to prevent stale connection reuse.