Kubernetes DNS 5s Delays: Taming ndots:5 & CoreDNS Latency
Kubernetes DNS calls taking 5 seconds? Diagnose glibc ndots:5 query amplification, kernel conntrack race conditions, and deploy NodeLocal DNSCache.
You inspect your distributed tracing spans during a traffic surge, and an eerie pattern emerges across your microservices. An external payment call or database lookup that typically resolves in 4 milliseconds suddenly logs a latency of exactly 5,004 milliseconds.
In Kubernetes clusters, random 5-second latency spikes are rarely caused by upstream third-party downtime. They stem from a dangerous combination of glibc’s default ndots:5 search domain configuration and Linux kernel netfilter connection tracking (conntrack) race conditions that silently drop UDP packets.
Here is the immediate triage checklist to eliminate 5-second DNS latency spikes across your cluster:
- Audit Pod DNS Configurations: Inspect
/etc/resolv.confinside failing pods to verifyndots:5and the search domain hierarchy. - Apply Trailing Dots to External URIs: Append a trailing dot to hardcoded external domain strings in your application configuration (e.g.,
api.stripe.com./v1/charges), transforming them into Fully Qualified Domain Names (FQDN) that bypass cluster search domains. - Tune Pod-Level ndots: Configure
dnsConfigin your deployment manifests withoptions: [{ name: "ndots", value: "2" }]to restrict search domain lookups to short service names. - Deploy NodeLocal DNSCache: Install the official Kubernetes NodeLocal DNSCache DaemonSet to cache DNS queries locally on each node and upgrade communication with CoreDNS from lossy UDP to persistent TCP.
Illustrative command verifying the /etc/resolv.conf configuration inside a running pod:
# Inspect the default Kubernetes DNS configuration inside a pod container
kubectl exec -it deployment/order-service -- cat /etc/resolv.conf
Illustrative output showing the default ndots:5 directive and search domain list:
nameserver 10.96.0.10
search default.svc.cluster.local svc.cluster.local cluster.local c.my-gcp-project.internal
options ndots:5
Anatomy of the ndots:5 Amplification Trap
To understand why a simple external HTTPS request triggers four redundant DNS lookups, we must examine how Linux resolvers interpret domain names.
The standard Linux C library (glibc) resolver evaluates whether a hostname should be treated as an absolute domain or tested against local search paths based on the ndots threshold. If the number of dots (.) in the target hostname is less than the ndots value, the resolver prioritizes the search domains listed in /etc/resolv.conf.
Kubernetes sets ndots:5 by default so developers can use short, convenient internal service hostnames:
databaseresolves todatabase.default.svc.cluster.localredis.cacheresolves toredis.cache.svc.cluster.local
+-------------------------------------------------------------------------+
| External Query Amplification (ndots:5) |
| |
| Target: api.stripe.com (contains 2 dots; 2 < 5 -> triggers search list) |
| |
| Step 1: api.stripe.com.default.svc.cluster.local -> NXDOMAIN |
| Step 2: api.stripe.com.svc.cluster.local -> NXDOMAIN |
| Step 3: api.stripe.com.cluster.local -> NXDOMAIN |
| Step 4: api.stripe.com.c.my-project.internal -> NXDOMAIN |
| Step 5: api.stripe.com. -> 200 OK (A) |
| |
| Total: 5 DNS round-trips for a single external API request! |
+-------------------------------------------------------------------------+
When your application attempts to resolve api.stripe.com, glibc counts 2 dots. Because 2 is less than 5, the resolver assumes api.stripe.com might be an internal service!
The resolver issues five sequential or parallel DNS lookups against CoreDNS:
api.stripe.com.default.svc.cluster.local(ReturnsNXDOMAIN)api.stripe.com.svc.cluster.local(ReturnsNXDOMAIN)api.stripe.com.cluster.local(ReturnsNXDOMAIN)api.stripe.com.c.my-gcp-project.internal(ReturnsNXDOMAIN)api.stripe.com(Finally resolves to the public IPv4 address)
Every external API call causes an immediate 5x query amplification against your CoreDNS pods. For an application handling 1,000 requests per second, this generates 5,000 to 10,000 DNS queries per second against the cluster DNS infrastructure, exhausting CPU limits and flooding network buffers.
The Linux Kernel Netfilter Conntrack Race: The Secret Behind 5 Seconds
Query amplification creates heavy load, but what causes requests to freeze for exactly 5 seconds?
The root cause lies inside the Linux kernel’s network filter (netfilter) connection tracking subsystem (nf_conntrack).
Parallel UDP Lookups in glibc
When modern applications resolve a hostname using getaddrinfo(), glibc concurrently transmits two distinct UDP packets from the same local socket:
- An A record request (querying IPv4)
- An AAAA record request (querying IPv6)
Both UDP datagrams are destined for the CoreDNS ClusterIP service (e.g., 10.96.0.10:53).
The Conntrack Insertion Collision
Because both packets originate from the same thread, socket, and source port at virtually the exact same microsecond, they pass through the Linux kernel’s iptables / netfilter translation pipeline simultaneously.
+-------------------------------------------------------------------------+
| Linux Kernel Netfilter Conntrack Race Condition |
| |
| Application Pod |
| |--- UDP Packet 1: A Record (Source Port: 42105 -> Dest: 53) ----+ |
| +--- UDP Packet 2: AAAA Record (Source Port: 42105 -> Dest: 53) --+ | |
| | | |
| Linux Kernel (Node) | | |
| +-> Conntrack evaluates Packet 1 -> Inserts (Tuple A) [SUCCESS] | | |
| +-> Conntrack evaluates Packet 2 -> Identical Hash Tuple Detected | | |
| Collision in nf_conntrack_confirm() | | |
| Packet 2 is SILENTLY DROPPED by kernel! <---------------------+ | |
| |
| CoreDNS Pod |
| Only receives Packet 1; Packet 2 never arrives! |
| |
| Glibc Resolver in Pod |
| Waits for missing response... |
| [glibc timeout constant: exactly 5000ms] |
| Timer fires -> Retransmits Packet 2 -> Resolves! |
+-------------------------------------------------------------------------+
When the kernel processes Packet 1, it allocates a conntrack entry and applies Destination Network Address Translation (DNAT) to route the packet to an active CoreDNS pod.
When Packet 2 arrives milliseconds later on the exact same socket tuple, the kernel’s nf_conntrack_confirm() function identifies a hash collision. Instead of queuing the packet, the kernel drops Packet 2 silently.
CoreDNS never receives the dropped query. Back in the client pod, glibc’s resolver waits for the missing response. In glibc, the hardcoded retransmission timeout for UDP DNS queries defaults to exactly 5 seconds.
After 5,000 milliseconds pass without a response, the resolver timer fires, glibc retransmits the dropped packet on a fresh socket, CoreDNS replies in 2ms, and the application resumes. To the user and application metrics, the request took 5,004 milliseconds.
Verifying Conntrack Drops and CoreDNS Saturation
To confirm whether your cluster is suffering from conntrack race conditions or CoreDNS resource starvation, run these three diagnostic checks.
1. Monitor Kernel Conntrack Drop Counters
On your Kubernetes worker nodes, check if netfilter is actively dropping packets due to insertion failures:
# Check node-level conntrack insertion failure counters
sudo conntrack -S
Illustrative output showing dropped packets:
cpu=0 found=120912 invalid=0 ignore=14023 insert=89012 insert_failed=142 drop=142 early_drop=0
cpu=1 found=118942 invalid=0 ignore=12984 insert=87110 insert_failed=98 drop=98 early_drop=0
If insert_failed or drop is greater than zero, the Linux kernel on that worker node is actively discarding concurrent UDP packets.
2. Inspect CoreDNS Latency and Error Metrics
CoreDNS exposes Prometheus metrics on port 9153. Run a Prometheus query to check request latency and RCODE distribution:
# Rate of CoreDNS NXDOMAIN responses (indicates search domain flooding)
sum(rate(coredns_dns_responses_total{rcode="NXDOMAIN"}[5m])) by (server)
# 99th percentile CoreDNS query processing duration
histogram_quantile(0.99, sum(rate(coredns_dns_request_duration_seconds_bucket[5m])) by (le))
If the NXDOMAIN rate dominates normal NOERROR responses, your applications are hammering CoreDNS with search path amplification.
Three Architectural Fixes to Eliminate 5-Second Latency
Resolving this latency bottleneck requires cutting unnecessary queries at the application level, tuning resolver thresholds, and deploying localized DNS caching.
Fix 1: Trailing Dots on External Hostnames (Instant Workaround)
If your application communicates with known external endpoints (e.g., Stripe, AWS, SendGrid, Twilio), append a trailing dot to the hostname string:
// ❌ Triggers 4 internal NXDOMAIN lookups before resolving
const PAYMENT_ENDPOINT = "api.stripe.com/v1/charges";
// ✅ Fully Qualified Domain Name (FQDN): Resolves directly in 1 round-trip!
const PAYMENT_ENDPOINT = "api.stripe.com./v1/charges";
Because api.stripe.com. ends with an explicit root dot, glibc recognizes it as an absolute FQDN. It ignores ndots:5 and dispatches the query directly to the external name server, reducing network hops from 5 to 1.
Fix 2: Optimize Pod-Level ndots via dnsConfig
You can override the default ndots:5 setting on a per-deployment basis. Setting ndots:2 instructs the resolver to only apply cluster search paths to short single-word or two-part service names (e.g., redis or db.internal), while treating any standard domain (like api.stripe.com) as an external query immediately:
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
namespace: default
spec:
replicas: 4
template:
metadata:
labels:
app: order-service
spec:
# Tune resolver configuration for low latency
dnsConfig:
options:
- name: ndots
value: "2"
- name: single-request-reopen
- name: timeout
value: "1"
- name: attempts
value: "3"
containers:
- name: app
image: myorg/order-service:v2.1
Key options explained:
ndots: "2": Bypasses search paths for any domain with 2 or more dots.single-request-reopen: Instructs glibc to close and reopen the network socket between A and AAAA queries, preventing the conntrack collision on simultaneous sends.timeout: "1": Reduces the retransmission timeout from 5 seconds down to 1 second if a packet is lost.
Fix 3: Deploy NodeLocal DNSCache (Enterprise Architecture)
The permanent, cluster-wide architectural solution is deploying NodeLocal DNSCache.
NodeLocal DNSCache runs a lightweight CoreDNS instance as a DaemonSet on every worker node in your cluster, listening on a dedicated link-local virtual IP (169.254.20.10).
+-------------------------------------------------------------------------+
| NodeLocal DNSCache Architecture |
| |
| [ Pod Container ] |
| | |
| | (Local loopback UDP query - sub-millisecond, zero drops) |
| v |
| [ NodeLocal DNSCache (DaemonSet on Node) ] |
| | |
| | (Cache Miss: Persistent TCP connection - No Conntrack Race!) |
| v |
| [ CoreDNS Pods (Cluster Core) ] |
+-------------------------------------------------------------------------+
Benefits of NodeLocal DNSCache:
- Local Node Cache: DNS queries from pods are serviced locally over loopback UDP, responding in sub-millisecond time.
- TCP Upstream Connection: When a cache miss occurs, the NodeLocal agent forwards the query to the central CoreDNS cluster over TCP instead of UDP. This completely bypasses the Linux kernel’s UDP netfilter conntrack race condition.
- High Negative Caching: NodeLocal DNSCache caches NXDOMAIN responses locally, shielding CoreDNS from search path flooding.
To deploy NodeLocal DNSCache, download the official Kubernetes template and substitute your cluster’s DNS service IP:
# Obtain your cluster's existing CoreDNS service IP
kubectl get svc -n kube-system kube-dns -o jsonpath='{.spec.clusterIP}'
# Output: 10.96.0.10
# Deploy NodeLocal DNSCache DaemonSet
kubectl apply -f https://raw.githubusercontent.com/kubernetes/kubernetes/master/cluster/addons/dns/nodelocaldns/nodelocaldns.yaml
Once installed, update your kubelet configuration or pod specifications to point nameserver to 169.254.20.10. All cross-origin UDP collisions and 5-second stalls disappear immediately.
Comparison: Kubernetes DNS Mitigation Strategies
The following table contrasts the four mitigation strategies across implementation complexity, cluster blast radius, and performance impact:
| Mitigation Strategy | Scope | Latency Improvement | Conntrack Race Resolved? | Implementation Overhead |
|---|---|---|---|---|
Trailing Root Dot (.) | Application code | High (eliminates 4 hops) | No (still UDP) | Requires editing external URL configs |
Pod dnsConfig (ndots:2) | Deployment spec | High (stops search spam) | Partially (single-request-reopen) | Must update manifests per service |
| Corefile Autopath Plugin | Cluster-wide | Moderate (resolves early) | No (heavy CoreDNS memory use) | Known race conditions in high-scale pods |
| NodeLocal DNSCache | Entire Cluster | Extreme (sub-1ms cache) | Yes (100% resolved via TCP) | Zero pod changes after cluster deploy |
Tuning the CoreDNS Corefile
If you manage the central CoreDNS deployment, ensure the Corefile includes cache right-sizing and health probes. Edit the coredns ConfigMap in kube-system:
kubectl edit configmap coredns -n kube-system
Configure the cache plugin with explicit TTL boundaries and prefetching:
apiVersion: v1
kind: ConfigMap
metadata:
name: coredns
namespace: kube-system
data:
Corefile: |
.:53 {
errors
health {
lameduck 5s
}
ready
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
fallthrough in-addr.arpa ip6.arpa
ttl 30
}
prometheus :9153
forward . /etc/resolv.conf {
max_concurrent 1000
}
cache 30 {
success 9984 30
denial 9984 5
prefetch 1 10m
}
loop
reload
loadbalance
}
Key Corefile directives:
cache 30: Holds positive DNS records for up to 30 seconds.denial 9984 5: Caches negative lookups (NXDOMAIN) for 5 seconds to reduce redundant search path queries.prefetch 1 10m: Automatically refreshes popular DNS records in the background before they expire, ensuring client requests always hit warm cache.
Frequently Asked Questions
Why does Kubernetes set ndots to 5 instead of 1?
Kubernetes uses ndots:5 to support complex hierarchical service discovery within clusters, allowing pods to communicate across namespaces and subdomains (e.g., service.namespace.svc.cluster.local) using relative names without requiring fully qualified domain names.
Does switching to Alpine Linux fix the 5-second DNS issue?
No. While Alpine Linux uses musl libc instead of glibc, musl executes DNS queries differently and traditionally does not support parallel TCP fallback or single-request-reopen. In fact, earlier versions of Alpine suffered even worse DNS timeouts under high concurrency. Modern production containers should use Debian-slim or distroless images with glibc and proper dnsConfig.
Can I set ndots:1 in my Kubernetes deployment?
Only if all internal inter-service communication uses fully qualified service names (service.namespace.svc.cluster.local). If you set ndots:1 and your code attempts to call order-service/api, the lookup will fail because order-service has 0 dots and will not append the cluster search domain. Setting ndots:2 is the recommended sweet spot.
How do I verify if NodeLocal DNSCache is handling queries?
Exec into a pod and run nslookup or dig against 169.254.20.10. Check query response times; local cache hits should respond in under 1ms. You can also monitor the node_local_dns_requests_total Prometheus metric exposed by the DaemonSet on port 9253.
Related Engineering Guides
- Kubernetes Exit Code 137: Fixing OOMKilled Node Pods: Diagnosing kernel SIGKILL terminations, balancing —max-old-space-size with cgroup limits.
- Serverless Cold Starts at Scale: Slashing P99 Latency: AST parsing bloat, transitive barrel files, and AWS Lambda memory sizing.
- AWS NAT Gateway Billing Traps: Slashing Egress Costs: Bypassing NAT transit fees and routing VPC traffic through private S3 Gateway Endpoints.
Elena Rostova
Product Strategy LeadProduct and operations lead dedicated to helping non-technical founders navigate technical scale and architectural decisions. Advises founders on technical debt triage, cloud unit economics, and rapid pre-launch risk evaluation.
Why do external DNS lookups in Kubernetes pods take exactly 5 seconds?
What does ndots:5 mean in /etc/resolv.conf?
How does appending a trailing dot fix DNS latency?
What is NodeLocal DNSCache and how does it prevent UDP drops?
Have our team inspect your AI-generated codebase.
48-hour turnaround with direct pull requests fixing security and scale bottlenecks.