Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Resolve DNS with exponential backoff
# vim: ai:ts=8:sw=8:noet
# set -eufo pipefail
export SHELLOPTS # propagate set to children by default
# Performs a DNS resolution and waits until the answer has a non-empty response
function resolve_dns_with_backoff {
local timeout=${DNS_RESOLUTION_TIMEOUT-5}
local domain=${1}
local attempt=0
local backoff=1
local now
local end
now=$(date +%s)
end=$((now + timeout))
while [[ ${now} < ${end} ]]
response=$(dig +short "${domain}")
if [ -n "${response}" ]; then
echo "DNS Response is ${response}"
return 0
echo "Attempt $attempt - DNS Response was empty! Retrying in $backoff seconds.." 1>&2
sleep "${backoff}"
attempt=$(( attempt + 1 ))
backoff=$(( backoff * 2 ))
now=$(date +%s)
return 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment