Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween 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 Scan×
Skip to content
World desk11 min

How to Fix the MySQL Server Has Gone Away Error (ERROR 2006)

A practical guide to diagnosing and fixing MySQL ERROR 2006, including idle connection timeouts, max_allowed_packet limits, client retries, forked processes, network failures, and server crashes.

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.

ERROR 2006 (HY000): MySQL server has gone away means your client no longer has a usable connection to MySQL. The fastest fix is not to change a random server variable. First determine whether the connection died after sitting idle, during a large request, because of a network or name-resolution problem, because application code reused a closed or fork-shared connection, or because the server restarted or crashed. Then apply the smallest fix that matches that evidence.

What the error means

MySQL reports this family of failures when a client and server can no longer complete their conversation. The related client conditions are:

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.
  • CR_SERVER_GONE_ERROR (usually displayed as error 2006): the client could not send a new request to the server.
  • CR_SERVER_LOST (often displayed as error 2013, “Lost connection to MySQL server during query”): the client did not receive a complete response.

The distinction is useful, but neither code identifies the root cause by itself. A connection can be lost because the server closed an idle session, a packet exceeded a limit, a TCP operation timed out, code used a connection after closing it, a forked process shared a socket, DNS or a firewall blocked the path, or mysqld terminated.

Start with timing and evidence

Record the details before changing configuration. They usually narrow the cause more effectively than a blanket reconnect loop.

  1. Write down the exact code and message: 2006, 2013, or another connector-specific message.
  2. Note the connector or driver, application language, MySQL version, client host, database host, and whether the connection is pooled.
  3. Capture the operation that failed: a simple query, a long-running query, a bulk INSERT/REPLACE, a BLOB upload, or a result fetch.
  4. Mark when the failure occurs. Does it happen immediately after a connection has been idle, only while a query is running, only for one host, or after a server restart?
  5. Save the relevant application and MySQL log entries, including timestamps, so they can be matched across systems.
Observed pattern Most useful first checks
First query after a long idle period fails wait_timeout, interactive_timeout, pool health checks, connector reconnect behavior
Failure occurs while sending or receiving a large statement or BLOB Server and client max_allowed_packet, batch size, client read/write timeouts
Only one application host or network path is affected DNS, port 3306, firewall, routing, TCP settings, host-specific privileges, Performance Schema host cache
Several clients fail at the same timestamp Server uptime, restart records, error log, operating-system events, killed threads
Failure follows a process fork or explicit close Connection lifecycle code; one independent connection per child process

Cause 1: MySQL closed an idle connection

MySQL identifies an idle timeout as the most common reason for this error. By default, the server closes a noninteractive connection after eight hours with no activity. That period is controlled by wait_timeout. Interactive clients can also be affected by interactive_timeout, depending on how the client establishes the session.

Check the server’s timeout values

From a working session, run:

SHOW VARIABLES LIKE 'wait_timeout';
SHOW VARIABLES LIKE 'interactive_timeout';

Compare the result with the longest time a pooled or persistent connection can sit unused. A pool that keeps sockets for longer than the server allows will eventually hand an expired socket to the application.

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

Make the pool validate sessions

Configure the connector or pool to test a connection before borrowing it, or to discard and recreate sessions that have exceeded the server’s idle period. Depending on the driver, the health check may issue a lightweight ping or a trivial query. The important behavior is:

  • Detect a stale connection before sending the real operation when possible.
  • Reconnect only the session that failed, not every active session in the pool.
  • Respect transaction boundaries; a reconnect cannot restore an uncommitted transaction or session variables that were not reapplied.
  • Use a bounded lifetime or idle limit in the pool that is shorter than the server’s timeout, with a margin for clock and scheduling differences.

Some connectors expose mysql_ping() or an equivalent API. Check the behavior of the specific driver: a ping can verify liveness, but it does not make an unsafe write retry safe.

Should you increase wait_timeout?

Only when the workload genuinely needs longer idle sessions and the server can support the extra resources. Raising the value indefinitely leaves more sleeping sessions consuming connection slots and memory. For most web applications, right-sized pooling, validation, and reconnect-on-borrow are safer than an extremely long server timeout.

Cause 2: The request or result exceeds max_allowed_packet

A statement, parameter, or result packet that is too large can cause MySQL to close the connection. This is common with large multi-row INSERT or REPLACE statements, bulk imports, and BLOB or long-text values. MySQL’s documented default for max_allowed_packet in the cited 8.0 context is 64 MB, but the deployed version and configuration must be checked rather than assumed. The client has its own packet limit, so changing only the server may not solve the failure.

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

Inspect both sides

On the server, run:

SHOW VARIABLES LIKE 'max_allowed_packet';

