Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Fix “Lost Connection to MySQL Server During Query” (Error 2013)

MySQL error 2013 is a symptom, not a single fault. This guide shows how to identify the failure phase and apply the correct network, timeout, pooling, or packet-size fix without unsafe retries.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

MySQL error 2013, CR_SERVER_LOST, means the client lost its connection while MySQL was handling a request. The fix depends on when the disconnect occurs: during the initial handshake, while a query is running, while rows are being transferred, after an idle pooled connection is reused, or when a packet exceeds the configured limit.

If you are asking “How do I fix ‘Lost connection to MySQL server during query’?”, “Why does MySQL server has gone away happen?”, or “How do I stop MySQL error 2013?”, start by confirming the server and endpoint, classify the failure phase, then change only the timeout, packet, network, or pooling setting that matches the evidence.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What MySQL error 2013 actually means

The message Lost connection to MySQL server during query is the client-facing form of MySQL error 2013 (CR_SERVER_LOST). It describes a broken client-server conversation, not one specific defect. The same message can appear when the connection fails during DNS lookup or authorization, while the server reads a statement, while it sends a result, or when an application reuses a connection that has been idle too long.

MySQL documentation says frequent lost connections usually indicate network connectivity trouble. The separate “MySQL server has gone away” condition is commonly caused by the server timing out and closing an inactive connection, but a crash, restart, oversized packet, wrong endpoint, or client timeout can produce a similar symptom.

Do not begin by raising every timeout. A longer timeout can hide a failing network, retain dead sockets, increase resource use, or make a duplicate transaction more likely after a retry. First record the exact error text, phase, timestamp, endpoint, query size, and whether the connection had been idle.

Use the failure phase to choose the right fix

When it fails Typical clues First areas to check
Initial connection or authorization “Reading authorization packet,” failure before a query is sent, or intermittent inability to connect DNS, host and port, firewall, server load, connect_timeout
While the server reads a request Large statement, bulk insert, BLOB upload, or a slow client-to-server link max_allowed_packet, net_read_timeout, client write timeout
While results are returned Small queries succeed but large result sets or slow links fail net_write_timeout, client read timeout, network path
After an idle period A pooled connection fails on its first use after minutes or hours wait_timeout, interactive_timeout, firewall or load-balancer idle policy, pool validation
Only with very large values Failure correlates with BLOBs, long strings, or giant multi-row statements Client and server max_allowed_packet, batch size, server memory
Immediately or after a restart Connection drops for many clients at once MySQL error log, crash or restart history, host resources

Timing is more useful than the wording alone. “During query” does not prove the SQL is logically wrong; it often means that data could not be read or written before one side gave up.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Five-minute diagnostic sequence

  1. Confirm the service. Verify that mysqld is running and has not restarted. Check the MySQL error log for crashes, forced shutdowns, out-of-memory events, or aborted connections.
  2. Confirm the endpoint. Compare the application’s hostname, TCP port, named pipe, or Unix socket with the listener actually used by MySQL. A valid server on the wrong port is still the wrong server.
  3. Classify the moment of failure. Note whether it occurs while connecting, sending a statement, receiving rows, or borrowing an idle pooled connection.
  4. Compare a small and large request. Run a lightweight query and then reproduce the failing workload. If only large payloads fail, investigate packet size and batching. If failures track slow links, investigate read/write timeouts and network devices.
  5. Apply one narrow change and retest. Use the same query, data size, route, and client version after the change. Record whether the error log and status counters improve.

Step 1: verify MySQL and the connection endpoint

Check that the server is running

On the database host, confirm the MySQL service is active and review its recent restart history. A server that exits during a query can look like a network failure from the client. Check disk space, memory pressure, and operating-system logs if the MySQL error log shows an abrupt termination.

For a managed database, ask the provider for the instance’s restart and maintenance events. If you cannot access mysqld, its listener, or its logs, provide the provider with the exact timestamp, client error number, endpoint, and query characteristics.

Check host, port, and socket

Make sure the client is using the intended DNS name and that the name resolves to the expected address. Confirm the TCP port or Unix socket path in the application configuration. A local command-line client may silently use a Unix socket while the application uses TCP, so test through the same driver and connection string as the failing application.

Firewall rules, security groups, load balancers, and service meshes must allow the chosen path in both directions. A TCP reset, an idle connection policy, or a faulty cable or switch can terminate an otherwise valid MySQL session.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Step 2: inspect logs and status counters

