Day 1 A-Foundations 2026-09-29 ← All lessons

From one server to a website: DNS, web tier, database

Every large system starts as one machine running everything. This lesson follows a single request all the way through, then makes the first structural change that every later lesson builds on: pulling the database out of the web server.

1 lookupDNS resolves once per TTL, then every request skips it (§2)
24 TBRAM in the largest single RDS instance — the ceiling you eventually hit (§3)
10M/moStack Overflow's monthly visitors on one master database in 2013 (§3)
2 tiersWeb and data. The split that makes every later lesson possible (§4)

Key points

Outcomes

01Trace one request from keystroke to rendered response, naming every actor and saying which ones are in the data path.
02Explain what DNS actually does, where the answer is cached, and why a DNS change takes time to take effect.
03Argue from statelessness why the web tier scales by cloning and the data tier does not.
04Choose relational or non-relational by naming the property you are trading away.
01

One request, end to end


You type api.mysite.com/users/42 and press enter. Four parties are involved, and only three of them handle your actual data:

How to read: Time runs downward. Each vertical line is one party. Dashed arrows are the name lookup; solid arrows carry your data. Note that after step 2, the resolver's line goes quiet — nothing else in this request touches it.

resolve every request browser DNS resolver web server database 1what IP is api.mysite.com? 215.125.23.214 cached by the browser, the OS and the resolver for the record's TTL 3GET /users/42 → 15.125.23.214 straight to the IP — the resolver is not in this path 4SELECT … id=42 51 row 6200 OK — HTML page or JSON body browser renders HTML; a mobile app parses JSON
Steps 1–2 happen once and the answer is reused. Steps 3–6 happen on every single request. Keeping those two phases separate in your head is most of what DNS confusion is.
The misconception this kills Diagrams often draw user → DNS → server in one chain, which makes DNS look like a router your traffic flows through. It is not. DNS is a question you ask before you dial, like looking up a phone number. Your call does not go through the phone book.
HTML or JSON? Same server, same request, different Accept header and usually a different route. A browser hitting /users/42 wants a rendered page; a mobile app hitting /api/v1/users/42 wants raw JSON it will draw itself. Nothing about the infrastructure changes — only the shape of the response body.
02

Inside the lookup: where the answer actually comes from


“DNS resolves the name to an IP” is a restatement, not an explanation. Here is the machinery, because one practical consequence of it will bite you in your first month.

A name is resolved by walking a chain of caches, and the walk stops at the first stop that already knows the answer. Only a genuine miss travels the whole way to the authoritative name server.

How to read: Left to right is the search order. Walk it one hop at a time — and notice how far you normally don't have to go.

cached — most lookups stop here walked only on a cold miss browsercache OScache ISP resolvercache root“ask .com” .com TLD“ask mysite” authoritativeyou own this A record: api.mysite.com → 15.125.23.214  ·  TTL 300 Every stop on the way back keeps a copy for TTL seconds. That is why a DNS change is slow to take effect — old answers are still alive in caches you do not control.
The chain is walked once. For the next TTL seconds every client behind the same resolver gets the cached answer without any of these servers being contacted.

Two things worth carrying out of this diagram. First, DNS is cheap because it is cached, which is why nobody worries about it being on the hot path — it mostly is not. Second, TTL is a promise you cannot take back. If you publish a record with a one-hour TTL and then need to move traffic, resolvers around the world will keep handing out the old IP for up to an hour. The standard fix is to lower the TTL days before a planned migration.

See it yourselfshell
# 1. The lookup. +short prints just the answer.
$ dig api.mysite.com +short
15.125.23.214

# 2. The TTL, in seconds. This is the number that controls propagation.
$ dig api.mysite.com | grep -A1 'ANSWER SECTION'
;; ANSWER SECTION:
api.mysite.com.   300   IN   A   15.125.23.214

# 3. Now skip DNS entirely and talk to the IP. Same response.
#    Proof that the resolver is not in the data path.
$ curl -i -H 'Host: api.mysite.com' http://15.125.23.214/users/42
HTTP/1.1 200 OK
Content-Type: application/json

{"id":42,"name":"Ada"}

Steering: three ways to send a user somewhere nearby

