dns
module, and the node:dns
module.
DNS caching in Bun
In Bun v1.1.9, we added support for DNS caching. This cache makes repeated connections to the same hosts faster. At the time of writing, we cache up to 255 entries for a maximum of 30 seconds (each). If any connections to a host fail, we remove the entry from the cache. When multiple connections are made to the same host simultaneously, DNS lookups are deduplicated to avoid making multiple requests for the same host. This cache is automatically used by:bun install
fetch()
node:http
(client)Bun.connect
node:net
node:tls
When should I prefetch a DNS entry?
Web browsers expose<link rel="dns-prefetch">
to allow developers to prefetch DNS entries. This is useful when you know you’ll need to connect to a host in the near future and want to avoid the initial DNS lookup.
In Bun, you can use the dns.prefetch
API to achieve the same effect.
dns.prefetch
This API is experimental and may change in the future.
dns.prefetch
API. This API is useful when you know you’ll need to connect to a host soon and want to avoid the initial DNS lookup.
dns.getCacheStats()
This API is experimental and may change in the future.
dns.getCacheStats
API. This API returns an object with the following properties:
Configuring DNS cache TTL
Bun defaults to 30 seconds for the TTL of DNS cache entries. To change this, you can set the environment variable$BUN_CONFIG_DNS_TIME_TO_LIVE_SECONDS
. For example, to set the TTL to 5 seconds:
Why is 30 seconds the default?
Unfortunately, the system API underneath (getaddrinfo
) does not provide a way to get the TTL of a DNS entry. This means we have to pick a number arbitrarily. We chose 30 seconds because it’s long enough to see the benefits of caching, and short enough to be unlikely to cause issues if a DNS entry changes. Amazon Web Services recommends 5 seconds for the Java Virtual Machine, however the JVM defaults to cache indefinitely.