Sub topic 9
Caching and TTL
This chapter assumes you can read the answer section of dig output and that you know the lookup path from the earlier chapters: stub resolver, recursive resolver, then root, TLD and authoritative servers. It explains why most lookups never reach an authoritative server, what the TTL controls, and how cached data affects the speed and visibility of DNS changes.
Why DNS caches everything
A full iterative lookup can take several round trips: root, TLD, authoritative. Doing that for every page load would be slow and would overload the root and TLD servers. So every layer that handles DNS answers keeps a copy for a while.
A cache stores a resource record set (RRset) together with an expiry time. An RRset is all records with the same name, class and type. For example, three A records for www.example.com are cached and expire as one unit.
The publisher of the zone chooses how long a copy may be kept. Each record carries a TTL (time to live): the number of seconds a cache may reuse it without asking again. The TTL is an unsigned 32-bit integer in the message, though RFC 2181 says values above 2^31 - 1 should be treated as 0.
Where caching happens
A single lookup can pass through several caches. Each one has its own copy and its own clock.
| Layer | Example | Notes |
|---|---|---|
| Application | Browser, language runtime | Often has its own cache and ignores the OS cache rules. Durations vary by program. |
| Operating system | systemd-resolved, macOS mDNSResponder, Windows DNS Client | Shared by all programs on the machine. |
| Local forwarder | Home router, corporate DNS forwarder | Many routers cache and forward to an upstream resolver. |
| Recursive resolver | Your ISP's resolver, 8.8.8.8, 1.1.1.1 | Shared by many users, so it has the highest hit rate. |
The recursive resolver cache matters most. When thousands of clients ask for the same popular name, one upstream lookup serves all of them until the TTL runs out.
The TTL counts down
The authoritative server always sends the full configured TTL. A cache then lowers the value as time passes and returns the remaining time to its clients. When the remaining time reaches 0, the entry is discarded and the next query triggers a fresh lookup.
You can see this with dig. Ask a public resolver twice and compare the second field of the answer line:
dig @8.8.8.8 +noall +answer example.com A
sleep 10
dig @8.8.8.8 +noall +answer example.com AAn answer line has the form name TTL class type data, for example example.com. 278 IN A 192.0.2.10. If the second query returns a TTL about 10 lower, you hit the cache. If the TTL jumps back to a large value, the entry expired or you reached a different cache. Large public resolvers often run many cache instances behind one address, so you may see TTLs go up and down between queries.
The following script automates the check. It queries one resolver several times and prints the TTL it reports:
import subprocess
import time
def reported_ttl(name, server):
result = subprocess.run(
["dig", f"@{server}", "+noall", "+answer", name, "A"],
capture_output=True, text=True, check=True,
)
lines = result.stdout.strip().splitlines()
if not lines:
return None
# Answer line: name TTL class type data
return int(lines[0].split()[1])
for attempt in range(4):
print(attempt, reported_ttl("example.com", "8.8.8.8"))
time.sleep(5)Expect values that fall by roughly 5 per iteration until an expiry resets them.
Negative caching
Resolvers also cache failures. If you ask for a name that does not exist, the authoritative server answers NXDOMAIN. Asking again for every typo or probe would waste resources, so the resolver remembers the negative answer. The same applies to NODATA, where the name exists but has no record of the requested type.
RFC 2308 defines how long a negative answer is kept. The server includes the zone's SOA record in the authority section. The cache uses the smaller of two values: the TTL of that SOA record and the last field of the SOA, the "negative caching TTL" (historically called MINIMUM).
In the sample zone file from this tutorial, the default TTL is 3600 and the last SOA field is 300. A nonexistent name is therefore cached for 300 seconds.
A practical consequence: if a client looks up a name before you create its record, the resolver may keep saying "does not exist" for up to the negative TTL after you add it. Keep the negative TTL short (a few minutes) if you create records often.
What resolvers do beyond the TTL
The TTL is the publisher's instruction, but resolver operators can adjust it:
- Clamping. Some resolvers enforce a minimum or maximum TTL. An answer published with TTL 5 might be kept for 30 seconds, or one with TTL 604800 might be capped at a day. Do not assume very low TTLs are honored exactly.
- Prefetching. A busy resolver may refresh popular entries shortly before they expire, so users rarely see a miss.
- Serving stale data. RFC 8767 lets a resolver return an expired entry if it cannot reach the authoritative servers. This keeps sites reachable during an outage of the authoritative side, but it also means an old answer can outlive its TTL.
- Capacity eviction. An entry can disappear earlier than its TTL when the cache is full. The TTL is a maximum lifetime, not a guarantee.
Delegation records have their own TTLs
NS records and glue for a zone exist in two places: in the parent zone (as the delegation) and in the child zone (as authoritative data). Each has its own TTL. Resolvers differ on which copy they keep, so a change of name servers does not take effect at a single moment. This is one reason moving a domain to a new DNS provider needs care: keep the old servers answering until the longest relevant TTL, usually the parent's NS TTL, has passed.
Choosing a TTL
A TTL trades speed and load against agility.
| TTL | Benefit | Cost |
|---|---|---|
| Short (30 s to 5 min) | Changes and failover take effect quickly | More queries to your servers, a cache miss more often, so slightly slower lookups for users |
| Medium (1 hour) | Reasonable default for most records | A mistake can linger for up to an hour |
| Long (1 day or more) | Very low query load, resilient to short outages | Changes take a long time to be seen everywhere |
Typical guidance: use a long TTL for records that rarely change (NS, MX), and a short one for records you may need to move quickly (A and AAAA behind a load balancer or failover).
Planned changes
To change an address with little disruption:
- Lower the TTL on the record well ahead of time, at least one old TTL before the change.
- Wait for the old TTL to expire everywhere. Caches that fetched the record just before your edit may keep it for the full old TTL.
- Change the data.
- Verify with
dig @ns1.example.comagainst the authoritative server, then with a public resolver. - Raise the TTL again when you are sure the change is correct.
Flushing and inspecting caches
You can clear caches you control, but not the ones you do not. Nothing lets you flush an ISP's resolver. For local caches:
| System | Command |
|---|---|
| Linux with systemd-resolved | `resolvectl flush-caches` |
| macOS | `sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder` |
| Windows | `ipconfig /flushdns` |
Browsers keep their own caches, which these commands do not clear.
Common errors
- "I changed the record but still see the old one." Check each layer. Query the authoritative server directly with
dig @ns1.example.com. If it returns the new data, the old data is in a cache and will expire within the old TTL. - Lowering the TTL at the moment of the change. The lower TTL only applies to caches that fetch it afterward. Caches holding the old record keep it for the old TTL.
- Mixed TTLs in an RRset. RFC 2181 requires all records in an RRset to have the same TTL. Servers normalize them, so setting different values on records of one name and type has no effect.
- Forgetting negative caching. A name that was queried before it existed can fail for several more minutes.
- Trusting a single
digrun. Anycast resolvers answer from many caches, so repeat the query before concluding anything.
Exercise
You run dig @8.8.8.8 +noall +answer shop.example.com A and get shop.example.com. 120 IN A 192.0.2.80. The zone's configured TTL for this record is 600. Is something wrong, and what does the 120 tell you?
Show answer
Nothing is wrong. The resolver cached the record earlier and has counted its TTL down. Roughly 480 seconds have passed since it fetched the record from the authoritative server, so the entry expires in about 120 seconds. A query to the authoritative server itself would show the full value of 600.
Exercise
A zone has a default TTL of 3600 and an SOA whose last field is 300. A client queries new.example.com, which does not exist yet, and gets NXDOMAIN. You create the record one minute later. How long can that client's resolver keep returning NXDOMAIN, and why?
Show answer
Up to about 300 seconds after the original query, so roughly 4 more minutes after you create the record. The resolver caches the negative answer for the smaller of the SOA record's TTL (3600) and the SOA's negative caching field (300), which is 300 seconds.