Java callers hit dead pod IPs after redeploy: JVM DNS cache and pooled connections
After each redeploy of a downstream service, Java callers threw connect timeouts for minutes. A forever DNS cache in the JVM plus long-lived pooled connections to a headless Service kept old pod IPs alive. How we found it and fixed both layers.
Every time the pricing service was redeployed, its Java callers (checkout and quote) logged a burst of connect timeouts that lasted between two and fifteen minutes. Error rate on checkout jumped to 8 percent during that window, then dropped back to zero on its own. Rollbacks made it worse, because a rollback is another redeploy.
java.net.SocketTimeoutException: Connect timed out
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:546)
at java.base/java.net.Socket.connect(Socket.java:751)
at org.apache.hc.client5.http.socket.PlainConnectionSocketFactory.connectSocket(...)
...
org.apache.hc.client5.http.ConnectTimeoutException: Connect to http://pricing-headless.prod.svc.cluster.local:8080 [pricing-headless.prod.svc.cluster.local/10.42.7.19] failed: Connect timed out
The IP in brackets, 10.42.7.19, belonged to a pricing pod that had been terminated three minutes earlier.
Reproducing it
Run three
pricingreplicas behind a headless Service (clusterIP: None).Send steady traffic from
checkout(Java 21, Apache HttpClient 5.3).kubectl rollout restart deployment/pricing.Watch
checkoutlogs: connect timeouts to old pod IPs start as soon as the first old pod is gone.
With a normal ClusterIP Service the problem did not show up. That was the first strong hint.
What we ruled out
CoreDNS serving stale records.
kubectl execinto a checkout pod andgetent hosts pricing-headless.prod.svc.cluster.localreturned only the new pod IPs within a second of the rollout.Readiness probes. New pods only joined the endpoints after passing readiness, and old pods left the endpoints as soon as they started terminating. The EndpointSlice was correct at all times.
Network policy. Fresh connections from a debug pod to new IPs worked immediately.
The cluster knew the right answer. The Java process did not ask, or did not listen.
Root cause
Two layers were caching addresses:
The base image's
java.securityfile hadnetworkaddress.cache.ttl=-1, which tells the JVM to cache successful DNS lookups forever. Someone had copied it from an old hardening guide. The JVM resolvedpricing-headlessonce at startup and never again.The HTTP client's connection pool kept persistent connections open with no time-to-live. Even after we fixed the TTL, existing connections to old pods stayed in the pool until they failed.
Because the headless Service returns pod IPs directly, both caches pointed at individual pods that no longer existed. The timeouts stopped only when enough requests had failed for the pool to evict connections and, in the processes that did re-resolve, when the cached entry happened to be refreshed.
What is happening under the hood
Java resolves host names through InetAddress, which keeps its own positive and negative caches. Two security properties control them:
networkaddress.cache.ttlfor successful lookups. A value of-1means cache forever. If it is not set, the JDK uses an implementation default (30 seconds in OpenJDK builds when no security manager is installed).networkaddress.cache.negative.ttlfor failed lookups, 10 seconds by default.
These are security properties, set in $JAVA_HOME/conf/security/java.security or with java.security.Security.setProperty() before the first lookup. The old system property -Dsun.net.inetaddr.ttl still works in OpenJDK but is the legacy name.
A ClusterIP Service hides all of this: the name resolves to one virtual IP that never changes, and kube-proxy (or the CNI's eBPF data path) routes each new connection to a ready pod. A headless Service does the opposite: DNS returns the pod IPs themselves, so the client is now responsible for following pod churn.
Connection pools add a second cache. A pooled keep-alive connection is a TCP socket to one specific IP. If the client never closes it, it keeps sending requests to that IP until the socket errors. When a pod is deleted, its IP can stop answering instead of resetting, so the client waits for a connect or read timeout rather than failing fast.
Environment
Component | Version / value |
|---|---|
Kubernetes | 1.31, Cilium CNI |
JDK | Eclipse Temurin 21.0.5 |
HTTP client | Apache HttpClient 5.3 |
Service type | headless ( |
|
|
Pool settings | max 200, no connection TTL |
Minimal reproduction
// Excerpt: resolves once, caches forever with cache.ttl=-1
var cm = PoolingHttpClientConnectionManagerBuilder.create()
.setMaxConnTotal(200)
.setMaxConnPerRoute(50)
.build(); // no TTL, no idle eviction
var client = HttpClients.custom().setConnectionManager(cm).build();
while (true) {
try (var resp = client.execute(new HttpGet("http://pricing-headless.prod.svc.cluster.local:8080/price/42"))) {
EntityUtils.consume(resp.getEntity());
}
Thread.sleep(50);
}
Print what the JVM thinks the name resolves to:
kubectl exec deploy/checkout -- jshell -R-Dx=1 <<'EOF'
System.out.println(java.security.Security.getProperty("networkaddress.cache.ttl"));
for (var a : java.net.InetAddress.getAllByName("pricing-headless.prod.svc.cluster.local")) System.out.println(a);
EOF
In the broken image this printed -1 and the IPs of pods that were long gone.
Who is affected
Java services calling headless Services, StatefulSet pod names or external DNS names that change IPs (cloud load balancers, database failover endpoints).
Images that set
networkaddress.cache.ttl=-1or run with a security manager (where forever is the default on older JDKs).Any client with pooled connections and no connection TTL, in any language.
Callers using a ClusterIP Service are mostly protected from DNS caching, but still need connection TTL when pods scale up, otherwise new pods get no traffic from existing connections.
The fix
We fixed three things: the DNS TTL, the connection lifetime, and the Service choice.
1. Set a bounded DNS TTL in the image.
# $JAVA_HOME/conf/security/java.security (base image)
-networkaddress.cache.ttl=-1
+networkaddress.cache.ttl=10
networkaddress.cache.negative.ttl=5
If you cannot rebuild the base image, set it at startup before any lookup:
public static void main(String[] args) {
java.security.Security.setProperty("networkaddress.cache.ttl", "10");
SpringApplication.run(App.class, args);
}
2. Give pooled connections a time-to-live and evict idle ones.
var connConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(2))
.setTimeToLive(TimeValue.ofSeconds(60)) // re-resolve and reconnect at least every minute
.build();
var cm = PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultConnectionConfig(connConfig)
.setMaxConnTotal(200)
.setMaxConnPerRoute(50)
.build();
var client = HttpClients.custom()
.setConnectionManager(cm)
.evictExpiredConnections()
.evictIdleConnections(TimeValue.ofSeconds(30))
.build();
A 2 second connect timeout also turned "hang for 10 seconds on a dead IP" into a quick failure the retry layer could handle.
3. Use a ClusterIP Service unless you need pod IPs.
checkout had no reason to talk to individual pricing pods. The headless Service was copied from a gRPC example. We switched callers to the normal ClusterIP Service:
-http://pricing-headless.prod.svc.cluster.local:8080
+http://pricing.prod.svc.cluster.local:8080
For the gRPC callers that do need client-side load balancing over pod IPs, we kept the headless Service and set maxConnectionAge on the server so clients reconnect and re-resolve on a schedule, as the gRPC docs recommend for this setup.
Alternatives and trade-offs
Option | Pros | Cons |
|---|---|---|
ClusterIP Service | No client DNS logic, kube-proxy balances new connections | Long-lived connections pin to one pod; still need connection TTL for balance |
Headless + short DNS TTL + connection TTL | Client-side balancing, per-pod routing | Every client library must be configured correctly |
Service mesh sidecar or ambient proxy | Proxy tracks endpoints, retries centrally | Extra moving parts (see post 649) |
| Old pods keep serving while clients notice | Slower rollouts; masks client bugs instead of fixing them |
We also added a short preStop sleep to pricing so that terminating pods finish in-flight requests, but treated it as a safety margin, not the fix.
How to test the fix
Run the reproduction loop against a staging cluster and redeploy repeatedly:
for i in 1 2 3 4 5; do
kubectl -n staging rollout restart deployment/pricing
kubectl -n staging rollout status deployment/pricing --timeout=180s
done
Meanwhile count connect timeouts from the caller:
kubectl -n staging logs deploy/checkout --since=15m | grep -c "Connect timed out"
Before the fix: hundreds per rollout. After: zero across five rollouts.
Confirming in production
Checkout error rate during pricing deploys: dashboards annotated with deploy markers showed no spike over the next 20 rollouts.
Client metric for pool connections per route stayed stable, and connection age histograms capped near 60 seconds.
A startup log line now prints the effective TTL so drift is visible:
INFO dns-config networkaddress.cache.ttl=10 negative.ttl=5
Regression guard
A container test in CI runs
java -XshowSettings:security:properties -version 2>&1 | grep networkaddress.cache.ttl(supported on JDK 21+) and fails if the value is-1or missing.A rule script flags
clusterIP: Nonein Service manifests unless the Service has an annotation explaining why.HTTP client construction is wrapped in one internal factory with TTL and idle eviction on by default.
Security implications
Caching DNS forever was originally a defence against DNS spoofing: if the first answer is trusted, later poisoned answers are ignored. Inside a cluster, CoreDNS is trusted infrastructure and pods churn constantly, so a forever cache trades a small theoretical benefit for real outages. Use mTLS or verified service identity (post 650) to protect against talking to the wrong endpoint, rather than freezing DNS. The fix does not widen exposure beyond that.
Prevention checklist
Never set
networkaddress.cache.ttl=-1in images that run on Kubernetes or talk to failover endpoints.Give every pooled HTTP client a connection TTL and idle eviction.
Default to ClusterIP Services; use headless only for StatefulSets or client-side load balancing you configure deliberately.
Set short connect timeouts so dead IPs fail fast.
Annotate deploys on dashboards so post-deploy error bursts are easy to spot.
References
Oracle, Java networking properties (
networkaddress.cache.ttl): https://docs.oracle.com/en/java/javase/21/core/java-networking.htmlKubernetes, Headless Services: https://kubernetes.io/docs/concepts/services-networking/service/#headless-services
Kubernetes, DNS for Services and Pods: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/
Apache HttpClient 5 connection management: https://hc.apache.org/httpcomponents-client-5.3.x/
gRPC, keepalive and connection age: https://grpc.io/docs/guides/keepalive/
Add a label
Embed this post
<iframe src="https://www.hibug.me/stale-service-discovery-jvm-dns-cache" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I am a frontend engineer who has worked on dashboards, booking flows and design systems, mostly in React and TypeScript. I care about the parts of the web platform that frameworks hide: forms, cookies, rendering cost and what the browser actually does with our code. The bugs I write about usually passed every review and only appeared with production data: a map with a million points, a name with an accent in a PDF, a cookie that one subdomain never sees. Each post shows a minimal reproduction, why the browser or framework behaves that way, and a fix with a test.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.