Video in progress

The IP address of an external API changed, but the Java service still tries the old IP. How is the JVM's DNS cache involved?

The JVM caches DNS answers independently of the OS, according to networkaddress.cache.ttl: 30 seconds by default when there is no security manager, but someone may have set it to -1 (forever). On top of that, old connections in a pool never go back to DNS at all.

📖 Answer

The JVM caches the InetAddress resolve result itself and ignores the TTL in the DNS answer. The value comes from the networkaddress.cache.ttl security property. If it is not set and there is no security manager, the JDK uses 30 seconds. Failed lookups have their own networkaddress.cache.negative.ttl (10 seconds by default).

The problem usually comes from two places:

  1. On old advice, someone set -Dsun.net.inetaddr.ttl=-1, or -1 in the java.security file in the image. Now on a DB failover, or when cloud load balancer IPs change, the JVM keeps hitting the old address until it is restarted.
  2. DNS was updated correctly, but connections in the HikariCP or HTTP client pool were opened to the old IP and are reused until they drop. Here Hikari's maxLifetime and the HTTP client's idle/TTL settings help.

This is a security property, not an ordinary system property, so -Dnetworkaddress.cache.ttl does not work:

// at the start of main(), before the first resolve
java.security.Security.setProperty("networkaddress.cache.ttl", "30");

Or you pass an extra file with -Djava.security.properties=/app/custom.security.

Inside Kubernetes there is one more layer: ndots:5 in the pod's /etc/resolv.conf. A name like api.partner.uz is first queried with api.partner.uz.orders.svc.cluster.local and the other search domains, so every external request costs several wasted DNS queries. Under load this overwhelms CoreDNS. A trailing dot on the name (api.partner.uz.), or ndots: 2 through dnsConfig.options on the pod, reduces it.

For internal services the problem is smaller: a Service's ClusterIP does not change, and pod IPs are swapped behind it. With a headless Service (client-side gRPC balancing, for example), the JVM cache matters again.