MechanismHow it steersWhat it cannot do
GeoDNSThe authoritative server returns a different IP depending on where the query came from.It sees the resolver's location, not the user's. Someone in Lagos using 8.8.8.8 may be steered to wherever Google's resolver appeared to be. And failover is bounded by TTL.
AnycastThe same IP is announced from many locations via BGP; the network delivers you to the topologically nearest one. No DNS involvement at all.You do not choose the destination — the internet's routing does, and it optimises for AS-path length rather than latency. A BGP change can also move an in-flight connection to a different site.
Unicast + GSLBA global load balancer with health checks picks the IP to hand back, using real latency and capacity data.Still delivered through DNS, so it inherits every caching problem above.
Gotcha — DNS failover is slower than its TTL The honest version of the TTL story: a 60-second TTL does not mean 60-second failover. Some resolvers clamp very low TTLs upward because honouring them is expensive. Browsers and JVMs keep their own caches with their own rules. And a client that has already opened a connection will not re-resolve at all until that connection breaks. In practice, planned DNS cutovers take tens of minutes to fully drain, so DNS is for planned moves and coarse regional steering, not for fast failover. Fast failover lives at a layer that does not involve names: anycast withdrawal, or a load balancer taking a backend out of rotation in seconds.
One practical detail interviewers like At the apex of a domain (example.com, no subdomain) the DNS spec will not let you use a CNAME, because the apex must also carry NS and SOA records. But cloud load balancers give you a hostname, not a stable IP. Providers resolve this with a non-standard ALIAS / ANAME record that behaves like a CNAME but returns an A record at query time. Knowing this is the difference between having configured DNS and having read about it.
Interview tip DNS is a managed service you buy (Route 53, Cloudflare, NS1), not something you run on your own boxes. Saying so signals you know where your system's boundary is. The follow-up is usually “how would you fail over to another region?” — and the answer involves that TTL.
03

One box, and the two things it cannot do


Start with everything on one machine: the web server process and the database process, same CPU, same disk. This is not a strawman. It is the correct design for a new product, and it survives much longer than people expect — Stack Overflow served 10 million monthly unique visitors in 2013 with a single master database. Do not split anything until you can say what is forcing you to.

Two things eventually force you to, and they are different problems:

Problem 1

There is a ceiling

  • You can keep buying a bigger box — this is vertical scaling — and it works for a long time.
  • But the ceiling is real: the largest single Amazon RDS instance tops out around 24 TB of RAM. There is no next size up.
  • Cost rises much faster than capacity on the way to that ceiling.
Problem 2

There is no second copy

  • One machine means one thing to lose. A kernel panic, a full disk, or a routine deploy takes the entire site down.
  • The database competing with the web server for RAM also means a traffic spike can starve your queries, and a slow query can stall your HTTP handlers.
  • You cannot fix this by buying a bigger box. It is a structural problem, not a capacity one.

The first move is not “add servers.” It is separate the two roles so they stop competing, and so each can be scaled by the method that actually works for it. Here is that move in three stages:

How to read: The same picture, evolving. Step through it. Row 2 is this lesson's change. Row 3 is what the change unlocks, and is Day 2's subject — it is drawn here only so you can see why row 2 matters.

1 — one box you web server database Simple, cheap, correct to start with. One failure takes down everything. 2 — split the tiers  ← this lesson you web tierholds no state data tierholds all state Each now gets the RAM, CPU and disk it needs, and each is scaled by a different method. 3 — clone the web tier  (Day 2) you loadbalancer web 1 web 2 data tier Still one database. Only the easy half got cloned.
A load balancer appears in row 3 because once you have more than one web server, something has to decide which one gets each request. Day 2 is about that box.
04

Why the split lets you scale: state is the whole answer


“Separating the tiers lets you scale them independently” is the sentence everyone repeats. It is worth knowing why it is true, because the reason is also the reason the two halves need completely different tools.

A web server, written correctly, is stateless: it remembers nothing between requests. Every request carries its own token or session ID, and anything the server needs it fetches from the data tier. A database is the opposite — being the thing that remembers is its entire job.

How to read: Two tiers, two very different answers to the question “what happens when I add one more box?”

web tier — holds nothing web 1 web 2 web 3 shared storesessions, data Every box runs identical code and knows nothing. Add a fourth: it works immediately. Kill one: no data lost. data tier — holds everything primary copy of the data? slice of the data? replication sharding Add a box and you must first answer: which data goes on it?
Cloning a stateless box is free. Cloning a stateful one requires a policy — which is why Days 2, 6 and 7 are all, in one way or another, about the right-hand side of this picture.

So the split buys you this: the half of your system that is easy to scale is now allowed to scale, instead of being welded to the half that is hard. You can add web servers this afternoon. You will spend the rest of this course on the other side.

Gotcha A web server is only stateless if you keep it that way. The moment you store a user's session in local process memory or write an uploaded file to the local disk, that box has become special — requests from that user must now return to it. Day 2 covers the cost of that mistake (sticky sessions) and the fix.
05