Then inspect the connector’s packet or maximum message setting. Names differ by driver; some clients inherit a compiled default while others expose a connection option. The effective limit is constrained by whichever side is lower.

Reduce the request before raising limits

  • Split a huge multi-row statement into smaller batches.
  • Stream large files or values when the connector supports streaming instead of building one enormous request in memory.
  • Commit in deliberate chunks so a failed batch can be identified and retried without duplicating an entire import.
  • Measure the largest encoded statement, not just the raw file size; SQL syntax, escaping, character encoding, and protocol overhead add bytes.

Raise the limit carefully when necessary

If the workload requires larger packets, set a value high enough for the largest legitimate operation on both server and client, then restart or reconnect as required by the version and configuration method. Leave headroom, but do not choose an arbitrarily huge value: packet buffers can increase per-connection memory pressure, and many simultaneous imports can exhaust available memory. Verify the resulting value from a fresh connection and test a representative payload.

Cause 3: Client read or write timeout

A connector can terminate an operation when it waits too long to write a request or read a response. Long-running queries, slow storage, large result sets, and congested links can all expose an aggressive client timeout. A server-side idle timeout may then appear as a client error if automatic reconnect is disabled.

Separate query duration from network silence

Check whether the server is still working when the client gives up. A query that legitimately runs for several minutes needs a client read timeout that exceeds that duration, plus transfer time for the result. Conversely, increasing a timeout will not repair a broken route or a server process that has already crashed.

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

Understand reconnect and retry semantics

Automatic reconnect can hide an idle disconnect for a read-only operation, but it can also create dangerous write behavior. If the client cannot prove whether the server received a transaction or statement, blindly resending a non-idempotent INSERT, payment update, or job claim can create duplicates. Prefer explicit retry rules:

  • Reconnect and retry only after classifying the failure as a lost session.
  • Retry reads or idempotent writes when the transaction design makes duplication impossible.
  • Use unique keys, transaction identifiers, or an application-level idempotency key for operations that may be sent twice.
  • Reapply required session state, such as database selection, time zone, isolation level, and temporary tables, after reconnecting.

Cause 4: Application code closed or shared the wrong connection

Queries after an explicit close

A call sequence that closes a connection and later attempts to execute a query is a logic error, even if it worked intermittently in development. Trace the connection object through request handlers, background jobs, error handlers, and cleanup code. Ensure that a failed operation cannot leave a closed object in a cache or pool.

Forked processes

Processes created with fork() inherit the parent’s file descriptors, including a MySQL socket. The child and parent then compete to use one protocol stream, which can corrupt request and response boundaries and produce apparently random disconnects. Open a new MySQL connection inside every child after the fork. Do not pass a live connection, cursor, or pool from the parent into workers. Close the parent’s inherited descriptor in the child before creating its own session when the runtime requires that cleanup.

Pool and thread lifecycle checks

  • Return connections to the pool only after rolling back or committing the current transaction according to application policy.
  • Do not use a connection concurrently from multiple threads unless the connector explicitly supports that pattern.
  • Close cursors and result streams before returning a connection to the pool.
  • After a communication exception, discard the connection unless the driver documents it as safely reusable.

Cause 5: DNS, firewall, routing, or TCP failure

A database setting cannot repair a blocked port or broken network path. DNS failures, a firewall denying TCP port 3306, a route that drops packets, disabled networking, faulty TCP/IP configuration, and defective network equipment can all surface as MySQL communication errors. MySQL’s skip_networking option also prevents TCP connections by design; clients must then use the supported local transport.

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

Compare hosts and paths

If local connections work but a remote application fails, compare the affected host with a known-good host. Check that the hostname resolves to the expected address and that the path reaches the database listener. Use the operating system’s approved DNS and TCP diagnostics, and verify that security groups, host firewalls, and intermediate firewalls allow the intended port. A host-specific failure also warrants checking MySQL account host privileges and the Performance Schema host cache.

Inspect server networking

Confirm that MySQL is listening on the expected interface and port, and that skip_networking is not enabled unintentionally. Review bind-address and TCP settings appropriate to the deployment. Do not expose a database port broadly just to test connectivity; make the narrowest temporary rule needed, then remove it.

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

Cause 6: Killed thread, restart, or server crash

A killed session or a terminated mysqld process breaks every connection that depended on it. Check server uptime and restart evidence with:

mysqladmin version

Compare the reported start time with the application error timestamp. Then review the MySQL error log and operating-system service logs. For more disconnection detail, MySQL documents increasing log_error_verbosity to 3, subject to the version’s configuration rules.

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

When a repeatable query crashes the server

If the same statement consistently causes a restart or kills mysqld, stop treating the symptom as a transient connection problem. Preserve the failing query, schema details, server version, error log, and restart time. Investigate resource exhaustion, storage faults, corrupted data, plugins, and known server defects using the logs and your organization’s incident process. A retry loop can increase damage and obscure the trigger.

