Belajar
← All lessons

How DNS works

Follow one lookup

Browser
Resolver
Root
.com
Name server

device.js

// your device asks one resolver, like 1.1.1.1const answer = await query("1.1.1.1", { name, type: "A" }); // then it connects to the address it got backconst socket = connect(answer.address, 443);

resolver.js

// the resolver, with nothing in its cacheasync function resolve(name) {  let reply = await ask("a.root-servers.net", name);  // root: "I don't know, ask the .com servers"  reply = await ask(reply.referral, name);  // .com: "ask the domain's own name server"  reply = await ask(reply.referral, name);  cache.set(name, reply.answer, reply.ttl);  return reply.answer;}

One name, many records each type answers a different question

NameTypeAAAAACNAMEMX

Answer

shop.com.zone

$ORIGIN shop.com.@      300   IN  A      203.0.113.7@      300   IN  AAAA   2001:db8::7@      3600  IN  MX     10 mail.shop.com.www    300   IN  CNAME  shop.com.mail   300   IN  A      203.0.113.25api    60    IN  A      203.0.113.40api    60    IN  A      203.0.113.41

nameserver.js

function lookup(name, type) {  const rows = zone.filter((r) => r.name === name);  const hits = rows.filter((r) => r.type === type);  if (hits.length) return hits;  const alias = rows.find((r) => r.type === "CNAME");  if (alias) return [alias, ...lookup(alias.value, type)];  if (rows.length) return [];  // the name exists, not the type  throw new Error("NXDOMAIN"); // no such name}

The cache skips it all for as long as the TTL says

Browser
Resolver
Name servers

resolver.js

async function lookup(name) {  const hit = cache.get(name);  if (hit && Date.now() < hit.expires) {    return hit.address;  }  cache.delete(name);  const { address, ttl } = await walkFromRoot(name);  cache.set(name, { address, expires: Date.now() + ttl * 1000 });  return address;}

Pick a TTL and live with stale answers

TTL on the record1 min5 min1 hour
Clock0:00
name server
cache

A long TTL means fewer lookups, but a move takes that long to reach everyone

dns.js

// at your DNS hostsetRecord("shop.com", "A", "203.0.113.7", { ttl }); // later: move the site to a new serversetRecord("shop.com", "A", "198.51.100.20", { ttl }); // every resolver that cached the old answerif (Date.now() < cached.expires) return cached.address;return (await walkFromRoot("shop.com")).address;

Topics

Next: How TCP delivers data

Open lesson