2. Common DNS caching services used in Unix/Linux systems:

0 27
Author: Zhai HailongI. BackgroundIn the field of computer science, one of the pr...

Author: Zhai Hailong

I. Background

In the field of computer science, one of the principles that should be considered first when it comes to performance optimization actions is the use of caching. A reasonable data caching mechanism can bring the following benefits:

1. Shorten the data acquisition path, cache hot data nearby for quick subsequent reading, thereby significantly improving processing efficiency;

2. Common DNS caching services used in Unix/Linux systems:

2. Reduce the frequency of remote data acquisition, alleviate the pressure on backend data services, and reduce the network bandwidth cost between the front end and the back end;

From the multi-level cache design of CPU hardware, to the fast display of pages by browsers, to the mainstream commercial products such as CDN, cloud storage gateway, and so on, the caching concept is applied everywhere.

In the public network field, the caching mechanisms of mature products such as operating systems, browsers, and mobile terminal APPs greatly alleviate the service pressure faced by network providers such as China Telecom, China Mobile, China Unicom, content providers such as major portal platforms, and CDN vendors, so that the operator's DNS can calmly face the billions of DNS resolutions per second, the network device cluster can easily bear the Tbit-level internet bandwidth per second, and the CDN platform can quickly handle the billions of requests per second.

Faced with the large and continuously growing scale of domain access in the company at present, while the author's team is continuously optimizing the cluster architecture and improving the performance of DNS software, it is also urgently needed to promote the optimization of the domain resolution request mechanism in various client environments, therefore, it is specially organized to investigate and write this guide article, in order to provide reasonable suggestions for the front-end development and operation and maintenance personnel of the company, customers and cooperative parties, optimize the overall DNS request process, and increase the efficiency of the business.

This article mainly discusses how to implement DNS resolution record caching locally for clients under different business and development language backgrounds, and at the same time, based on the author's team's understanding of DNS itself and the company's network environment, some other measures are given, ultimately committed to the normalization of DNS resolution requests on the client side.

Second, explanation of terms

1. Client

The client referred to in this article refers to all objects that actively initiate network requests, including but not limited to servers, PCs, mobile terminals, operating systems, command-line tools, scripts, service software, user APPs, and so on.

2. DNS

Domain Name System (Server/Service), domain name system (server/service), can be understood as a type of database service;

The client communicates with the server over the network, which is identified by the IP address; while as the user of the client, it is difficult for humans to remember a large number of IP addresses, so easy-to-remember domain names such as www.jd.com, will map the domain name andThe mapping relationship of IP addresses is stored in DNS for client queries;

The client can only initiate network communication requests to the IP address after obtaining the IP address of the service end by sending a domain resolution request to the DNS, and truly obtain the service or content carried by the domain name.

Reference:Domain Name System Domain resolution process

3. LDNS

Local DNS, local domain name server; in the public network access environment, it is usually automatically allocated by the network supplier (the supplier has control rights, and can even perform DNS hijacking, that is, tampering with the IP address obtained by resolving the domain name), and in the internal network environment, it is automatically allocated by the IT department;

Typically, Unix, Unix-like, and MacOS systems can view their LDNS by /etc/resolv.conf, declared after nameserver, and this file also supports user self-service editing and modification, thus specifying LDNS, such as common public DNS such as Google DNS, 114DNS, etc.; it is generally not recommended to make changes擅自 without consulting the IT department in a pure internal network environment, which may cause the service to be unavailable; for reference.man resolv.confCommand result.

When there is an abnormal situation in domain name resolution, the possibility of LDNS service abnormality or resolution hijacking should also be considered.

Reference:Modify TCP/IP settings (including DNS) in the Windows system;

4. hosts

The DNS system can dynamically provide the mapping relationship between domain names and IP addresses, and static record files of domain name and IP mapping relationships commonly exist in various operating systems' hosts files. Typically, hosts records take precedence over DNS resolution, that is, when there is no local cache or the cache does not hit, the corresponding domain name records are queried first through hosts. If there is no related mapping in hosts, then continue to initiate a DNS request. For the control of this logic in the Linux environment, please refer to the following section on DNS cache in C/C++ language introduction.