Which database: a decision, not a feature list


You now have a data tier. What goes in it? The honest default is a relational database, and the reason is not that they are old — it is that they give you a set of guarantees you would otherwise have to build yourself. The useful question is which of those guarantees you are willing to give up.

Decision axisRelational (SQL)Non-relational (NoSQL)
Combining recordsJOIN across tables, in the database, at query timeGenerally no joins. You denormalize up front, or join in application code
Changing the shape of dataA migration. Enforced for every row, and sometimes locks the tableWrite a new field today. Nothing stops you — and nothing cleans up the old rows either
How it scalesVertically first, then read replicas, then sharding (which you implement)Horizontally by design. Adding nodes is the normal operation
ConsistencyTransactions. A write either fully happens or does notOften eventual: a read right after a write may return the old value
Ad-hoc questionsAny query you can express in SQL, including ones you did not plan forFast only for the access pattern you designed the keys around
ExamplesPostgreSQL, MySQL, OracleDynamoDB, Cassandra, MongoDB, Neo4j

Read the rows as trades, not as scores. Nothing in the right-hand column is a defect — each one is a guarantee deliberately dropped to buy scale or flexibility.

“NoSQL” is four different things

Lumping these together is why the category is confusing. They are not variants of each other; they solve different problems.

FamilyShapeGood atExample
Key-valueOne key → one blobFetching a known item in under a millisecond. Sessions, carts, cachesRedis, DynamoDB
DocumentKey → nested JSONRecords whose fields differ from row to row; product catalogsMongoDB, CouchDB
Wide-columnRow key → many sparse columnsHuge write volume and range scans by key. Time series, event logsCassandra, HBase
GraphNodes and edgesQueries about relationships: “friends of friends who like X”Neo4j
What to say out loud “I'd start relational, because the access patterns aren't settled yet and I want joins and transactions while the schema is still moving. I'd move a specific workload to a key-value store when I can point at it — session lookup, say — and show that it's a single-key read that doesn't need any of what the relational database is charging me for.”
Gotcha “NoSQL scales better” is not a reason by itself. A single Postgres instance comfortably handles workloads most products never reach, and picking a distributed store early means paying for eventual consistency, no joins and harder debugging before you have the scale that would justify any of it.
Q&A

Check yourself


These are the shapes real interviewers use: a symptom you have to diagnose, or a decision you have to defend. Work out your answer before expanding.

Q1The classic opener: “what happens when you type google.com and press enter?” You get three sentences in before the interviewer stops you and asks: “wait — does the HTTP request go through the DNS server?” What is the right answer, and why are they asking?
  • Yes — DNS forwards the request to the right server
  • No — DNS is a lookup that completes first; the browser then connects directly to the returned IP
  • Only for the first request
✓ No. DNS resolves, then gets out of the way. The lookup is a separate request/response that finishes before the HTTP connection is opened; after that, DNS is not in the data path at all. They are asking because it is the cleanest single test of whether you have a mental model or a memorised list. Candidates who recite “DNS → server → database” as a chain reveal they have never thought about where the packets actually go — and it matters downstream, because it is why DNS latency is a one-off cost, why DNS-based failover is slow, and why you cannot use DNS to load-balance individual requests.
Q2You must move your service to a new IP with no downtime. Walk through the plan. What is the step most people miss, and what breaks without it?
  • Update the A record, then shut down the old server once traffic stops
  • Lower the TTL days in advance, then switch, then keep the old server running for at least the old TTL
  • Use a load balancer so DNS never changes
✓ Lower the TTL first — days before the change. The missed step is that a TTL change is itself subject to the old TTL. If your record has a 24-hour TTL and you drop it to 60 seconds this morning, resolvers holding the old record will not notice for up to 24 hours. So the sequence is: lower the TTL, wait out the old TTL, then switch the record, then keep the old server alive for at least the new TTL before decommissioning. Without it you drop traffic from every client whose resolver is still handing out the old address. The better architectural answer the interviewer is fishing for: put a load balancer in front so the public IP never changes, and DNS is only involved in region-level failover — where this same TTL arithmetic applies, which is why DNS failover takes minutes and not seconds.
Q3Your API p99 latency has tripled. You have one web server and one database on separate machines. Describe how you would determine which tier is at fault, before changing anything.
  • Restart both services and see if it recovers
  • Compare time spent in the handler against time spent waiting on queries — then check the resource that is saturated on each box
  • Add a cache; it will help either way