Increase useful error-log detail

Set log_error_verbosity to 3 when you need more disconnection detail, following your change-control process. Keep the setting long enough to capture a reproduction, then reassess log volume. Align the server-log timestamp with the client timestamp and timezone.

Check aborted-connection counters

MySQL exposes two counters that help separate connection phases:

  • Aborted_connects counts failed attempts to establish a connection, including handshake or authorization failures.
  • Aborted_clients increases when an established client disconnects improperly or is closed after being idle.

Capture the values before and after a controlled reproduction. A rising Aborted_connects count points toward endpoint, DNS, firewall, authentication, or handshake problems. A rising Aborted_clients count is more consistent with idle expiration, client crashes, or interrupted result transfers. These counters are aggregate, so correlate them with timestamps and logs rather than treating them as proof by themselves.

Record the variables that govern the session

For each reproduction, record the effective values of connect_timeout, wait_timeout, interactive_timeout, net_read_timeout, net_write_timeout, and max_allowed_packet. Also record the client-driver and server versions, host and port or socket, query size, expected row count, and whether the connection was reused from a pool.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fix network, DNS, firewall, and endpoint failures

Frequent disconnects on ordinary-sized queries usually require network investigation rather than a MySQL variable change. Test name resolution from the application host, verify the resolved address, and check that the route reaches the database listener. Examine firewall and load-balancer logs for rejects, resets, and idle-flow expiration. On local networks, inspect interface errors and switch or cable faults.

Some routers and firewalls close idle TCP flows. The MySQL protocol does not automatically ping an idle connection, so a connection can look healthy in the pool while the network device has already removed it. Compare the device’s idle limit with the longest time a connection remains unused. If the device cannot be reconfigured, use pool validation and shorter connection lifetimes.

Correct a wrong port or socket before changing timeouts. A timeout increase cannot make a client reach a listener that is not present at the configured endpoint.

Fix an initial handshake or authorization timeout

If the client reports an error while “reading authorization packet,” the disconnect occurs before normal query processing. MySQL’s documented default for connect_timeout is 10 seconds (Oracle MySQL, 2026). A slow or distant connection may need a higher value, but first check DNS latency, authentication plugins, server CPU, and connection storms.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Raise the server-side value only after confirming that the endpoint is correct and the server is responsive. Ensure the client’s connection timeout is at least as long as the server-side allowance; otherwise the client may abandon the attempt first. Retest several fresh connections, not a reused pooled socket, and watch Aborted_connects and the error log.

Fix slow query or result transfers

Client-to-server reads

net_read_timeout controls how long the server waits for more data from a client during a read. Its documented default is 30 seconds (Oracle MySQL, 2026). MySQL suggests increasing it when a slow link or a very large request needs longer to arrive. This is relevant to large uploads, generated SQL, and bulk operations.

Change the client’s write timeout as well, so the client does not stop sending before the server’s limit. Do not use a large value to compensate for a stalled application; investigate whether the client is blocked, CPU-starved, or transmitting over an unreliable route.

Server-to-client writes

net_write_timeout governs how long the server waits while writing a block of a result to the client. Large result sets over a slow connection can exceed the default behavior. Align the client read timeout with the expected transfer time and check for packet loss, bandwidth limits, and a proxy that closes long-running responses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reducing the result set is often safer than extending timeouts indefinitely. Select only required columns, paginate rows, and stream results when the driver supports it. This lowers the time a socket remains open and reduces memory pressure on both sides.

Fix “MySQL server has gone away” after idle time

MySQL normally closes an inactive noninteractive connection after eight hours by default (Oracle MySQL, 2026), controlled by wait_timeout. Interactive sessions use interactive_timeout. A pool can therefore hand an application a socket that the server has already closed. A firewall or router may close it much earlier.

Make pooled connections safe to reuse

  • Validate a connection when it is borrowed, using the pool’s built-in liveness check or a lightweight /* ping */ query where the driver supports it.
  • Set the pool’s maximum idle age below the shortest known server or network idle limit.
  • Enable TCP keepalive where appropriate, while recognizing that keepalive settings differ by operating system and do not replace application-level validation.
  • Close or recycle connections during planned database failovers and maintenance windows.

