TExcelTAD
Home › System Design › DNS and Proxies

DNS and Proxies

Before a request reaches any of your servers, two kinds of middlemen handle it: the Domain Name System turns a name like shop.example.com into an IP address, and proxies sit between clients and servers to route, cache, filter or secure traffic. Both are simple ideas that large systems lean on heavily.

How DNS resolution works

DNS is a distributed, hierarchical, heavily cached database. A lookup that isn't cached walks down the hierarchy:

text
browser -> OS stub resolver -> recursive resolver (ISP / 1.1.1.1 / 8.8.8.8)
                                   |  1. "who handles .com?"        -> root server
                                   |  2. "who handles example.com?"  -> .com TLD server
                                   |  3. "A record for shop...?"     -> example.com's authoritative server
                                   v
                              93.184.216.34  (cached for the record's TTL)

Each answer has a TTL (time to live). Resolvers cache it for that long, so most lookups never leave the resolver. Let's model a resolver with a cache and a simulated clock:

python · try it yourself
ZONES = {
    ".":            {"com.": "ns.tld-com"},
    "com.":         {"example.com.": "ns1.example"},
    "example.com.": {"shop.example.com.": ("203.0.113.10", 300)},   # (ip, ttl seconds)
}

class Resolver:
    def __init__(self):
        self.cache = {}          # name -> (ip, expires_at)
        self.queries_sent = 0

    def resolve(self, name, now):
        cached = self.cache.get(name)
        if cached and cached[1] > now:
            return cached[0], "cache"
        self.queries_sent += 3                      # root, TLD, authoritative
        ip, ttl = ZONES["example.com."][name]
        self.cache[name] = (ip, now + ttl)
        return ip, "3 upstream queries"

r = Resolver()
for t in [0, 10, 200, 299, 300, 450]:
    ip, how = r.resolve("shop.example.com.", now=t)
    print(f"t={t:3}s {ip} via {how}")
print("total upstream queries:", r.queries_sent)
t=  0s 203.0.113.10 via 3 upstream queries
t= 10s 203.0.113.10 via cache
t=200s 203.0.113.10 via cache
t=299s 203.0.113.10 via cache
t=300s 203.0.113.10 via 3 upstream queries
t=450s 203.0.113.10 via cache
total upstream queries: 6

DNS as a design tool

Record / technique What it does Design use
A / AAAA Name → IPv4 / IPv6 address Point a name at a load balancer
CNAME Name → another name www → shop.cdn-provider.net
Multiple A records Resolver returns several IPs (round robin) Crude load spreading
GeoDNS / latency-based Answer depends on the client's location Send users to the nearest region
Health-checked records Unhealthy IPs are removed from answers Regional failover
Low TTL Clients re-resolve sooner Faster failover, more DNS traffic

TTL is a trade-off: a 1-day TTL means a failover can take a day to reach everyone; a 30-second TTL makes failover fast but multiplies queries. Many teams lower TTLs before a planned migration and raise them again afterwards.

python · try it yourself
clients = 1_000_000          # clients that each make 1 request per minute for a day
for ttl in [30, 300, 3_600, 86_400]:
    lookups_per_client = max(1, 86_400 // max(ttl, 60))     # at most one per minute
    worst_failover = ttl
    print(f"TTL {ttl:6}s: ~{clients * lookups_per_client:>13,} lookups/day, failover up to {worst_failover / 60:6.1f} min")
TTL     30s: ~1,440,000,000 lookups/day, failover up to    0.5 min
TTL    300s: ~  288,000,000 lookups/day, failover up to    5.0 min
TTL   3600s: ~   24,000,000 lookups/day, failover up to   60.0 min
TTL  86400s: ~    1,000,000 lookups/day, failover up to 1440.0 min

Forward and reverse proxies

A proxy is a server that forwards traffic on someone's behalf. The direction makes all the difference:

text
Forward proxy (acts for clients)          Reverse proxy (acts for servers)

client -+                                             +-> app server 1
client -+-> [proxy] ---> internet         internet -> [proxy] -+-> app server 2
client -+                                             +-> app server 3
Forward proxy Reverse proxy
Who configures it Clients / their company The service owner
Hides The clients from servers The servers from clients
Typical uses Corporate egress filtering, caching, anonymity TLS termination, load balancing, caching, compression, rate limiting, WAF
Examples Squid, corporate proxies Nginx, HAProxy, Envoy, cloud load balancers

A reverse proxy is the front door of almost every web system. Because every request passes through it, it's the natural place for cross-cutting concerns. The model below chains three of them: TLS termination, a path-based router and a small response cache.

python · try it yourself
def backend_products(path):
    return f"product page for {path.split('/')[-1]}"

def backend_static(path):
    return f"<file {path}>"

ROUTES = [("/static/", backend_static), ("/products/", backend_products)]
cache, stats = {}, {"hits": 0, "misses": 0}

def reverse_proxy(request):
    scheme, path = request.split("://", 1)[0], "/" + request.split("/", 3)[3]
    if scheme != "https":
        return "301 redirect to https"
    if path in cache:
        stats["hits"] += 1
        return cache[path] + "  [from proxy cache]"
    for prefix, backend in ROUTES:
        if path.startswith(prefix):
            stats["misses"] += 1
            response = backend(path)          # plain HTTP inside the private network
            if prefix == "/static/":
                cache[path] = response        # only static files are cacheable here
            return response
    return "404 not found"

for req in ["http://shop.example/products/42",
            "https://shop.example/products/42",
            "https://shop.example/static/app.js",
            "https://shop.example/static/app.js",
            "https://shop.example/admin"]:
    print(f"{req:<36} -> {reverse_proxy(req)}")
print(stats)
http://shop.example/products/42      -> 301 redirect to https
https://shop.example/products/42     -> product page for 42
https://shop.example/static/app.js   -> <file /static/app.js>
https://shop.example/static/app.js   -> <file /static/app.js>  [from proxy cache]
https://shop.example/admin           -> 404 not found
{'hits': 1, 'misses': 2}

Tip: The reverse proxy is itself a single point of failure unless you run at least two, usually as an active/passive pair sharing a virtual IP, or behind a cloud load balancer that is redundant by design.

Common mistakes

  • Forgetting that DNS is cached. Changing a record doesn't change what clients already resolved; plan for the old TTL.
  • Using DNS round robin as a load balancer. Clients cache one IP and ignore health; use a real load balancer behind the name.
  • Trusting X-Forwarded-For blindly. Only the proxy you control should set it; clients can forge it.

Test yourself

What does a DNS record's TTL control?

  1. How long the server keeps a TCP connection open
  2. How long resolvers may cache the answer
  3. The maximum number of lookups per second
  4. How long a domain registration lasts

Which is a typical job of a reverse proxy?

  1. Hiding employees' browsing from websites
  2. TLS termination and routing requests to backend servers
  3. Resolving domain names
  4. Storing database backups

In the resolver model, why did the lookup at t=300 go upstream again?

  1. The cache was full
  2. The 300-second TTL had expired
  3. The IP address changed
  4. Upstream servers require a lookup every 300 queries