Therefore, in practical work, we often use the above default characteristics to write the mapping relationship between specific domain names and specific IP addresses to the hosts file (commonly known as 'fixed hosts'), which is used to bypass the DNS resolution process and perform targeted access to the target IP (its effect is the same as the -x option of curl, or the -e option specifying the proxy of wget);

5. TTL

Time-To-Live, survival time value, this concept is applicable in many fields and may have different meanings.

The TTL descriptions in this article are all for data caching, which can be understood directly as the 'validity period' of cached data. Starting from the time the data is cached, data that exists in the cache for a duration longer than the TTL specified is considered expired. When the data is called again, it will immediately confirm its validity or re-acquire it from the authoritative data source.

Since the cache mechanism is usually passively triggered and updated, during the cache validity period of the client, if the backend authoritative data changes, the client will not be aware of it, which is manifested as a certain degree of data update delay in business and a temporary inconsistency between cached data and authoritative data.

For the cache TTL of the client-side DNS records, we recommend a value of 60s; at the same time, for low-sensitivity services such as testing, or domain resolution that is not frequent, it can be appropriately extended, even reaching the level of hours or days.

III. DNS resolution optimization suggestions

1. Research on the support of DNS cache by various language network libraries

The following research results are recommended for developers to refer to in order to implement self-developed client DNS cache. The support for DNS cache may vary from language to language, and we will analyze them one by one here.

C/C++ language

(1) The getaddrinfo function of glibc

The glibc library in the Linux environment provides two domain name resolution functions: the gethostbyname function and the getaddrinfo function. gethostbyname was commonly used, but with the transition to IPv6 and thread-safe programming models, getaddrinfo is more useful because it parses IPv6 addresses and is thread-safe. It is recommended to use the getaddrinfo function.

Function prototype:

int getaddrinfo( const char *node, 
                 const char *service,
                 const struct addrinfo *hints
                 struct addrinfo **res);
Copy code

The getaddrinfo function is a relatively low-level basic library function, many domain name resolution functions in development languages depend on this function, so we introduce the processing logic of this function here. Trace the system call of this function through the strace command.

1670399221_639044f51490813a92515.png!small?1670399224520

1) Find the nscd cache (for an introduction to nscd, see the following text)

We can see the following system calls through the strace command in the Linux environment

//Connect to nscd
socket(PF_LOCAL, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 3
connect(3, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
close(3) 
Copy code

Connect to the nscd service to query the DNS cache through the unix socket interface "/var/run/nscd/socket".

2) Query the /etc/hosts file

If the nscd service is not running or the cache is not hit, continue to query the hosts file, and we should see the following system calls

//Read the hosts file
open("/etc/host.conf", O_RDONLY)        = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=9, ...}) = 0
...
open("/etc/hosts", O_RDONLY|O_CLOEXEC)  = 3
fcntl(3, F_GETFD)                       = 0x1 (flags FD_CLOEXEC)
fstat(3, {st_mode=S_IFREG|0644, st_size=178, ...}) = 0
Copy code

3) Query DNS service

The IP address of the DNS server (nameserver) is queried from the /etc/resolv.conf configuration, and then a DNS query is performed to obtain the resolution result. The following system calls can be seen:

//Get DNS service IP from resolv.conf
open("/etc/resolv.conf", O_RDONLY)      = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=25, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fef2abee000
read(3, "nameserver 114.114.114.114\n\n", 4096) = 25
...
//Connected to DNS service, starting DNS query
connect(3, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("114.114.114.114")}, 16) = 0
poll([{fd=3, events=POLLOUT}], 1, 0)    = 1 ([{fd=3, revents=POLLOUT}])
Copy code

Whether the client first searches for the /etc/hosts file or first retrieves the DNS server for query resolution from /etc/resolv.conf is controlled by /etc/nsswitch.conf:

#/etc/nsswitch.conf part configuration
...
#hosts:     db files nisplus nis dns
hosts:      files dns
...
Copy code

Through the strace command, it can be seen that after the nscd socket system call and before reading /etc/resolv.conf, the file is read

newfstatat(AT_FDCWD, "/etc/nsswitch.conf", {st_mode=S_IFREG|0644, st_size=510, ...}, 0) = 0
...
openat(AT_FDCWD, "/etc/nsswitch.conf", O_RDONLY|O_CLOEXEC) = 3
Copy code

4) Verification

#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>

int gethostaddr(char * name);

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "%s $host", argv[0]);
        return -1;
    {}

    int i = 0;
    for(i = 0; i < 5; i++)
    {
        int ret = -1;
        ret = gethostaddr(argv[1]);
        if (ret < 0)
        {
            fprintf(stderr, "%s $host", argv[0]);
            return -1;
        {}
        //sleep(5);
    {}

    return 0;
{}

int gethostaddr(char* name)
{
    struct addrinfo hints;
    struct addrinfo *result;
    struct addrinfo *curr;
    int ret = -1;
    char ipstr[INET_ADDRSTRLEN];
    struct sockaddr_in  *ipv4;

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    ret = getaddrinfo(name, NULL, &hints, &result);
    if (ret != 0)
    {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret));
        return ret;
    {}

    for (curr = result; curr != NULL; curr = curr->ai_next)
    {
        ipv4 = (struct sockaddr_in *)curr->ai_addr;
        inet_ntop(curr->ai_family, &ipv4->sin_addr, ipstr, INET_ADDRSTRLEN);
        printf("ipaddr:%s\n", ipstr);
    {}

    freeaddrinfo(result);
    return 0;
{}
Copy code

In summary, the getaddrinfo function combined with nscd can implement DNS caching.

(2) Domain Name Resolution Function of libcurl Library

The libcurl library is a commonly used network transmission library for clients in C/C++ languages. The curl command is based on this library. This library also calls the getaddrinfo library function to implement DNS domain resolution and supports nscd DNS caching.

int
Curl_getaddrinfo_ex(const char *nodename
                    const char *servname
                    const struct addrinfo *hints
                    Curl_addrinfo **result)
{
    ...
    error = getaddrinfo(nodename, servname, hints, &aihead);
    if(error)
        return error;
    ...
{}
Copy code

Java

Java is the main language used by many companies for business system development. By writing a simple HTTP client program, we can test and verify whether Java's network library supports DNS caching. The test verifies that the HttpURLConnection component in the Java standard library and Apache httpcomponents-client are both supported.

(1) Java Standard Library HttpURLConnection

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpUrlConnectionDemo {

    public static void main(String[] args) throws Exception {
        String urlString = "http://example.my.com/";

        int num = 0;
        while (num < 5) {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            os.flush();
            os.close();

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                {}
                System.out.println("rsp:" + sb.toString());
            } else {
                System.out.println("rsp code:" + conn.getResponseCode());
            {}
            num++;
        {}
    {}
{}
Copy code

The test results show that the Java standard library HttpURLConnection supports DNS caching, with only one DNS request out of 5 requests.

(2) Apache httpcomponents-client

import java.util.ArrayList;
import java.util.List;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;

public class QuickStart {
    public static void main(final String[] args) throws Exception {
        int num = 0;
        while (num < 5) {
            try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
                final HttpGet httpGet = new HttpGet("http://example.my.com/");
                try (final CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
                    System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
                    final HttpEntity entity1 = response1.getEntity();
                    EntityUtils.consume(entity1);
                {}
            {}
        num++;
        {}
    {}
{}
Copy code

The test results show that Apache httpcomponents-client supports DNS caching, with only one DNS request in 5 requests.

The test results show that Java's virtual machine implementation has a set of DNS caching, that is, the implementation of a simple DNS caching mechanism in java.net.InetAddress, with a default caching time of 30 seconds, which can be modified by networkaddress.cache.ttl. The caching range is the JVM virtual machine process, which means that within 30 seconds, a domain name will only request the DNS server once in the same JVM process. At the same time, Java also supports nscd DNS caching, and it is estimated that the underlying call is made to the getaddrinfo function, and the caching level of nscd is higher than that of the Java virtual machine's DNS caching.

# The default cache ttl is modified in jre/lib/security/java.security, where 0 is no caching, and -1 is permanent caching
networkaddress.cache.ttl=10

# This parameter sun.net.inetaddr.ttl was the default value before, and has now been replaced by networkaddress.cache.ttl
Copy code

Go

With the development of cloud-native technology, the Go language has gradually become the first language of cloud-native, and it is necessary to verify whether Go's standard library supports DNS caching. Through our test and verification, we found that Go's standard library net.http does not support DNS caching, nor does it support nscd caching. It should not have called the library function of glibc, nor implemented the function of getaddrinfo. This is related to the bootstrapping of the Go language. Since version 1.5, Go has been written almost entirely in Go (.go) and assembly (.s) files, and the C (.c) files of previous versions have been rewritten. However, there are some third-party Go versions of DNS caching libraries that can be implemented at the application layer, and the httpclient of the fasthttp library can also be used.

(1) Standard library net.http

package main

import (
        "flag"
        "fmt"
        "io/ioutil"
        "net/http"
        "time"
)

var httpUrl string

func main() {
    flag.StringVar(&httpUrl, "url", "", "url")
    flag.Parse()
    getUrl := fmt.Sprintf("http://%s/", httpUrl)

    fmt.Printf("url: %s\n", getUrl)
    for i := 0; i < 5; i++ {
        _ , buf, err := httpGet(getUrl)
        if err != nil {
            fmt.Printf("err: %v\n", err)
            return
        {}
        fmt.Printf("resp: %s\n", string(buf))
        time.Sleep(10 * time.Second)    # Wait for 10s to initiate another request
    {}
{}

func httpGet(url string) (int, []byte, error) {
    client := createHTTPCli()
    resp, err := client.Get(url)
    if err != nil {
        return -1, nil, fmt.Errorf("%s err [%v]", url, err)
    {}
    defer resp.Body.Close()

    buf, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return resp.StatusCode, buf, err
    {}

    return resp.StatusCode, buf, nil
{}
func createHTTPCli() *http.Client {
    readWriteTimeout := time.Duration(30) * time.Second
    tr := &http.Transport{
        DisableKeepAlives: true,  // Set short connection
        IdleConnTimeout:   readWriteTimeout,
    {}
    client := &http.Client{
        Timeout:   readWriteTimeout,
        Transport: tr,
    {}
    return client
{}
Copy code

From the test results, net.http always goes to DNS queries and does not support DNS caching.

(2) fasthttp library

The fasthttp library is a high-performance HTTP library in the Go version, with optimal performance optimization, 10 times the performance of the standard library net.http, one of which is the support for DNS caching, which we can see from its source code

//Mainly in fasthttp/tcpdialer.go
type TCPDialer struct {
    ...
    // This may be used to override DNS resolving policy, like this:
    // var dialer = &fasthttp.TCPDialer{
    // 	Resolver: &net.Resolver{
    // 		PreferGo:     true,
    // 		StrictErrors: false,
    // 		Dial: func (ctx context.Context, network, address string) (net.Conn, error) {
    // 			d := net.Dialer{}
    // 			return d.DialContext(ctx, "udp", "8.8.8.8:53")
    // 		},
    // 	},
    // }
    Resolver Resolver

    // DNSCacheDuration may be used to override the default DNS cache duration (DefaultDNSCacheDuration)
    DNSCacheDuration time.Duration
    ...
{}
Copy code

This can refer to the following methods to use the fasthttp client end

func main() {
	// You may read the timeouts from some config
	readTimeout, _ := time.ParseDuration("500ms")
	writeTimeout, _ := time.ParseDuration("500ms")
	maxIdleConnDuration, _ := time.ParseDuration("1h")
	client = &fasthttp.Client{
		ReadTimeout:                   readTimeout,
		WriteTimeout:                  writeTimeout,
		MaxIdleConnDuration: maxIdleConnDuration,
		NoDefaultUserAgentHeader: true, // Don't send: User-Agent: fasthttp
		DisableHeaderNamesNormalizing: true, // If you set the case on your headers correctly you can enable this
		DisablePathNormalizing: true,
		// Increase DNS cache time to an hour instead of the default minute
		Dial: (&fasthttp.TCPDialer{
			Concurrency: 4096,
			DNSCacheDuration: time.Hour,
		}).Dial,
	{}
	sendGetRequest()
	sendPostRequest()
{}
Copy code

(3) Third-party DNS caching library

This is a Go version on github DNS Cache Library

You can refer to the following code for DNS caching support in the HTTP library

r := &dnscache.Resolver{}
t := &http.Transport{
    DialContext: func(ctx context.Context, network string, addr string) (conn net.Conn, err error) {
        host, port, err := net.SplitHostPort(addr)
        if err != nil {
            return nil, err
        {}
        ips, err := r.LookupHost(ctx, host)
        if err != nil {
            return nil, err
        {}
        for _, ip := range ips {
            var dialer net.Dialer
            conn, err = dialer.DialContext(ctx, network, net.JoinHostPort(ip, port))
            if err == nil {
                break
            {}
        {}
        return
    
{}
Copy code

Python

(1) requests library

#!/bin/python

import requests

url = 'http://example.my.com/'

num = 0
while num < 5:
    headers={"Connection":"close"}     # Open short connection
    r = requests.get(url, headers=headers)
    print(r.text)
    num +=1
Copy code

(2) httplib2 library

#!/usr/bin/env python
import httplib2
http = httplib2.Http()
url = 'http://example.my.com/'

num = 0
while num < 5:
    loginHeaders={
        'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.0 Chrome/30.0.1599.101 Safari/537.36',
        'Connection': 'close'  # Open short connection
    {}
    response, content = http.request(url, 'GET', headers=loginHeaders)
    print(response)
    print(content)
    num +=1
Copy code

(3) urllib2 library

#!/bin/python

import urllib2
import cookielib

httpHandler = urllib2.HTTPHandler(debuglevel=1)
httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
opener = urllib2.build_opener(httpHandler, httpsHandler)
urllib2.install_opener(opener)

loginHeaders={
    'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.0 Chrome/30.0.1599.101 Safari/537.36',
    'Connection': 'close' # Open short connection
{}

num = 0
while num < 5:
    request = urllib2.Request('http://example.my.com/', headers=loginHeaders)
    response = urllib2.urlopen(request)
    page = ''
    page = response.read()
    print response.info()
    print page
    num +=1
Copy code

All three libraries tested in Python support nscd's DNS caching (it is speculated that the underlying call is also getaddrinfo function), the above tests use HTTP short connections, and all are tested in python2 environment.

Summary

For HTTP clients, it is recommended to first enable the HTTP keep-alive mode, which can reuse TCP connections, thereby reducing TCP handshake time and repeated domain resolution requests, and then enable nscd caching. In addition to Go, C/C++, Java, and Python all support DNS caching, reducing DNS query time.

Here, we only analyze commonly used programming languages such as C/C++, Java, Go, and Python, and welcome other language experts to supplement.

2. Common DNS cache services for Unix/Linux systems:

In cases where due to certain special reasons, both self-developed and non-self-developed client software itself cannot provide DNS cache support, it is recommended that administrators deploy DNS cache programs in the system environment where they are located;

Here, we introduce several common lightweight DNS cache programs for Unix/Linux systems. While most desktop operating systems such as Windows, MacOS, and almost all web browsers have built-in DNS cache functions, this article will not elaborate on this.

P.S. Please ensure that the DNS cache service starts with the system boot;

nscd

Name service cache daemon, ready to use as soon as installed, usually installed by default on Linux systems, for related introductions, please refer to its manpage:man nscd;man nscd.conf

(1) Installation Method: Install through the system's built-in package management program, such asyum install nscd

(2) Cache Management (Clear):

1.service nscd restartRestart the service to clear all caches;

2.nscd -i hostsClear the domain cache in the hosts table (hosts is the table name used for domain cache, nscd has multiple cache tables, please refer to the program's related manpage)

dnsmasq

It is relatively lightweight and can be chosen as a replacement for nscd, usually requiring separate installation

(1) Installation Method: Install through the system's built-in package management program, such asyum install dnsmasq

(2) Core File Introduction (based on Dnsmasq version 2.86, there may be some differences in lower versions, please refer to the corresponding documentation such as manpage)

(3) /etc/default/dnsmasq provides six variables for defining six types of control functions

(4) /etc/dnsmasq.d/ This directory contains a README file, which can be referred to; custom configuration files can be stored in the directory

(5) /etc/dnsmasq.conf main configuration file, if dnsmasq is only configured as a caching program, refer to the following configuration

listen-address=127.0.0.1                #Program listening address, must specify the local network or loopback address of this machine, to avoid exposure to the public network environment
port=53                                 #Listening port
resolv-file=/etc/dnsmasq.d/resolv.conf  #Configure dnsmasq to forward dns resolution requests to the custom file
cache-size=150                          #Number of cache records, default 150, can be adjusted as needed and appropriately increased
no-negcache                             #Do not cache resolution failure records, mainly NXDOMAIN, that is, the domain does not exist
log-queries=extra                       #Enable logging, specify "=extra" to record more detailed information, which can only be enabled during problem troubleshooting and normally turned off
log-facility=/var/log/dnsmasq.log       #Specify log file

#At the same time, the first nameserver in the /etc/resolv.conf of this machine must be set to the above listening address, so that the dns query requests of this machine's system will be forwarded and cached by dnsmasq
#Additionally, /etc/resolv.conf must be configured with 2 nameservers to support system automatic retry in case of dnsmasq service anomaly, note that resolv.conf only reads the first 3 nameservers
Copy code

(6) Cache management (clear):

1.kill -s HUP `pidof dnsmasq`recommended method, no need to restart the service

2.kill -s TERM `pidof dnsmasq`orservice dnsmasq stop

3.service dnsmasq force-reloadorservice dnsmasq restart

(7) Official documentation:thekelleys.org.uk/dnsmasq/doc…

3. Cancel the request for querying the AAAA record of the domain name for pure internal network business

Taking the Linux operating system as an example, commonly used network request command-line tools often complete the domain resolution process by calling getaddrinfo(), such as ping, telnet, curl, wget, etc., but for the consideration of versatility, they are all designed to initiate two requests for each resolution of the same domain name, respectively querying the domain name A record (i.e., IPV4 address) and AAAA record (i.e., IPV6 address).

As most companies' internal network environments and cloud-based internal network environments have not yet used ipv6 networks, the DNS system usually does not add AAAA records for internal network domain names, and the futile request for the AAAA record of the domain name will cause unnecessary resource consumption for front-end applications and backend DNS services. Therefore, for businesses that only need to request internal network domain names, such as deciding to develop a client independently, it is recommended that developers design it to only request the A record of the internal network domain name according to the actual situation, especially when it is not possible to implement a local caching mechanism due to certain reasons.

4. Standardize the domain name processing logic

The client needs to strictly standardize the processing logic of domain names/hostname to avoid generating a large number of resolution requests for non-existent domains (ensure that the domain is obtained from authoritative channels, avoid intentionally or inadvertently using randomly generated domain names, or hostnames), therefore, the return results (NXDOMAIN) of such requests are usually not cached or have a short caching time, and will trigger the client to retry, which has a certain impact on the backend DNS system.


你可能想看:
最后修改时间:
admin
上一篇 2025年03月25日 13:41
下一篇 2025年03月25日 14:04

评论已关闭