✓ Split the latency, then find the saturated resource. The useful decomposition is: total request time = application compute + time blocked on the database + network. Instrument the query call sites (or read your APM's breakdown) and the answer usually falls out immediately. Then confirm with the resource: web-tier CPU near 100% points at compute; database CPU or disk I/O saturated with normal web CPU points at queries; both idle while latency is high points at lock contention, connection-pool exhaustion or an external dependency. The reason this is a Day 1 question: separating the tiers is what made this diagnosis possible at all — on one shared box you cannot tell whose CPU you are looking at. “Add a cache” before knowing the answer is how you spend a sprint speeding up the thing that was never slow.
Q4“Design a system to store user sessions.” You suggest Redis. The interviewer asks: “why not just keep them in the web server's memory? It's faster and it's free.” Give the strongest version of their argument, then your answer.
  • They are right — in-process memory is the correct choice
  • Their argument is real for a single box; it fails because it welds every user to one machine, which blocks horizontal scaling, deploys and autoscaling
  • Redis is faster than local memory
✓ Concede the speed, then name what it costs. Their case is genuinely good: a local hash map is a nanosecond lookup with no network hop, no serialisation and no extra service to operate — on one server it is strictly better, and pretending otherwise is a bad answer. Your case: it makes that server special. Every subsequent request from that user must return to it, so you need sticky sessions; a deploy or a crash logs those users out; the load balancer can no longer balance; and autoscaling becomes destructive. You are trading a few hundred microseconds per request for the ability to treat web servers as disposable — which is the single property that makes everything in Day 2 possible. Interviewers ask this specifically to see whether you can argue against your own recommendation before defending it.
Q5You are designing a product catalogue. Different product categories have wildly different attributes — a laptop has RAM and a screen size, a shirt has a size and a colour. A colleague says “this is obviously a document store.” What would you want to know before agreeing?
  • Nothing — variable attributes is the textbook document-store case
  • What the query patterns are: faceted search and cross-product reporting are joins, and a flexible write schema says nothing about them
  • Whether the team already knows MongoDB
✓ Ask what questions the data has to answer. “Variable attributes” describes the write shape, and that is the weaker half of the decision. The things that actually decide it: (a) do you need faceted filtering (“laptops, 16 GB+, under £1000, in stock”)? That is a multi-attribute query that document stores handle awkwardly and a search index like Elasticsearch handles well — so the real answer may be neither of the two you were offered. (b) Does anything need to join products to orders, inventory or pricing? (c) Does a price or stock update need to be transactional? A very common production answer is relational as the system of record, with a denormalised document pushed into a search index for the catalogue page — getting the transactional guarantees and the query flexibility, at the cost of keeping two stores in sync. The signal being tested is whether you pick a database from the data's shape or from the workload's shape.
In practiceWhat production adds, and the questions that come next optional

This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.

DNS and anycast

  • How BGP announcements make anycast work, and what a route leak or withdrawal does to it
  • When you need CNAME vs. A/AAAA vs. ALIAS at the apex, and health-checked routing policies

RDBMS internals

  • Write path: WAL, checkpointing, fsync, and why vacuum/compaction exists
  • Composite index column order and why the leftmost-prefix rule decides usability

NoSQL taxonomy

  • Secondary indexes in distributed stores: local vs. global, and the consistency caveat of each

Terms used

A record
The DNS record type that maps a hostname to an IPv4 address.
TTL
Time to live, in seconds. How long a cached DNS answer may be reused before it must be looked up again.
Resolver
The DNS server that does the lookup legwork for you, and caches the result. Usually your ISP's, or a public one like 1.1.1.1.
Authoritative NS
The name server holding the real records for a domain. Edits you make in a DNS control panel land here.
Tier
A role in the system, not a machine. The web tier may be one box or fifty; it is still one tier.
Stateless
Keeping no per-user data between requests, so any box can serve any request.
Vertical scaling
Making one machine bigger. Simple, bounded, no redundancy.
Load balancer
The box that spreads incoming requests across a pool of identical servers. Day 2.
Replication
Keeping full copies of a database on more than one machine.
Sharding
Splitting one dataset across machines so each holds a different slice.

What breaks next. You now have two tiers, but you still have exactly one of each. One web server means a deploy is an outage. One database means a disk failure is a data loss. And neither box has anywhere to put the load when traffic doubles. Day 2 fixes all three, in the order a real team would: load balancer, then replication, then cache, then CDN.

Source: System Design Interview, Ch. 1 — Single server setup, Database, Which databases to use? (pp. 1–10). Resolution chain, TTL behaviour and the NoSQL family table are standard background added here for completeness.