Reconnect logic must be transaction-aware. If a write may have reached the server before the connection broke, blindly repeating it can duplicate data. Use an idempotency key, a unique constraint, or an application-level transaction strategy before retrying. Reads are generally easier to retry, but only after confirming that the operation is safe and the session state has been recreated.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Fix oversized packets, BLOBs, and giant statements

A MySQL communication packet can contain one SQL statement, one returned row, or a replication event. If either the client or server receives a packet larger than its max_allowed_packet, MySQL closes the connection and reports ER_NET_PACKET_TOO_LARGE. Both sides therefore matter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The documented server default is 64 MB and the protocol maximum is 1 GB (Oracle MySQL, 2026). These are limits, not recommendations. Raising the value increases the amount of memory a connection may need; set it only when the workload requires it and the server has adequate headroom.

Choose between a larger limit and smaller batches

  • Raise the limit together: Configure a server value large enough for the biggest legitimate statement or row, and configure the client or connector to permit at least that size. Restart or reconnect as required by the specific setting, then verify the effective values from both sides.
  • Reduce the payload: Split giant INSERT or REPLACE batches, upload BLOBs in application-managed chunks where supported, and avoid constructing a single enormous SQL string.
  • Measure the real maximum: Include SQL syntax, encoded data, and protocol overhead when estimating statement size. A file’s byte size is not necessarily the final packet size.

If small statements work and the same operation fails only when a BLOB, long string, or large batch crosses a threshold, reproduce with progressively smaller batches. A sharp size boundary strongly supports a packet-limit diagnosis; a gradual failure tied to transfer duration points more toward timeouts or the network.

Client, server, network, or pool: where should you change?

Observed problem Primary change location Risk to consider Verification
Handshake expires before authentication Server connect_timeout, client connection timeout, DNS or network Longer waits can consume connection slots during an outage Fresh connections succeed; Aborted_connects stops rising
Slow upload or download net_read_timeout, net_write_timeout, client read/write timeout, network path Long-held sockets and increased resource use Same workload completes; logs show no transfer timeout
Idle pooled socket is dead Pool validation and lifetime, server timeout, firewall idle policy Validation adds a ping; retries can duplicate writes Borrowed connections pass validation; idle reuse no longer fails
Large BLOB or batch fails Both packet limits or application batching Higher memory use and larger failure blast radius Payload completes at a known size; no packet-too-large error
Many clients disconnect together Server health, restart cause, shared network equipment Changing per-session settings will not repair a host failure Error log and restart timeline explain the common timestamp

Retest without creating a second problem

  1. Save the original settings and capture baseline values for the relevant counters.
  2. Reproduce with the smallest request that fails, then with the production-sized request.
  3. Change one setting or network policy at a time. Record who changed it, when, and whether it is dynamic or requires a restart.
  4. Run the same transaction through the same driver, endpoint, and pool behavior. A successful command-line test over a different socket does not prove the application path is fixed.
  5. Check the MySQL error log, Aborted_connects, Aborted_clients, server restarts, and application retry logs after the test.
  6. Restore an unnecessarily high temporary timeout or packet limit after diagnosis, or document the new operational value and its memory and capacity implications.

A fix is credible when the original trigger disappears under the original workload and the corresponding evidence changes: no handshake failures for a connection issue, no transfer timeout for a slow-link issue, no stale-socket errors after idle reuse, or no packet error at the required payload size.

Prevent recurring lost connections

  • Monitor the MySQL error log and alert on server restarts, repeated aborted connections, and packet-too-large errors.
  • Track connection age, pool borrow failures, query duration, result size, and retry counts in the application.
  • Set pool idle and maximum lifetimes below the strictest known infrastructure timeout, and validate on borrow.
  • Keep bulk statements bounded and make write operations safely repeatable before enabling automatic retries.
  • Document the endpoint, socket, timeout values, packet limits, driver version, and failover behavior so an incident can be reproduced quickly.
  • Test failover and network interruption in a nonproduction environment, including what happens when a connection breaks after the server has accepted a write.

When to escalate

Escalate to the database or infrastructure owner when the server restarts, the error log shows crashes or out-of-memory conditions, multiple applications lose connections simultaneously, or packet and timeout settings are already appropriate. Include the exact client error number, phase, timestamp, host and port or socket, query or payload size, row count, idle duration, client-driver and server versions, relevant variable values, counter deltas, and whether mysqld restarted. That evidence lets an operator distinguish a broken route from a server-side failure without guessing.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.