The Domain Name System (DNS) translates human-readable domain names to machine-readable IP addresses needed to establish communication on the internet. It serves as an essential phonebook for the internet.
Without DNS, we would have to remember a series of numbers that comprise IP addresses for every website or server we wanted to connect with. DNS simplifies this process by mapping memorable names like example.com to their corresponding IP addresses.
This article will provide an in-depth understanding of how DNS works, the role of DNS caching, and a detailed guide on how to flush the DNS cache on Ubuntu systems.
How DNS Lookup Works
So how does your computer translate a domain name to an IP address exactly? It doesn‘t happen magically. The DNS lookup process involves several steps:
1. Recursive DNS Query
Your Ubuntu system is pre-configured with IP addresses of DNS servers known as recursors. When you attempt to access a domain like example.com, your computer sends a recursive DNS query to the recursor asking:
"Hey recursor, can you please find me the IP address for example.com?"
Popular public DNS recursor services include Google DNS (8.8.8.8), Cloudflare (1.1.1.1), and Quad9 (9.9.9.9).
2. Root Nameserver Query
The recursor server does not know the IP address for every domain off hand. It starts the lookup process by asking the root nameservers to find the responsible authoritative nameserver for example.com.
Root nameservers act as the first point of contact and provide information about the Top Level Domains (TLDs) like .com, .org, .net.
3. TLD Nameserver Query
The TLD nameservers keep track of the authoritative nameservers for each domain under the TLD.
When it receives the root nameserver response, the recursor asks the .com TLD:
"Hey .com nameserver, can you tell me the authoritative nameservers for example.com?"
4. Authoritative Nameserver Query
The .com TLD nameserver replies with a list of authoritative nameservers responsible for the example.com domain. The recursor then asks the example.com authoritative nameserver:
"Hey example.com nameserver, what is the IP address for example.com?"
5. IP Address Response
The authoritative nameserver finally responds with the IP address for example.com, which is then returned to your Ubuntu system by the recursor.
This multi-step iterative process of querying different layers of nameservers constitutes a full DNS lookup. Without caching, this entire sequence would have to be repeated every time you needed to access example.com!
The Need for DNS Caching
The full DNS lookup process can take up anywhere from 50ms to a few hundred milliseconds depending on network distance and congestion. Hundreds of DNS requests are made during a single web session. Having to repeatedly perform the full lookup would introduce massive latency and severely degrade user experience.
This is where caching comes into picture. DNS caching eliminates repeat lookups by saving domain name to IP address mappings locally after the first lookup. Subsequent requests for the same domain can be served almost instantly from the cache without having to undergo the full lookup process.
With DNS caching enabled, a web session that previously took 5 seconds could complete in 500ms! Page load times drop significantly through the proactive caching provided by DNS resolvers.
That said, caching also comes with an important tradeoff:
- Records stored in cache can become outdated if the domain‘s IP address changes.
Websites may change hosting providers and migrate to different IP addresses. Content Delivery Networks (CDNs) may alter IP addresses mapped to domain names to route traffic based on location. If the locally cached record still points to an old IP address, users will likely face connectivity errors or be directed to invalid destinations.
It is therefore crucial we provide administrators the ability to flush or invalidate cached DNS records and fetch updated mappings periodically. Let‘s look at how DNS caching is implemented in Ubuntu and how to clear the cache when required.
DNS Caching in Ubuntu
Recent Ubuntu releases (18.04+) come with systemd-resolved enabled by default to handle local DNS caching and resolving:
Recursive (caching) DNS server
running locally
Some metrics exposed by systemd-resolved reveal the effectiveness of DNS caching:
$ systemd-resolve --statistics
DNSSEC supported: no
Transactions:
Current Transactions: 0
Total Transactions: 59214
Cache:
Current Cache Size: 45
Cache Hits: 98174
Cache Misses: 41727
DNSSEC Verdicts:
Secure: 47
Insecure: 12
Bogus: 2
Indeterminate: 0
We can observe:
- Over 98,000 cache hits indicates most DNS queries are served from cache
- The cache hit ratio is (98174 hits) / (98174 hits + 41727 misses) = 70%
- With a 70% cache hit rate, systemd-resolved could avoid ~41K unnecessary recursive lookups!
That‘s a massive reduction in lookups and latency. No wonder major distros now ship with DNS caching enabled out of the box!
When to Flush DNS Cache?
However, as discussed earlier, sometimes websites change hosting providers and migrate to different IP addresses. CDNs also dynamically adjust IP addresses mapping to domains to route users to nearby datacenters.
If your Ubuntu desktop still has old DNS records cached pointing to outdated IP addresses, you may face issues like:
- Websites failing to load or serving 404 errors
- Being redirected to incorrect CDN locations and experiencing slow page loads
- SSL errors due to attempting HTTPS connection to unexpected IP addresses
Clearing stale records and flushing the DNS cache will force Ubuntu to perform a fresh lookup and retrieve updated IP addresses from the nameservers.
Let‘s look at the exact commands needed to invalidate the systemd-resolved cache.
Flush DNS Cache on Ubuntu 18.04/20.04
On recent Ubuntu versions, you can flush cached DNS records using the systemd-resolve utility:
$ sudo systemd-resolve --flush-caches
Simply run this command to dump all existing DNS entries cached by systemd-resolved and fetch the latest mappings afresh.
You can also restart the systemd-resolved service itself to empty its cache:
$ sudo systemctl restart systemd-resolved
After flushing the DNS cache, verification reveals zero cached entries:
$ systemd-resolve --statistics
DNSSEC supported: no
Transactions:
Current Transactions: 0
Total Transactions: 59228
Cache:
Current Cache Size: 0
Cache Hits: 98190
Cache Misses: 41738
With no DNS records cached now, the next lookups will pull updated mappings directly from the nameservers.
Alternate DNS Caching Daemons
Although most Ubuntu desktops rely on systemd-resolved for local DNS caching today, network administrators previously used dedicated cache daemons like dnsmasq or bind9 to serve the same purpose.
You might encounter older Ubuntu 16.04 LTS servers still running such cache daemons. Let‘s explore popular alternatives and how to flush their caches:
dnsmasq
The dnsmasq package provides a lightweight, easy to configure DNS & DHCP server. Configuring dnsmasq for DNS caching looks like:
listen-address=127.0.0.1
bind-interfaces
server=8.8.8.8
cache-size=10000
Flush all cached entries from dnsmasq with:
$ sudo systemctl restart dnsmasq
nscd
nscd caches DNS lookups on Unix-like systems. It also handles caching for other data like users/groups and can speed up system calls.
Enable DNS caching under nscd through:
enable-cache hosts yes
positive-time-to-live hosts 3600
Restarting nscd will invalidate all cached records:
$ sudo systemctl restart nscd
bind9
bind9 (Berkeley Internet Name Domain) is the most widely deployed DNS server package globally. It can function as an authoritative nameserver, a recursor, or for our use case – a caching resolver:
options {
directory "/var/cache/bind";
allow-query { any; };
forwarders {
8.8.8.8;
8.8.4.4;
};
dnssec-validation auto;
auth-nxdomain no; # conform to RFC1035
listen-on-v6 { any; };
};
You can flush bind9‘s cache with:
$ sudo rndc flush
This covers configuration and cache flushing for the most popular DNS caching software on Ubuntu. Pick the one matching your network environment.
Security & Performance Considerations
Before concluding, let‘s also examine some security and performance implications of relying on local DNS caches:
Cache Poisoning Vulnerabilities
The convenience provided by DNS caching does introduce additional attack surface as malicious hackers could attempt targeted cache poisoning.
By injecting specially crafted DNS responses, attackers can trick the cache into storing incorrect IP address mappings. Users could then be redirected to fake, compromised websites masquerading as the legitimate services.
Enabling DNSSEC validation on your recursive resolvers mitigates this vulnerability. DNSSEC cryptographically signs records allowing caches to authenticate the origin and integrity of responses.
Caching Metrics & Recommendations
From a performance lens, caching becomes counterproductive if stale records linger for too long or the cache size is insufficient causing premature evictions.
When evaluating DNS cache configurations, key metrics to analyze include:
- Cache hit ratio – Higher is better
- Hit rate per million queries (HPMQ) – Higher is better
- TTL ratios – Modulate cache expiry period
- Lookup time saved compared to uncached lookups
Based on your usage patterns, strike a balance with tuning parameters like:
- Cache size (number of records)
- Maximum TTL
- Minimum/Maximum cache expiry period
- Prefetch popularity threshold
Flush caches during off-peak hours or install automatic periodic cron jobs to stay proactive against stale records.
Conclusion
DNS caching plays an instrumental role in speeding up domain name resolutions by storing mappings locally. However, cached entries can sometimes become outdated and continue pointing to incorrect IP addresses.
This guide provided an in-depth primer on DNS inner workings, benefits of caching, systemd-resolved usage on Ubuntu and how to flush its cache. We also explored configuration of additional cache daemons like dnsmasq and bind9 that you may encounter.
Accuratelyinvalidating stale DNS records by flushing caches and retrieving updated mappings will mitigate connectivity or redirection issues caused by outdated IP addresses.


