How-To Guide

How to Cache DNS Lookups in Clients

Understand where DNS is cached, honour TTLs and negative caching, and avoid re-resolving on every request.

On this page

  1. Introduction
  2. Where DNS Is Cached
  3. TTL and Negative Caching
  4. Configuring a Client Cache
  5. Interaction with Connection Pools
  6. Pitfalls
  7. Conclusion

Introduction

DNS resolution is a round trip before the round trip: a client that resolves a hostname on every request adds latency and load, and can fail when the resolver is slow. The layers between an application and the domain system each cache, but their behaviour varies and misconfigured caching causes real bugs, such as a client that keeps connecting to a host after a failover because it cached the old address forever. This article explains where DNS is cached, how TTLs and negative caching work, how to configure a client cache, and the pitfalls that turn caching into a correctness problem.

Where DNS Is Cached

A lookup passes through several caches: the operating system resolver, a local caching resolver, the recursive resolver at the ISP or cloud, and the authoritative servers. Each caches according to the TTL of the record, so the effective cache lifetime is the shortest TTL along the path. Understanding that chain explains why a change can take minutes to appear: one of the caches is holding the old record until its TTL expires.

The application is another cache layer. A process that resolves once and keeps the address is caching DNS, often forever, which is fine until the address changes. Many runtimes resolve a hostname per connection and rely on the OS cache, which respects the TTL; a library that resolves once at start-up does not. Knowing which behaviour your client has is the first step.

TTL and Negative Caching

A DNS record carries a time-to-live in seconds; a cache may serve it until the TTL expires and then must re-resolve. For a failover, the TTL bounds how long a client can keep using an old address, so a service that expects fast failover needs a short TTL. The cost of a short TTL is more queries, so the choice is a trade-off between agility and resolver load.

Negative caching stores the fact that a name does not resolve, with its own TTL, so a burst of lookups for a missing name does not flood the resolver. It also means a name that was just created may fail for a short time after, because the negative response is cached. Honour negative caching rather than retrying aggressively, and pick a negative TTL that balances the two. A client that treats every failure as transient and retries without bound defeats negative caching and can trigger resolver rate limiting, which then affects unrelated lookups from the same source.

# Inspect the TTL the resolver returns and the negative-cache behaviour
dig +noall +answer example.com            # shows the record and its TTL
dig +noall +answer example.com A          # repeat: the TTL decreases as it caches

# A name that does not resolve returns NXDOMAIN with an SOA whose
# minimum field is the negative TTL.
dig +noall +authority nonexistent.example.com

# Query a specific resolver and check how long it caches
dig @1.1.1.1 +noall +answer example.com

Configuring a Client Cache

A client-side cache should hold records for at most their TTL, keyed by name and type, and evict on expiry. It should also handle multiple addresses: a name can resolve to several addresses, and the client should try them rather than using only the first. Caching without honouring the TTL, or caching only one of several addresses, produces the common bug of a client stuck on a dead address.

// A TTL-respecting DNS cache with multiple addresses per name.
const cache = new Map(); // key -> { records, expiresAt }

async function resolveCached(name, type = 'A') {
  const key = name + ':' + type;
  const hit = cache.get(key);
  if (hit && hit.expiresAt > Date.now()) return hit.records;

  const resolver = new (require('node:dns').Resolver)();
  const records = await new Promise((resolve, reject) => {
    resolver.resolve(name, type, (err, addrs) => {
      // Honour the record TTL if available; otherwise use a conservative default.
      const ttl = resolver.getDefaultResultOrder ? 30 : 30;
      err ? reject(err) : resolve({ addrs, ttl });
    });
  });
  cache.set(key, { records, expiresAt: Date.now() + records.ttl * 1000 });
  return records;
}

Interaction with Connection Pools

A connection pool keeps connections to a resolved address, so a pool can outlive the DNS change even when the resolver cache expires. When a failover happens, existing pooled connections to the old address stay usable until they are dropped, and new connections resolve the new address. To react quickly, the pool must recycle idle connections and must not keep a connection alive indefinitely.

For an address that changes, consider resolving periodically and updating the pool, or using a library that re-resolves on connection creation and honours the TTL. The same stale-connection problem appears when a load balancer changes its IP: pooled connections pin to the old one until they are recreated. Bounded connection lifetime is the mitigation.

Pitfalls

The classic pitfall is caching forever: a client that resolves once at start-up and never again keeps using an address even after the service moved. This is convenient until the first failover, and then it is an outage that a restart fixes, which hides the design flaw. Honour the TTL, or at least re-resolve on connection failure.

A second pitfall is using only the first address of a multi-address record, which turns a redundant service into a single point of failure and ignores the round-robin the DNS intended. Try multiple addresses on failure. A third is ignoring negative caching and hammering the resolver for a name that does not exist, which can trigger rate limiting on the resolver and fail legitimate lookups.

Conclusion

DNS is cached at several layers, and a client is one of them. Cache records no longer than their TTL, handle multiple addresses so a dead one does not become a single point of failure, honour negative caching so a missing name does not flood the resolver, and bound the lifetime of pooled connections so a failover is actually seen. The trade-off is between how fast a change takes effect and how much resolver load you accept; choose the TTL from your failover requirement, and never cache an address forever.

Sources: RFC 1035: Domain names, RFC 2308: Negative caching of DNS queries, Node.js dns module.

FAQ

Why does a DNS change take time to take effect?
Several caches sit between the client and the authoritative server, each holding the old record until its TTL expires. The effective delay is the shortest TTL along the path, so a long TTL keeps the old address in use until it expires.
Why should a client handle multiple addresses for a name?
A name can resolve to several addresses for redundancy. Using only the first turns the service into a single point of failure and ignores the distribution DNS intended. Try the other addresses when one fails.

Related Examples