How-To Guide

How to Handle DNS Failures and Fallback

Make outbound calls resilient to DNS failures: cache resolutions, add timeouts, retry other records, and avoid tight retry loops on resolution errors.

On this page

  1. Introduction
  2. Bound resolution time
  3. Retry across addresses, not the same one
  4. Cache with respect for TTL
  5. Distinguish error classes
  6. Test the fallback path
  7. Common pitfalls
  8. Conclusion

Introduction

Before an application can open a connection it must resolve a hostname to an address, and that step is easy to overlook until it fails. A DNS outage, a slow resolver, or a stale cached address all present as a request that hangs or errors before any TCP connection is attempted. Because resolution happens below the code a developer usually writes, its failure modes are often invisible in application logs and hard to diagnose.

This tutorial builds outbound call handling that is resilient to DNS failure. It covers bounding resolution time, retrying across multiple resolved addresses rather than the same one, caching with respect for record TTLs, and classifying resolution errors so the caller retries the ones worth retrying. The examples use Node.js, but the strategies apply to any HTTP client.

Bound resolution time

A resolver that hangs is worse than one that fails fast, because a hanging lookup consumes a connection slot and a request timeout without producing an error you can act on. Wrap resolution in a timeout so it fails within a known budget, and account for that budget in the overall request timeout. If the total request budget is one second and resolution may take five, the request will time out before it even connects.

Resolution can fail for several reasons: the name does not exist (NXDOMAIN), the server is unreachable (timeout), or the server returned an error (SERVFAIL). These are not equivalent. NXDOMAIN usually means a misconfiguration and retrying rarely helps; a timeout may be transient and worth one retry; SERVFAIL can indicate a temporary resolver problem. Classify before deciding to retry.

import { lookup } from 'node:dns/promises';

async function resolveWithTimeout(host, timeoutMs) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);
  try {
    return await lookup(host, { all: true, signal: controller.signal });
  } finally {
    clearTimeout(timer);
  }
}

Retry across addresses, not the same one

A hostname commonly resolves to several addresses for load balancing and redundancy. If the first address refuses connections, the fix is to try the next address, not to retry the first in a loop. Resolve all addresses once, then attempt each in order with a short per-attempt timeout, and stop at the first success. This is the client-side half of redundancy: DNS gives you several addresses, and the client is responsible for using them.

Interleave addresses or randomize the starting point to spread load across all of them rather than hammering the first. When one address is down, a client that always starts with the first address pays its connection failure on every request until the record changes. Randomizing the order avoids that hotspot.

async function connectAny(host, port, timeoutMs) {
  const addresses = await resolveWithTimeout(host, timeoutMs);
  const shuffled = addresses.slice().sort(() => Math.random() - 0.5);
  let lastError;
  for (const { address, family } of shuffled) {
    const socket = await tryConnect(address, port, family).catch((e) => { lastError = e; });
    if (socket) return socket;
  }
  throw lastError ?? new Error('no address reachable for ' + host);
}

Cache with respect for TTL

Resolving on every request adds latency and resolver load. Cache the resolved addresses, but honor the record’s time-to-live so a failover to a new address takes effect within the TTL window. Use the TTL as a ceiling, and cap very long TTLs with a shorter maximum of your own so a bad address cannot be pinned for hours. Also implement negative caching carefully: caching an NXDOMAIN briefly avoids hammering the resolver, but set a short negative TTL so a newly created record is seen quickly.

Do not rely solely on the operating system resolver cache, whose behavior and TTL handling vary by platform. An explicit cache in your client makes the behavior predictable and testable, and lets you serve a stale address during a resolver outage if you decide that availability matters more than freshness for that dependency.

Distinguish error classes

Treat the error classes separately in your retry policy. NXDOMAIN: fail fast, alert on a configuration error, and do not retry within the request. Timeout: retry with backoff and jitter, bounded to a small number of attempts. SERVFAIL: retry once, then fail. Connection refused after a successful resolution: rotate to another address rather than re-resolving. Conflating all of these into a single retry loop either wastes attempts or gives up on transient failures that a single retry would fix.

Record the resolver error class in logs and metrics so you can tell a resolver outage from an application bug. A spike in timeouts points at the resolver or the network; a spike in NXDOMAIN points at a deployment that changed a hostname; connection errors point at the network or the target itself.

type ResolutionError = 'nxdomain' | 'timeout' | 'servfail';

function classify(err: NodeJS.ErrnoException): ResolutionError {
  if (err.code === 'ENOTFOUND') return 'nxdomain';
  if (err.code === 'ETIMEOUT' || err.name === 'AbortError') return 'timeout';
  return 'servfail';
}

const policy: Record<ResolutionError, { retries: number }> = {
  nxdomain: { retries: 0 },
  timeout: { retries: 2 },
  servfail: { retries: 1 },
};

Test the fallback path

DNS failure is hard to reproduce against real infrastructure, so test it with a controlled resolver or an injected lookup function. Seed several addresses where the first refuses connections and assert the client proceeds to the second. Simulate a timeout and assert the request fails within budget rather than hanging. Simulate NXDOMAIN and assert no retries occur. These tests make the policy visible and prevent a refactor from quietly restoring a tight retry loop.

Common pitfalls

Retrying the same address in a tight loop, resolving on every request, ignoring the record TTL, treating every resolution error as retryable, and letting resolution hang without a timeout are the recurring mistakes. Each has a direct countermeasure: address rotation, an explicit TTL-aware cache, error classification, and a bounded resolution budget. Together they turn a fragile dependency into a managed one.

Conclusion

Treat DNS as a fallible dependency rather than a transparent function. Bound lookup time, resolve once and try each address rather than retrying one, cache with TTLs that allow failover, and classify errors so retries match the failure. Self-check by injecting a resolver that fails the first address and times out, and asserting the client rotates and fails within budget. When resolution failure is handled deliberately, an outage becomes a slow path instead of an incident.

Sources: RFC 1035: Domain names implementation and specification, RFC 2308: Negative caching of DNS queries, Cloudflare: What is DNS.

FAQ

Should I retry a DNS failure aggressively?
No. A tight retry loop on a resolution failure multiplies load on an already-struggling resolver and rarely helps. Use exponential backoff with jitter, and cap the number of attempts; if the name does not resolve, the caller should fail fast and let a higher layer decide.
Does the OS cache DNS lookups?
Often yes, through a stub resolver or a system cache, but the behavior, TTL handling, and negative caching vary by platform and configuration. Do not rely on it for correctness; if you need predictable failover, cache explicitly in your client with the record TTL as the ceiling.

Related Examples