Distinguish an administrative kill

An administrator or automated timeout may intentionally terminate a thread. Correlate the failure with maintenance jobs, deployment scripts, resource governors, and commands that kill sessions. Fix the policy or workload causing the kill rather than raising client timeouts blindly.

Server-side evidence to collect

After reconnecting, gather counters and host information while the incident is still occurring:

SHOW GLOBAL STATUS LIKE 'Aborted_clients';
SHOW GLOBAL STATUS LIKE 'Aborted_connects';
SHOW GLOBAL STATUS LIKE 'Connection_errors%';
SELECT * FROM performance_schema.host_cache;

Aborted_clients and Aborted_connects provide context about sessions that ended unexpectedly or failed during connection establishment. The Connection_errors_* variables break connection failures into categories such as host, handshake, and internal errors. The Performance Schema host_cache table can reveal repeated DNS, TCP, or handshake problems by source host. Interpret counters as trends: inspect their change over the incident window rather than assuming the current total belongs to one outage.

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.

Use logs strategically

  • Error log: server crashes, restarts, aborted connections, resource failures, and configuration problems.
  • General query log: a temporary diagnostic tool for correlating received statements and connection events; enable it only with a clear retention and performance plan.
  • Application log: connector exception, elapsed time, host, operation type, transaction identifier, and whether a retry occurred.

Fixes by failure pattern

Evidence Corrective action Avoid
Only the first request after long inactivity fails Align pool lifetime with wait_timeout; validate or recreate stale sessions. Raising the timeout without considering sleeping-connection capacity.
Large import, BLOB, or multi-row statement fails Reduce batch size; increase server and client max_allowed_packet only as required and safe. Changing only one side or selecting an unlimited-looking value.
Failure follows a close, pool reuse, or fork Repair ownership; open one connection per child and discard broken sessions. Sharing inherited sockets or returning active result streams to a pool.
One host or route fails Correct DNS, firewall, routing, TCP, listener, or hardware issues; verify host-specific access. Expecting a MySQL variable to fix a blocked port.
Uptime reset or error-log crash evidence Investigate the restart, killed thread, resource failure, or server defect. Masking a crash with automatic retries.

A safe recovery checklist

  1. Stop repeated retries if the failing operation is a non-idempotent write.
  2. Record error code, timestamp, host, connector, query type, and idle duration.
  3. Check MySQL error and application logs, then compare mysqladmin version uptime with the incident.
  4. Inspect wait_timeout, interactive_timeout, and both client and server packet limits.
  5. Collect Aborted_clients, Aborted_connects, Connection_errors_*, and performance_schema.host_cache evidence.
  6. Test whether the issue follows one host, network path, process, worker, query, or payload size.
  7. Apply the narrow fix: pool validation, smaller batches, coordinated packet limits, lifecycle correction, network repair, or crash remediation.
  8. Reconnect with a fresh session and reapply required session state.
  9. Retry only when the operation’s duplication and transaction consequences are understood.
  10. Monitor the same counters, logs, latency, and failure pattern after the change.

Common mistakes that make the outage worse

  • Changing every timeout at once: you lose the evidence needed to identify the cause and may consume connection resources.
  • Raising max_allowed_packet only on the server: the client can still reject the payload.
  • Retrying every error automatically: a lost acknowledgement can turn one write into two.
  • Keeping dead sockets in a pool: every borrower receives the same failure until the pool evicts them.
  • Blaming MySQL for a network outage: DNS, firewall, routing, and hardware require infrastructure fixes.
  • Ignoring restart evidence: a crash needs root-cause analysis, not a larger retry budget.
  • Using a forked parent connection: inherited sockets are not independent database sessions.

When you do not administer the server

Provide the database administrator or hosting team with the exact error, UTC timestamp, source host, destination host and port, connector version, query category, payload size, idle duration, and whether other clients were affected. Ask them to check timeout and packet variables, error-log entries, uptime, connection counters, host-cache records, and firewall or DNS events for that interval. This information lets the administrator distinguish a stale pooled session from a server-wide restart without guessing.

Preventing future “gone away” incidents

  • Set pool idle and maximum lifetimes below the server’s enforced timeout, with a safety margin.
  • Enable connection validation and discard sessions after communication exceptions.
  • Keep bulk statements within a tested packet and memory budget; make batch size configurable.
  • Instrument query duration, bytes or rows per batch, reconnect count, and error code.
  • Use idempotency keys or transaction design that makes safe retries explicit.
  • Alert on rising aborted-connection and connection-error counters, restart events, and repeated failures from one host.
  • Test network failover, server restart behavior, and worker-process startup in a nonproduction environment.

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.