mopduan/team

一次 Node.js 服务线上问题引出的 DNS 缓存方案研究与思考

Opened this issue · 0 comments

问题背景

某天上午,运营同学突然在群里反馈很多用户来报登录问题。起初以为是内网接口服务异常了,但接口反馈没有产生异常的日志,也就是说异常请求还没打过去。于是我们登录服务器,筛选了下Node.js服务的日志:

image.png

通过日志,我们可以很直观的看出问题所在:DNS解析失败

整理思路

作为一个日均流量过千万的Node.js服务,每个请求都需要解析N个内网接口域名

平时还好,如果DNS服务出现了问题,或者网络抖动,很容易在Node.js服务与内网接口服务都正常的情况下,导致线上业务不可用

针对这种情况,我们需要在Node.js服务端对DNS解析做一层缓存

首先我们需要明确一点:!!!Node.js本身不做DNS查询结果的缓存!!!

默认DNS查询方案

我们先来了解一下默认的DNS查询方案:

Node.js内置的http模块的http.request()请求时,会使用dns.lookup()进行查找

  • 方法调用链条是 http.request() -> net.createConnection() -> dns.lookup()
function lookupAndConnect(self, options) {
  // ...
  const lookup = options.lookup || dns.lookup;
  defaultTriggerAsyncIdScope(self[async_id_symbol], function() {
    lookup(host, dnsopts, function emitLookup(err, ip, addressType) {
      self.emit('lookup', err, ip, addressType, host);
      // ...
    });
  });
}

通过这段代码我们可以看出,options.lookup参数可以自行设置,可以传入dns.resolve或者自定义的符合要求的方法

getaddrinfo 函数

dns.lookup()方法调用到最终,调用的是底层的getaddrinfo()函数(也就是上文报错点)

在C/C++代码中getaddrinfo函数是同步调用,所以需要libuv通过线程池来实现Node.js的异步I/O

注:查阅相关资料,我们可以看到线程池默认大小是4

可以通过UV_THREADPOOL_SIZE环境变量设置。Node.js v14中最大为1024

可能会出现的问题

当请求在DNS查询阶段耗时过长时,由于默认线程池过小,服务处理请求的速度跟请求数量远远不匹配,服务运行时间越长积压的请求数连接数就越多

关于默认缓存

  • !!!Node.js本身不做DNS查询结果的缓存!!!,Node.js每次域名请求时都会请求DNS Server

  • 使用DNS缓存注意缓存的过期时间

实现DNS缓存的相关依赖

lookup-dns-cache

lookup-dns-cache是很成熟的DNS缓存库,但比较古老

image.png

他的思路比较简单:

  1. 底层查询使用了 dns.resolve()来替换dns.lookup
  2. 通过一个Map缓存已经解析出来的hostname信息
  3. 避免并行的DNS请求。同一时间只执行一个对相同hostname的查询请求,通过Map来实现

dns.resolvedns.lookup 区别

通过官方文档可以看出

image.png

  1. dns.resolve不使用getaddrinfo()
  2. dns.resolve是异步实现的
  3. dns.resolve不解析本地hosts文件,直接走网络解析

详情可以查看:https://nodejs.org/dist/latest-v14.x/docs/api/dns.html#dns_dns_resolve_dns_resolve_and_dns_reverse

示例代码
const { resolve, lookup } = require('dns');

lookup('preview4.xx.xx.com', (err, address, family) => {
    console.log('地址: %j 地址族: IPv%s', address, family); // 地址: "xxx.xxx.xx.xx" 地址族: IPv4
});

resolve('preview4.xx.xx.com', (err, records) => {
    console.log(records); // undefined
});

preview4.xx.xx.com 是本地host配置的域名

由于dns.resolve()不使用getaddrinfo(),所以此时解析出来的地址为undefined

避免并行请求实现

利用Map对正在查询的hostname做缓存。查询结束后从Map中删除

let task = this._tasksManager.find(key);

if (task) {
  task.addResolvedCallback(callback);
} else {
  task = new ResolveTask(hostname, ipVersion);
  this._tasksManager.add(key, task);
  task.on('addresses', addresses => {
    this._addressCache.set(key, addresses);
  });
  task.on('done', () => {
    this._tasksManager.done(key);
  });
  task.addResolvedCallback(callback);
  task.run();
}

基于ttl的缓存

  1. 通过dns.reslove方法设置ttl:true让DNS查询结果返回ttl值
  2. 判断hostname还在缓存且未过期时直接返回缓存,否则进行查询
/**
 * @param {string} key
 * @returns {Address[]|undefined}
 */
find(key) {
    if (!this._cache.has(key)) {
        return;
    }

    const addresses = this._cache.get(key);

    if (this._isExpired(addresses)) {
        return;
    }

    return addresses;
}

cacheable-lookup

在实际使用中,发现了 dns.resolve()无法解析本地hosts配置 的域名,单纯使用lookup-dns-cache会导致本地开发环境出现报错。

经过调研,发现了cacheable-lookup这个库,作者是got的作者szmarczak。

image.png

通过提交记录我们可以看出,作者还在保持的对库的持续更新。

对比 lookup-dns-cache

async queryAndCache(hostname) {
	if (this._hostnamesToFallback.has(hostname)) {
		return this._dnsLookup(hostname, all);
	}

	let query = await this._resolve(hostname);

	if (query.entries.length === 0 && this._dnsLookup) {
		query = await this._lookup(hostname);

		if (query.entries.length !== 0 && this.fallbackDuration > 0) {
			// Use `dns.lookup(...)` for that particular hostname
			this._hostnamesToFallback.add(hostname);
		}
	}

	const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl;
	await this._set(hostname, query.entries, cacheTtl);

	return query.entries;
}

通过源码我们可以看出,当resolve方法没有解析成功时,会使用lookup方法进行兜底,更符合我们本地开发环境更改hosts文件的场景

同时,这个库也提供了基于ttl的缓存阻止并行请求等功能点

于是,我们可以解决我们的问题了!

解决方案

在内网接口调用处统一增加cacheable-lookup进行DNS解析的缓存