The connection to MySQL dropped while a query was running (error 2013)
ERROR 2013 (HY000): Lost connection to MySQL server during queryShort answer
Error 2013 means the client sent a query or was waiting for the answer and the connection ended. The server may have closed it (idle timeout, a packet over max_allowed_packet), the transfer may have outlasted a timeout, or mysqld itself may have restarted after a crash or an out-of-memory kill. Check the server's uptime and error log first.
Fix it fast
1Find out which cause you have
Find out whether the server itself went down. A small Uptime means mysqld restarted, so skip to the crash cause. A large Uptime means the server stayed up and closed or lost this one connection; then the limits listed below decide which cause applies.
SHOW GLOBAL STATUS LIKE 'Uptime'; SELECT @@wait_timeout, @@net_read_timeout, @@net_write_timeout, @@max_allowed_packet, @@connect_timeout; SHOW GLOBAL STATUS LIKE 'Aborted%';2Match what you see, then jump to its fix
- 1
Uptime is only seconds or minutes, every open connection failed at the same moment, and the error log shows a start-up sequence at that time.The server restarted: a crash or an out-of-memory killFix - 2
Only large statements fail: bulk inserts with many rows, big blobs, or a restore of a dump. The same query with fewer rows works.The packet is larger than max_allowed_packetFix - 3
The error says 'during query', appears only on queries that return millions of rows or take long to stream, and the server's Uptime is large.A large result is still being sent when a timeout expiresFix - 4
The first query after a quiet period fails and the next one works, often with 'gone away' (2006) alongside 2013; Aborted_clients keeps growing.The connection sat idle past wait_timeout and a pool reused itFix
- 1
What does the error look like?
ERROR 2013 (HY000): Lost connection to MySQL server during queryERROR 2006 (HY000): MySQL server has gone awayLost connection to MySQL server at 'reading initial communication packet', system error: 0pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
Cause 1 of 4
The server restarted: a crash or an out-of-memory kill
1Check
Read the server's error log around the time of the error, and the kernel log. MariaDB's crash guide says a SIGKILL means something outside the server ended it, and that the operating system kills the server when it runs out of memory, because the database is usually one of the biggest memory users.
journalctl -u mysql -u mariadb --since "1 hour ago" --no-pager | tail -50
sudo journalctl -k --since "1 hour ago" --no-pager | grep -iE 'out of memory|oom|killed process'
mysqladmin version | grep -i uptime2Fix
If the kernel log shows an out-of-memory kill, the server is configured for more memory than the machine or container has. Lower the largest consumers (the InnoDB buffer pool, and per-connection buffers multiplied by max_connections), and leave room for the operating system. If instead the log shows a crash with a stack trace, that is a server problem to investigate from its own log.
# my.cnf, example for a machine with 8 GB shared with the application
[mysqld]
innodb_buffer_pool_size = 4G
max_connections = 150
sudo systemctl restart mysql # or: mariadb3Verify
Uptime keeps growing, and no new kill line appears in the kernel log under load.
mysql -e "SHOW GLOBAL STATUS LIKE 'Uptime'"
sudo journalctl -k --since "1 hour ago" | grep -ci 'out of memory'Confirmed by mariadb.com
Cause 2 of 4
The packet is larger than max_allowed_packet
1Check
The manual says a packet that is too large makes the server assume the client is faulty and close the connection. The limit applies on the server and, separately, in each client program. See the server's value, and compare it with the size of the data you send.
SELECT @@GLOBAL.max_allowed_packet / 1024 / 1024 AS server_mb;
-- the client program has its own limit
-- mysql --help | grep max-allowed-packet2Fix
Raise the limit on the server and in the client that sends the data, or split the statement into smaller batches. SET GLOBAL affects new connections only, so reconnect; add the value to the option file to keep it after a restart.
SET GLOBAL max_allowed_packet = 256 * 1024 * 1024;
# my.cnf
[mysqld]
max_allowed_packet = 256M
# client side, for a restore or a dump
mysql --max-allowed-packet=256M app < dump.sql
mysqldump --max-allowed-packet=256M app > dump.sql3Verify
A new connection reports the new value and the large statement completes.
mysql -e "SELECT @@max_allowed_packet"Confirmed by dev.mysql.com
Cause 3 of 4
A large result is still being sent when a timeout expires
1Check
The manual names a very large result set as one cause: the transfer can run past net_read_timeout, so it suggests raising it. Its default is 30 seconds. Applications can also set their own read and write timeouts in the client library, and the manual says raising them may help.
SELECT @@net_read_timeout, @@net_write_timeout;
-- how long does the query itself run, and how many rows does it return?
SELECT COUNT(*) FROM big_table WHERE created_at >= '2026-01-01';2Fix
Return less data (paginate, filter, or aggregate in SQL) before turning knobs. If a large transfer is legitimate, raise net_read_timeout for that session only and raise any read timeout configured in the application's driver.
SET SESSION net_read_timeout = 120;
-- per-driver timeout, for example PyMySQL: pymysql.connect(..., read_timeout=300)3Verify
The query now finishes, and the failure stays gone when it is run twice.
SELECT @@session.net_read_timeout;Confirmed by dev.mysql.com
Cause 4 of 4
The connection sat idle past wait_timeout and a pool reused it
1Check
By default the server closes a connection that has done nothing for eight hours (wait_timeout, 28800 seconds). Connection pools and long-running workers hold connections for longer than that, and they get an error on the first use of a connection the server already closed. Aborted_clients counts such disconnects.
SELECT @@wait_timeout, @@interactive_timeout;
SHOW GLOBAL STATUS LIKE 'Aborted_clients';2Fix
Make the pool retire connections before the server does (a maximum connection lifetime below wait_timeout), test a connection before use, or reconnect and retry once on 2006 and 2013. Raising wait_timeout is possible, but it keeps dead clients' connections alive on the server.
# HikariCP example: maxLifetime below the server's wait_timeout
spring.datasource.hikari.max-lifetime=1500000 # 25 minutes
# SQLAlchemy
create_engine(url, pool_pre_ping=True, pool_recycle=1500)3Verify
The first request after a quiet period succeeds, and Aborted_clients stops growing.
SHOW GLOBAL STATUS LIKE 'Aborted_clients';Confirmed by dev.mysql.com
How do I stop it coming back?
- Alert on Uptime resetting and on kernel out-of-memory messages, so a restart is noticed before users report it.
- Size buffers so that the buffer pool plus per-connection memory fits in the memory the server really has, in containers too.
- Keep batches of rows and file sizes comfortably below max_allowed_packet, on both server and clients.
- Retire pooled connections earlier than wait_timeout and retry idempotent work once after a lost connection.
Sources
- MySQL 8.4: MySQL server has gone away (2006) / Lost connection (2013)
- MySQL 8.4: Lost connection to MySQL server during query
- MySQL 8.4: Communication errors and aborted connections
- MySQL 8.4: What to do if MySQL keeps crashing
- MariaDB: MariaDB crashes (SIGKILL and out of memory)
- MariaDB: Memory allocation
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Databases
A statement waited for a lock held by another transaction and gave up (error 1205)
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction
Error 1205 means a statement waited longer than innodb_lock_wait_timeout (50 seconds by default) for a row lock that another transaction still holds.
4 causes, each with a fixDatabases
Installing the Airflow MySQL provider fails on pkg-config or mysqlclient
Building the mysqlclient wheel fails during the install
The Airflow MySQL provider depends on mysqlclient, which pip compiles against the MySQL C client library.
2 causes, each with a fixDatabases
A query on Aurora MySQL dies with 'table /rdsdbdata/tmp/#sql... is full'
ERROR 1114 (HY000): The table '/rdsdbdata/tmp/#sqlfd_1586_2' is full
In Aurora MySQL 3, internal temporary tables share one pool, and when that pool and the memory-mapped overflow file are used up, a reader instance ends the query with error 1114.
3 causes, each with a fixDatabases
Azure Database for MySQL refuses a connection that does not use SSL
ERROR 3159 (HY000): Connections using insecure transport are prohibited while --require_secure_transport=ON.
Azure Database for MySQL Flexible Server requires encrypted connections by default (require_secure_transport = ON, TLS 1.2).
4 causes, each with a fixDatabases
Compiling a C or C++ program that includes mysql.h fails
undefined reference to `mysql_init'
The compiler only finds mysql.h when the MySQL client development files are installed and their folder is on the include path.
3 causes, each with a fixDatabases
DBeaver fails to resolve Maven dependencies when downloading a database driver
A driver library does not download automatically
DBeaver downloads driver jars from a Maven repository.
3 causes, each with a fix