On This Page
Picture a card-authorisation log service with a flat error graph all day. Then, every night around 02:10, a spike: forty-odd Communications link failure exceptions in about a minute, and then nothing until the next night. Nobody deployed. MySQL never restarted. The spike lines up with the first batch of the nightly reconciliation job, which is the first thing to touch the database after six quiet hours.
That shape is the whole diagnosis, if you know how to read it. Communications link failure is what MySQL Connector/J says when the network conversation with the server broke, and it says the same two words whether you never reached the server or reached it hours ago and were quietly hung up on. The useful part is in the two lines underneath, and almost everybody skips them.
The exception, and the two numbers under it
The version you get when the connection never happened:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:...)
...
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.Net.connect0(Native Method)
...
at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:...)
And the version you get when a connection that worked yesterday is used again today:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet successfully received from the server was 28,800,123 milliseconds ago. The last packet sent successfully to the server was 28,800,124 milliseconds ago.
The exception class is com.mysql.cj.jdbc.exceptions.CommunicationsException in Connector/J 8.x, 9.x and the new calendar-versioned 26.x line (26.10.0 shipped on 2026-10-21, per the Connector/J release notes). On the old 5.1 driver it was com.mysql.jdbc.exceptions.jdbc4.CommunicationsException, and the idle variant tacked on a long sentence that starts with a stray full stop: ". is longer than the server configured value of 'wait_timeout'", followed by advice to use autoReconnect=true. Ignore that advice. More on why below.
getSQLState() returns 08S01, the "communication link failure" class, and getErrorCode() returns 0, because no MySQL server error number was involved. The driver made this one up from a socket exception. That's the first thing to absorb: this is a client-side error. The server may never have heard of you.
Where it shows up tells you a lot too. At application startup, it's almost always the first kind. After a quiet period (overnight, a weekend, the first request after a long GC pause), it's almost always the second.
Did it ever connect at all?
Read the "last packet" sentence before anything else. It's the fastest triage there is.
- "sent 0 milliseconds ago" and "has not received any packets": the driver never got a single byte back. TCP was refused, timed out, the host name didn't resolve, or the TLS handshake failed. Go straight to the
Caused by:line. - "received N milliseconds ago" with a big N: you had a working connection, it sat idle for N milliseconds, and somebody closed it. Compare N with
wait_timeouttimes 1,000 and with every idle timeout between you and the server. - "received N milliseconds ago" with a small N (a few hundred, a few thousand), mid-query: the connection died while busy. Killed thread, server crash or restart, a failover, or a network reset. The server's error log has the answer.
Then two commands, from the app's own host or container:
nc -vz db-host 3306 # anything listening on that address and port, from here?
mysql --protocol=TCP -h db-host -P 3306 -u app -p -e 'SELECT CURRENT_USER(), @@version, @@wait_timeout'
If nc fails, you're in the never-connected bucket and this is really ERROR 2003 wearing a Java costume. If the CLI connects fine from the same place and the app still fails, the difference is in the JDBC URL (host, port, sslMode) or in how long the app holds connections. If the CLI gets a numbered error instead, like 1045 or 1130, use the connection error comparison: those come from a server that answered, and Connector/J reports them as their own SQLException, not as a link failure.
Making both versions fail on demand
Two failures, one container, one Java file. Run it against a disposable database only; the lab shrinks wait_timeout to ten seconds, which you'd never want on a shared server.
I'll be straight about this one: the workspace I wrote this in had no Docker daemon and no route to Maven Central, so I couldn't run it here. The commands below are the ones to use, and the expected output is the message text from Connector/J and the MySQL docs, not a paste from my terminal.
What you need: Docker, a JDK 17 or newer, mysql:9.7.4 (9.7.4 is the current LTS patch, released 2026-10-20 per the 9.7 release notes), and the com.mysql:mysql-connector-j jar from Maven Central (any 8.0.33+, 9.x or 26.x release behaves the same way for this lab).
Step 1: a server that drops idle connections after ten seconds.
docker run -d --name lab-mysql \
-e MYSQL_ROOT_PASSWORD=lab -e MYSQL_DATABASE=authlog \
-e MYSQL_USER=authlog -e MYSQL_PASSWORD=lab-only \
-p 3307:3306 mysql:9.7.4 --wait-timeout=10
docker logs -f lab-mysql # wait for "ready for connections" on port 3306, then Ctrl+C
Step 2: the program. Save as Lab.java:
import java.sql.*;
public class Lab {
public static void main(String[] args) throws Exception {
String url = args[0];
long idleMs = Long.parseLong(args[1]);
try (Connection c = DriverManager.getConnection(url, "authlog", "lab-only")) {
try (Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT CONNECTION_ID(), @@SESSION.wait_timeout")) {
rs.next();
System.out.println("connected: id=" + rs.getLong(1) + " wait_timeout=" + rs.getInt(2));
}
Thread.sleep(idleMs); // the connection sits idle, like a pooled connection overnight
try (Statement s = c.createStatement()) {
s.executeQuery("SELECT 1"); // first use after the idle period
}
System.out.println("still alive");
} catch (SQLException e) {
System.out.println("SQLState=" + e.getSQLState() + " errorCode=" + e.getErrorCode());
for (Throwable t = e; t != null; t = t.getCause()) {
System.out.println(" " + t.getClass().getName() + ": " + t.getMessage());
}
}
}
}
Step 3: never connected. Point it at a port nothing listens on:
java -cp mysql-connector-j-26.10.0.jar Lab.java "jdbc:mysql://127.0.0.1:3399/authlog" 0
Expected: SQLState=08S01 errorCode=0, a CommunicationsException with "The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.", and a cause of java.net.ConnectException: Connection refused. It appears instantly. If it takes about a minute instead and the cause is SocketTimeoutException: Connect timed out or a plain ConnectException: Connection timed out, your packets are being dropped rather than refused, which points at a firewall or security group.
Step 4: idle cut. Real port, fifteen seconds of idleness against a ten-second wait_timeout:
java -cp mysql-connector-j-26.10.0.jar Lab.java "jdbc:mysql://127.0.0.1:3307/authlog" 15000
Expected: the connected: line shows wait_timeout=10, then the second query fails with SQLState 08S01 and "The last packet successfully received from the server was 15,0xx milliseconds ago." The number lands a little above 15,000, not at 10,000, because the driver counts from its last packet, not from when the server gave up.
Forcing levers, and what production looks like: --wait-timeout=10 stands in for the 28,800-second (eight hour) default. Port 3399 stands in for a typo'd port, a stopped server or a container that isn't published.
If you see something else: ERROR 1045 or 1130 means you reached a server with the wrong account (see how MySQL matches user@host). Public Key Retrieval is not allowed is an authentication problem with its own article. And if step 4 prints "still alive", check wait_timeout in the first line: a my.cnf in a reused volume can override the flag.
Teardown: docker rm -f lab-mysql. No named volume was created, so nothing lingers.
The plain version
Connector/J opened a socket, or tried to, and the socket failed. If it failed before the server sent its greeting, you have a reachability problem: wrong host, wrong port, nothing listening, a firewall, DNS, or TLS. If it failed on a connection that had been idle, something between your code and mysqld closed it while you weren't looking, and your code only found out on the next write or read.
Two problems. Same two words.
What the driver knows, and what it's guessing
When a TCP connection is closed by the other side or by a middlebox, your JVM usually isn't told until it tries to use it. MySQL's client protocol has no heartbeat. So a connection can be dead for hours while it sits in a pool looking perfectly healthy, and the failure gets reported at the moment of use, which is why the stack trace always blames whatever innocent query happened to be first.
Connector/J can't see why the socket died. All it has is a SocketException, an EOFException or a SocketTimeoutException from the JDK, plus two timestamps it keeps for itself: when it last sent a packet successfully, and when it last received one. That's where the "last packet" sentence comes from. The timestamps arrived in the 5.1 days (bug 44587), the "has not received any packets" wording via bug 46637. Bug 90753, fixed in Connector/J 8.0.12, was about the driver failing to recognise a wait_timeout expiry because it compared against the wrong timestamp. The numbers are the driver's only evidence, so they're worth reading carefully.
Who closes idle connections? At least three candidates, and they each leave a fingerprint in N:
mysqlditself, afterwait_timeoutseconds of inactivity for normal clients (interactive_timeoutonly applies when the client says it's interactive; Connector/J'sinteractiveClientproperty defaults tofalse). Default 28,800 seconds in 8.0, 8.4 and 9.7. N lands at or above 28,800,000. Managed services and some DBAs set it far lower, so ask the server:SELECT @@GLOBAL.wait_timeout.- Something in the network path: a cloud load balancer, a NAT gateway, a corporate firewall, a Kubernetes service mesh sidecar. These usually drop the state silently, so your next packet gets a reset or vanishes. N clusters around their idle limit, which is often far shorter than eight hours. An AWS Network Load Balancer defaults to 350 seconds for TCP, an Azure load balancer to four minutes. If every N you see is around 350,000 or 240,000, the database isn't your problem.
- A proxy like ProxySQL or RDS Proxy, with its own idle and lifetime rules.
Now the dead end I'd warn you off, because it's the reflex: raise wait_timeout. It feels right. The message even mentions it on old drivers. In the card-authorisation picture from the top it would have done nothing at all if the N values sat at 350,000-something every night and the server's wait_timeout was still eight hours. Raising it to a week would only have meant more idle threads holding memory on the server. The cut was coming from the load balancer.
And the surprise from reading the server side: since MySQL 8.0.24 the server doesn't hang up silently any more when wait_timeout expires. It sends an error packet first, ER_CLIENT_INTERACTION_TIMEOUT, error 4031, and the mysql CLI prints it on your next statement:
ERROR 4031 (HY000): The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior.
That's a clear, honest message. But it only helps when mysqld is the one closing the connection. A load balancer or NAT table that forgets you sends nothing, and you're back to reading timestamps. How each Connector/J release surfaces a 4031 packet I couldn't verify without running the lab, so check getErrorCode() on your own driver: if you see 4031 there, wait_timeout did it, full stop.
Getting from that one wrapper message to the right one of its causes is the sort of thing that eats a day or more when you're doing it from pasted stack traces. This page exists so it doesn't eat yours.
Fixing Communications link failure by which number you got
Never connected ("0 milliseconds ago", no packets received). Fix the cause in Caused by:, not the driver:
ConnectException: Connection refused: nothing listening on that host and port. Wrong port in the URL, server down,bind-addresson127.0.0.1, or a container port that isn't published. In Docker Compose, the classic is an app container diallinglocalhost:3306, which is the app container itself; use the service name. Testcontainers users should take the URL fromgetJdbcUrl()rather than hard-coding 3306, because the mapped port is random.SocketTimeoutException: Connect timed outorConnectException: Connection timed out: packets dropped. Security group, firewall, wrong subnet. SetconnectTimeoutin the URL (default0, meaning no timeout of its own, per the networking properties page) so the failure comes in seconds, not at the operating system's leisure.UnknownHostException: db: DNS. The name only resolves inside some network you aren't in.SSLHandshakeException, often "No appropriate protocol (protocol is disabled or cipher suites are inappropriate)": the JVM and the server couldn't agree on TLS. Typically an old server offering only TLS 1.0 or 1.1 to a modern JDK that disables them, orsslMode=VERIFY_CAagainst a certificate the JVM doesn't trust. Upgrade the server's TLS or fix the trust store. Don't fix it by turning TLS off.sslModedefaults toPREFERREDsince Connector/J 8.0.13.
Idle cut ("received N milliseconds ago", N large). Work out who did it from N, then make sure your pool retires connections before that party does:
# Spring Boot + HikariCP, against a server with wait_timeout=28800 behind a 350 s load balancer
spring.datasource.url=jdbc:mysql://db.internal:3306/authlog?connectTimeout=5000
spring.datasource.hikari.max-lifetime=1500000
spring.datasource.hikari.keepalive-time=120000
Why it works: HikariCP's maxLifetime (default 30 minutes) closes a connection before the server's wait_timeout can, and keepaliveTime (default two minutes in current HikariCP releases; check yours) pings idle connections often enough that a 350-second load balancer never sees one go quiet. The rule of thumb from the HikariCP docs: maxLifetime several seconds shorter than any time limit imposed by the database or the infrastructure. Keepalive has to be shorter than the shortest idle limit in the path.
What it costs: a ping per idle connection every two minutes and a reconnect every 25 minutes. Cheap.
You'll often see HikariCP noticing this before your code does, as a warning like:
HikariPool-1 - Failed to validate connection com.mysql.cj.jdbc.ConnectionImpl@5d1f... (No operations allowed after connection closed.). Possibly consider using a shorter maxLifetime value.
That warning is Hikari catching a dead connection during validation and throwing it away. Harmless once in a while; every night at the same time, it's the problem above. Pool sizing and leak detection belong to the HikariCP pool exhaustion article, so I won't repeat them here.
Died mid-query (N small). Check the server error log and SHOW GLOBAL STATUS LIKE 'Uptime' for a restart, look for a KILL from a DBA or a watchdog, and check whether a failover happened. Connector/J's own socketTimeout (default 0) will also produce a link failure if you set it shorter than a slow query, so look for that in the URL. Those cases overlap heavily with ERROR 2013 and ERROR 2006, which cover the server side in detail.
Not fixes:
autoReconnect=true. The Connector/J manual itself says it's not recommended and deprecated: after a silent reconnect you lose session variables, temporary tables, server-side prepared statements and any open transaction, and the driver can't know whether your last statement ran. It defaults tofalsefor good reason.wait_timeout=31536000. Fills the server with idle threads and does nothing about the network path.- Catching
CommunicationsExceptionand retrying everything. Retrying aSELECTon a fresh connection is fine. Retrying anINSERTwhose fate you don't know is how you double-post a ledger entry.
Pools that retire connections before anyone else does
The design that makes the idle variant go away for good: write down every idle limit between the app and mysqld (server wait_timeout, load balancer, NAT, proxy, mesh), take the smallest, and set the pool's keepalive well under it and its maximum lifetime under the smallest absolute limit. Keep that list in the service's README, because it changes every time someone adds a hop.
Then make the app's own idea of a connection short-lived. Borrow, use, return. A batch job that grabs a connection at 18:00 and holds it while it reads files until 02:00 will hit this no matter what the pool says, because the pool can't retire a connection you're holding.
Watching for it, and which versions say what
On the server: Aborted_clients in SHOW GLOBAL STATUS counts connections closed without a proper goodbye, wait_timeout expiries included. A step change in its rate after an infrastructure change is your early warning. With log_error_verbosity=3, aborted connections also appear in the error log; since 8.0.17 a wait_timeout expiry is logged as its own, more specific note (ER_NET_WAIT_ERROR) instead of a generic read error, per bug 93240.
On the app: count SQLState 08S01 by the bucket you read from the message (never connected, idle cut, mid-query). Alerting on the raw exception name mixes three different problems into one noisy graph.
In tests: a Testcontainers MySQL started with --wait-timeout=5, plus one test that idles a pooled connection for ten seconds before using it. If it fails, your pool settings are wrong, and you found out on a laptop.
Version notes worth keeping:
| Component | What changed |
|---|---|
| Connector/J 5.1 | Old package com.mysql.jdbc; idle message suggests autoReconnect=true |
| Connector/J 8.0.12 | wait_timeout detection fixed (bug 90753) |
| Connector/J 8.0.13 | sslMode replaces useSSL; default PREFERRED |
| MySQL 8.0.17 | Server logs wait_timeout expiries specifically (ER_NET_WAIT_ERROR) |
| MySQL 8.0.24 | Server sends error 4031 before closing an idle connection |
| Connector/J 26.x | Calendar versions (26.7.0, 26.10.0); same CommunicationsException |
After any upgrade of the server, driver, load balancer or mesh, re-check the idle-limit list. That list is the thing that goes stale.
Worth pinning
- "Communications link failure" is a client-side wrapper with SQLState
08S01and error code 0. The answer is in the "last packet" sentence and theCaused by:line. - "Sent 0 ms ago, no packets received" means you never connected. Treat it as a reachability problem.
- A big "received N ms ago" means an idle cut. Match N against
wait_timeoutand every idle timeout in the path before touching anything. - Fix idle cuts in the pool:
maxLifetimeunder the shortest absolute limit,keepaliveTimeunder the shortest idle one. autoReconnect=truehides the failure and can lose your transaction. Leave it off.
Communications link failure: what people search
How do I fix Communications link failure in Spring Boot with MySQL?
Read the "last packet" line first. If it says 0 milliseconds and no packets received, the app can't reach MySQL at the host and port in spring.datasource.url, so check the port, the host name (a Compose service name, not localhost, inside containers) and firewalls. If it shows a large "received" value, set spring.datasource.hikari.max-lifetime below the server's wait_timeout and keepalive-time below any load balancer idle timeout.
What does "The last packet sent successfully to the server was 0 milliseconds ago" mean?
The driver never received a single packet from a MySQL server. TCP was refused or timed out, DNS failed, or the TLS handshake broke, and the Caused by: exception says which. It's the Java-side equivalent of the CLI's ERROR 2003.
Should I add autoReconnect=true to the MySQL JDBC URL?
No. MySQL's own Connector/J documentation calls it not recommended and deprecated, because a silent reconnect drops session state and can't tell you whether your last statement was applied. Use a connection pool that validates and retires connections instead.
Why does Communications link failure happen after the app has been idle overnight?
The server closes connections idle longer than wait_timeout (28,800 seconds by default), and load balancers or NAT gateways often close them much sooner. Your pool still holds the dead connection, and the first query of the morning finds out. A shorter pool lifetime and a keepalive interval fix it.