Summary#
When you press Enter, the browser parses the URL, checks its own caches, finds the server's IP address through DNS, opens a TCP connection, secures it with TLS, sends an HTTP request, and receives a response that has passed through CDNs, load balancers, web servers, caches and databases. It then parses HTML into a DOM, fetches CSS, JavaScript and images, lays out and paints the page. On a first visit from far away, most of the time is not spent computing anything: it is spent on network round trips for handshakes and on the browser waiting for render-blocking files. That is why caches, CDNs, connection reuse, TLS 1.3 and HTTP/2 or HTTP/3 matter so much for speed.
Why It Exists#
Every system you design sits behind this journey. A user does not experience your database's query time or your service's throughput; they experience the time from click to a usable page, which includes a dozen steps you might not control directly. If you do not know where that time goes, you cannot make it fast, and you cannot reason about what fails: a DNS outage, an expired certificate and a crashed app server all look like "the site is down" to users, but each has a different cause and fix.
This walk-through connects the building blocks from What Is System Design? into one flow. Later pages go deeper into each step: Networking Fundamentals, DNS, TCP vs UDP, HTTP and HTTPS, CDN and Load Balancing.
How It Works#
0. Before you even press Enter#
Modern browsers start working while you type:
- Autocomplete suggests URLs from history and bookmarks, and may send keystrokes to a search provider for suggestions.
- Predictive preconnect: if you usually visit a site after typing its first letters, the browser may resolve DNS or even open a connection in advance.
- Input interpretation: the browser decides whether what you typed is a URL or a search query.
example.comis a URL;example combecomes a search. - HSTS check: if the site is on the browser's HSTS (HTTP Strict Transport Security) list, either because it sent a
Strict-Transport-Securityheader on an earlier visit or because it is on the built-in preload list, the browser upgradeshttp://tohttps://internally, without first making an insecure request.
1. Parse the URL#
A URL (Uniform Resource Locator) like https://shop.example.com:443/products/42?color=red#reviews has six main parts:
| Part | Example | Meaning |
|---|---|---|
| Scheme | https | Protocol to use (http, https, ftp, mailto, ...) |
| Host | shop.example.com | Which server, as a domain name or IP address |
| Port | 443 | Which "door" on that server (default 443 for HTTPS, 80 for HTTP; usually omitted) |
| Path | /products/42 | Which resource on the server |
| Query | ?color=red | Extra key-value parameters, separated by & |
| Fragment | #reviews | A position inside the page; never sent to the server |
A few details matter in practice:
- Percent-encoding: characters that are not allowed in URLs, such as spaces, are encoded as
%plus two hex digits: a space becomes%20. Query strings often encode spaces as+. - Internationalised domain names: a domain with non-ASCII characters (such as
münchen.de) is converted to an ASCII form called Punycode (xn--mnchen-3ya.de) before DNS lookup. - Userinfo: URLs may include
user:password@before the host. Browsers discourage it because it leaks credentials and is used in phishing. - Length: there is no strict standard limit, but very long URLs (over a few thousand characters) are rejected by some servers, proxies and CDNs, so large inputs belong in a request body.
URL vs URI vs URN. A URI (Uniform Resource Identifier) is any string that identifies a resource; the generic syntax is defined in RFC 3986. A URL is a URI that also says how to reach the resource (scheme plus location). A URN (Uniform Resource Name) names a thing permanently without saying where it is, like urn:isbn:0451450523 for a book. Every URL is a URI; not every URI is a URL. Browsers today follow the WHATWG URL Standard, which describes exactly how they parse real-world (sometimes malformed) URLs.
2. Check the browser's own caches#
Before touching the network, the browser checks:
- Service worker: a site can install a script that intercepts requests and answers from its own cache (this is how offline web apps work).
- HTTP cache: if an earlier response for this URL is stored and still fresh according to its
Cache-Controlheader, the browser uses it with no network request at all. If it is stale but has anETagorLast-Modifiedvalue, the browser can ask the server "has this changed?" and get a tiny304 Not Modifiedresponse. - Back/forward cache: pressing Back can restore the whole page from memory instantly.
For a first visit to a page, none of these help, so the browser goes to the network.
3. Look up the IP address with DNS#
Computers route packets by IP address, not by name. DNS (Domain Name System) translates the host into an IP. The lookup walks a chain of caches, from closest to furthest:
- Browser DNS cache (seconds to minutes).
- Operating system cache and the local
hostsfile. - Recursive resolver: a server run by your ISP, company or a public service (such as 8.8.8.8 or 1.1.1.1) that does the hard work and caches answers for everyone who uses it.
- If the resolver has no cached answer, it asks a root server, which points to the servers for
.com(a TLD, top-level domain), which point to the domain's own authoritative name server, which finally returns the record.
Key ideas:
- Record types: an A record maps a name to an IPv4 address, AAAA to an IPv6 address, and CNAME says "this name is an alias of that name" (common with CDNs:
shop.example.com→shop.example.com.cdn-provider.net). - TTL (time to live): every answer says how long it may be cached, from seconds to days. Long TTLs mean fewer lookups; short TTLs let you move traffic quickly.
- There are 13 root server identities (named A to M), but each is served by many machines around the world using anycast, where the same IP address is announced from many locations and packets go to the nearest one.
- Timing: a cached lookup takes ~0-1 ms; a full uncached lookup typically takes 20-120 ms, more on slow mobile networks.
- Privacy: classic DNS is unencrypted. DNS over HTTPS (DoH) and DNS over TLS (DoT) encrypt lookups so networks cannot see or tamper with them.
- IPv4 and IPv6: if the name has both A and AAAA records, browsers use Happy Eyeballs (RFC 8305): they try IPv6 and IPv4 almost in parallel and use whichever connects first, so a broken IPv6 path does not stall the page.
DNS is also a routing tool. GeoDNS returns different IPs depending on where the resolver is, sending European users to a European region. Details in DNS.
4. Open a TCP connection#
TCP (Transmission Control Protocol) gives a reliable, ordered stream of bytes over an unreliable network. Before sending data, client and server perform a three-way handshake:
- Client sends SYN ("I want to connect; my starting sequence number is X").
- Server replies SYN-ACK ("OK; mine is Y; I got your X").
- Client sends ACK ("I got your Y"), and can send data right after.
That costs one round trip (RTT, round-trip time: how long a packet takes to go there and back). Typical RTTs: ~0.5 ms inside a data center, ~20-80 ms within a continent, ~80-100 ms between the US and Europe, and 150-200 ms or more between the US and Asia. Light in fibre travels at about two-thirds of its speed in a vacuum, roughly 200 km per millisecond, so distance sets a hard floor that no software can beat.
The client picks a random ephemeral port (for example 52,314) as its side of the connection, so the connection is identified by four values: client IP, client port, server IP, server port.
Slow start. A new TCP connection does not send at full speed immediately. It starts with a small congestion window (commonly 10 packets, about 14 KB) and roughly doubles it each round trip while there is no packet loss. This is why the first ~14 KB of a response arrive in the first round trip, why very large HTML pages need several round trips even on fast networks, and why reusing a "warm" connection is faster than opening a new one. See TCP vs UDP.
Connections are state: teardown and reuse#
A TCP connection is not just a wire. Both ends keep state for it: sequence numbers, buffers, the congestion window and timers. That state has to be created (the handshake), kept up to date while data flows, and eventually torn down. Closing is a four-step exchange, because each direction of the byte stream is closed separately:
- The side that is finished sends FIN ("I have no more data to send").
- The other side replies ACK. It may still send data of its own at this point.
- When it is done too, it sends its own FIN.
- The first side replies ACK, and the connection is closed.
The side that closed first then waits in a state called TIME_WAIT for a short period (commonly up to a minute or two, depending on the operating system) so that delayed packets from the old connection cannot be mistaken for a new one. A busy proxy that opens and closes thousands of short connections per second can pile up tens of thousands of sockets in TIME_WAIT and run out of local ports. This is one practical reason servers and proxies prefer long-lived, reused connections.
The lesson for design is simple. One logical "request and response" hides many packets and several round trips. If every request paid for a fresh TCP and TLS setup, a page with 80 resources would pay for 80 handshakes. HTTP keep-alive (the default in HTTP/1.1) lets one connection carry many requests in sequence, and HTTP/2 multiplexing lets one connection carry many requests at the same time. The same reasoning drives designs that need a server to push data to clients, such as chat or live scores. They keep a persistent connection (WebSocket or Server-Sent Events) open for minutes or hours, so the server must hold that connection state for every online user. See Real-Time Communication.
5. Secure the connection with TLS#
For HTTPS, a TLS (Transport Layer Security) handshake follows. In TLS 1.3 (RFC 8446, 2018):
- The client sends a ClientHello: the TLS versions and ciphers it supports, a key share for key exchange, the hostname it wants (SNI, Server Name Indication, so one IP can serve many sites), and the application protocols it speaks (ALPN, used to agree on HTTP/2 or HTTP/1.1).
- The server replies with a ServerHello with its key share, then its certificate chain, a signature proving it holds the certificate's private key, and a Finished message.
- Both sides now derive the same session keys, and the client can send its encrypted HTTP request.
The certificate is how the browser knows it is talking to the real shop.example.com. It is issued by a certificate authority (CA) that the browser or operating system trusts, it lists the domain names it is valid for, and it expires (public certificates are now valid for at most about 13 months, and the industry is moving to shorter lifetimes). The browser checks the chain of signatures up to a trusted root, the hostname, the dates and whether the certificate was revoked. Browsers also require that certificates appear in public Certificate Transparency logs, which makes mis-issued certificates easy to spot.
Cost: TLS 1.3 needs one round trip on top of TCP; the older TLS 1.2 needed two. For returning visitors, session resumption skips most of the work, and 0-RTT lets the client send its request in the very first message. 0-RTT data can be replayed by an attacker, so it should be used only for safe, idempotent requests such as GET.
After the handshake, everything in the connection (URL path, headers, cookies, body) is encrypted. On-path observers can still see the IP addresses, the timing and size of traffic, and, unless Encrypted Client Hello is used, the hostname in the SNI field.
6. Send the HTTP request and receive the response#
The browser sends an HTTP request: a method (GET to read, POST to submit), a path, headers and sometimes a body.
GET /products/42?color=red HTTP/1.1
Host: shop.example.com
User-Agent: Mozilla/5.0 (...)
Accept: text/html
Accept-Encoding: gzip, br
Accept-Language: en-IN
Cookie: session=abc123
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Encoding: br
Cache-Control: private, no-cache
ETag: "v42-9f1c"
Set-Cookie: recently_viewed=42; Secure; HttpOnly; SameSite=Lax
<!doctype html> ...The server answers with a status code, headers and a body:
- 2xx success:
200 OK,201 Created,204 No Content. - 3xx redirect:
301/308moved permanently,302/307temporary,304 Not Modified(use your cached copy). - 4xx client error:
400bad request,401not authenticated,403forbidden,404not found,429too many requests. - 5xx server error:
500internal error,502bad gateway,503service unavailable,504gateway timeout.
Redirects cost round trips. Typing example.com may redirect from http:// to https://, then from example.com to www.example.com. Each redirect is another full request, possibly with a new connection. HSTS removes the first one.
HTTP versions change how requests travel, not what they mean. HTTP/1.1 sends one request at a time per connection, so browsers open about six connections per host. HTTP/2 sends many requests at once over one connection as binary frames, with header compression. HTTP/3 does the same over QUIC, a transport built on UDP that combines the transport and TLS handshakes and avoids one lost packet stalling every stream. See HTTP, HTTP/2, HTTP/3 and HTTPS.
Compression. Text responses (HTML, CSS, JS, JSON) are usually compressed with gzip or Brotli (br), shrinking them by 70-90%.
What HTTP promises, and what it does not#
HTTP is a request-response protocol, and it is stateless: each request carries everything the server needs, and the server does not have to remember anything about earlier requests. Sessions and logins are built on top, by sending a cookie or token with every request. Statelessness is a gift to system designers. A handler that is a pure function of the request (plus shared data in a database or cache) can run on any of a hundred identical servers, so you scale by adding copies behind a load balancer. Keep the stateful part of the system as small as possible.
Methods say what the client intends, and their idempotency matters for retries. An operation is idempotent if doing it twice has the same effect as doing it once:
| Method | Meaning | Idempotent? | Has a body? |
|---|---|---|---|
| GET | Read a resource | Yes, and also safe (no side effects) | No |
| PUT | Replace a resource with this full version | Yes | Yes |
| DELETE | Remove a resource | Yes | Usually no |
| PATCH | Change part of a resource | Not necessarily | Yes |
| POST | Create something or trigger an action | No | Yes |
Because the network can lose a response after the server did the work, clients and proxies retry. Retrying a GET or PUT is harmless. Retrying a POST /payments can charge a customer twice unless the API uses an idempotency key. See API Design.
Headers are open-ended key-value pairs, and that flexibility is a lesson in interface design. New features arrive as new headers that old clients simply ignore. Content negotiation is a good example. The browser sends Accept-Encoding: gzip, br to say which compression formats it understands. The server picks the best one it supports and labels the response Content-Encoding: br. An old client that sends no such header still gets an uncompressed response. Nothing breaks, and newer clients get smaller responses.
HTTPS protects the channel, not the content's honesty. TLS stops eavesdroppers and tampering in transit, but the request still comes from a client you do not control. A classic bug is an API that accepts "userId": 42 in the request body and loads that user's data. Anyone can edit the body and read another user's records. The server must take identity from something it can verify, such as a signed session token, and ignore any identity the client simply claims. See Authentication and Authorization.
7. Inside the data center: load balancers and web servers#
The IP address you got from DNS rarely belongs to the machine that runs the code. A typical path looks like this:
- CDN edge: for many sites, DNS points to a CDN. The edge server, often in the user's own city, ends the TCP and TLS connections (so handshakes are short), serves cached content directly, and forwards cache misses to your servers over already-open, warm connections. See CDN.
- Load balancer: receives requests for your region and spreads them across healthy servers, removing any server that fails its health checks. It may also end TLS. See Load Balancing.
- Reverse proxy: often NGINX, Envoy or HAProxy in front of the application. It handles compression, request buffering, rate limiting and routing by path. See Proxies and Reverse Proxies.
- Web or application server: runs the code that handles
/products/42. It checks the session cookie, reads the product from a cache (about 1 ms) or the database (1-10 ms for an indexed read), maybe calls other services, renders HTML or JSON, and returns it. A well-built handler takes 10-100 ms.
Every hop adds a little latency (0.1-1 ms inside a data center) and a possible failure point. A 502 Bad Gateway typically means a proxy could not get a valid response from the server behind it; a 504 Gateway Timeout means it waited too long.
How traffic is spread: client-side versus dedicated load balancing#
Step 7 hides a design choice. Something must decide which of many servers handles each request, and that "something" can sit in two places.
Client-side load balancing. The client holds the list of servers and picks one itself. It fetches the list from a service registry (or from the servers themselves) and refreshes it periodically or when notified. There is no extra network hop on each request, so it is fast, but every client must learn about changes.
- Redis Cluster works this way. Nodes gossip with each other so every node knows the cluster layout. A client asks any node for the map of hash slots to nodes, hashes each key to its slot and sends the command straight to the right node. If the layout has changed, the node answers with a
MOVEDredirection and the client updates its map. - DNS is client-side load balancing at internet scale. A name can have several A records, and resolvers rotate the order, so different clients try different IPs first. This is also how you avoid a single load balancer being a single point of failure: run two or more load balancers (ideally in different zones or regions) and publish all of them in DNS. If one dies, clients fall back to the others. The catch is speed: changes cannot spread faster than the record's TTL, and some resolvers hold answers longer than they should.
- gRPC has client-side balancing built in, which makes it a natural fit for internal service-to-service calls.
Client-side balancing suits two situations: a small number of clients you control (your own services and libraries), where pushing updates is easy, or a huge number of clients that can tolerate slow updates, like DNS.
Dedicated load balancers. A separate server or device sits between clients and servers. Clients know one address, and the balancer knows the backends. It costs one extra hop per request, but the server list can change in seconds and routing can be controlled finely. Dedicated balancers come in two kinds:
| Layer 4 (transport) | Layer 7 (application) | |
|---|---|---|
| Looks at | IP addresses and ports only | The full HTTP request: path, headers, cookies |
| Connection model | Passes the client's TCP connection through to one backend, as if they were directly connected | Ends the client's connection and opens its own connections to backends |
| Speed | Very fast, little processing per packet | More CPU per request (parsing, often TLS) |
| Can route by URL or user | No | Yes, for example /api to one pool and /static to another, or a cookie to pin a user |
| Best for | WebSockets and other long-lived connections, raw throughput | Ordinary HTTP APIs and web pages, long polling, gateway-like routing |
| Examples | AWS NLB, HAProxy in TCP mode, hardware balancers | AWS ALB, NGINX, Envoy, HAProxy in HTTP mode |
Some layer-7 balancers do support WebSockets, but a common default is layer 4 for long-lived connections and layer 7 for everything else.
Health checks let a balancer route around failures without anyone being paged. A TCP check only confirms the server accepts connections. An HTTP check calls an endpoint such as /healthz and expects a 200, which also catches a process that is up but broken. When a server fails a few checks in a row, it stops receiving traffic until it passes again.
Algorithms. The common choices are round robin (each server in turn), random, least connections (the server with the fewest open connections), least response time, and IP hash (the same client IP goes to the same server). For stateless HTTP servers, round robin or random is usually enough, and a newly added server starts receiving its share at once. For servers that hold long-lived connections, prefer least connections. Otherwise servers that have been up longest slowly collect most of the connections, and a freshly started server sits idle.
Implementations range from hardware appliances (F5 BIG-IP), through software (HAProxy, NGINX, Envoy), to cloud services (AWS ELB, ALB and NLB, Google Cloud Load Balancing, Azure Load Balancer). Large hardware and cloud balancers handle enormous request rates. In a typical design discussion, the balancer's own capacity is rarely the bottleneck, and saying "a managed or hardware load balancer" settles the point.
The front door is also the bouncer. Because every request passes through the gateway or load balancer, it is the natural place to enforce rate limits. A request over its limit is rejected with 429 Too Many Requests before it reaches an application server, so the application spends nothing on abusive traffic. The limitation is context: the gateway sees only what is in the request. It can identify a client by:
- User ID, taken from a verified token (often a JWT in the
Authorizationheader), for logged-in APIs. - IP address, often from the
X-Forwarded-Forheader set by an upstream proxy, for anonymous traffic. Many users behind one corporate NAT or mobile carrier gateway share an IP, so IP limits must be generous. - API key, often in an
X-API-Keyheader, for developer APIs.
Real systems layer several rules (per user, per IP, per endpoint and a global ceiling) and enforce the most restrictive one that applies. A rule such as "premium users get 10 times the limit" works at the gateway only if the premium status travels in the request, for example as a claim in the signed token. The gateway also needs a fast shared counter store, usually Redis, and a plan for when that store is slow or down. See the rate limiter case study.
8. The browser renders the page#
The browser now turns bytes into pixels. This sequence is called the critical rendering path:
- Parse HTML into the DOM (Document Object Model), a tree of elements. The parser streams: it starts before the whole file has arrived.
- Discover sub-resources. A preload scanner looks ahead for
<link>,<script>and<img>tags and starts fetching them early, often from a CDN and over the same HTTP/2 connection. - Build the CSSOM from CSS. CSS is render-blocking: the browser will not paint until it has the CSS, to avoid flashing unstyled content.
- Run JavaScript. A plain
<script>tag is parser-blocking: HTML parsing stops while the script downloads and runs, because it might change the document.deferscripts run after parsing, andasyncscripts run as soon as they arrive, without blocking the parser. - Layout computes the size and position of every visible element.
- Paint and composite draw pixels into layers and combine them on screen, usually with GPU help.
- After load, JavaScript frameworks may hydrate the page (attach event handlers), fetch data from APIs and re-render parts of it.
Google's Core Web Vitals measure the result from the user's point of view: LCP (Largest Contentful Paint, when the main content appears; "good" is 2.5 s or less), INP (Interaction to Next Paint, responsiveness; good is 200 ms or less) and CLS (Cumulative Layout Shift, visual stability; good is 0.1 or less).
9. Where the latency goes#
Here is a rough budget for a first visit from a user about 100 ms RTT away from the origin, with no CDN:
| Step | Round trips | Time |
|---|---|---|
| DNS lookup (uncached) | 1-4 by the resolver | ~50 ms |
| TCP handshake | 1 | ~100 ms |
| TLS 1.3 handshake | 1 | ~100 ms |
| HTTP request to first byte | 1 + server time | ~100 ms + 50 ms |
| Rest of HTML (slow start) | 1-2 | ~100-200 ms |
| CSS and JS (render-blocking) | 1-2 more | ~100-200 ms |
| Parse, layout, paint | none | ~50-200 ms on a phone |
| Total | ~0.65-1.0 s |
Only about 50 ms of that is your server's work. Most of the time is distance multiplied by round trips. The same visit through a CDN edge 10 ms away, with cached static files and a warm connection to the origin, might take 250-400 ms. A repeat visit with a reused connection and cached CSS and JS might take under 200 ms.
The layers underneath#
The steps above line up with the layers of the network stack. The full OSI model has seven layers, but three matter most in system design:
- Network layer (layer 3): IP. It gives every machine an address and moves packets from one address to another, hop by hop through routers. Delivery is best effort: packets can be dropped, duplicated or arrive out of order, and IP does not fix that. Machines inside a data centre usually get addresses automatically (via DHCP) and can use private ranges such as
10.0.0.0/8. To be reachable from the internet, an address must be a public IP, allocated through regional internet registries and announced to the internet's routers, which then know where to send packets for it. (Other layer-3 fabrics exist, such as InfiniBand in large ML training clusters, but IP dominates.) - Transport layer (layer 4): TCP, UDP and QUIC. These turn "packets to a machine" into "a conversation between two programs", identified by ports. TCP adds reliability, ordering, flow control (do not overrun a slow receiver) and congestion control (back off when the network is congested). UDP adds almost nothing, which is why real-time games and video calls build their own lighter rules on it. QUIC is a modern transport on top of UDP that behaves like an improved TCP with built-in TLS.
- Application layer (layer 7): DNS, HTTP, WebSocket and others. These define the messages your code actually exchanges.
The value of layering is that each layer can trust the one below. Your application code assumes bytes arrive intact and in order, because TCP retransmits what IP lost. It never has to find a physical path across the world, because IP and the routers of your ISP and backbone providers do that. The cost is that every layer adds headers, handshakes and processing, and the higher in the stack a component works, the more it must parse per request. That is exactly why layer-7 load balancers cost more CPU than layer-4 ones. See Networking Fundamentals.
Distance: regions, edges and data locality#
The speed of light sets the floor. Light in fibre travels at about 200,000 km per second, two-thirds of its speed in a vacuum. New York to London is about 5,600 km, so a round trip covers 11,200 km and takes at least 56 ms before any router, queue or server adds a microsecond. Real paths are longer than great circles, so observed RTTs are higher. Compare that with well under 1 ms inside one data centre.
Large services therefore deploy in several regions (cities or areas such as "US East" or "Mumbai"), and inside each region across several availability zones: separate buildings with separate power and networking, a few milliseconds apart, so a flood or a cut cable in one building does not take the service down.
Within those constraints, the guiding principle is data locality: keep the data a request needs close to the code that processes it, and both close to the user. If the web servers are in New York but the database is in Los Angeles, every query pays tens of milliseconds, and a page that makes ten sequential queries pays that ten times. Two strategies help:
- CDNs answer cacheable requests from edge locations in hundreds of cities. They work best for static assets, but any response that is the same for many users and tolerates some staleness can be cached at the edge, including public search results.
- Regional partitioning splits the data itself by geography when users mostly interact with nearby things. A ride-hailing rider in Miami never needs a driver in New York. Millions of riders and drivers exist worldwide, but in any one city there are only thousands. Group nearby cities into regions, give each region its own database and services in a nearby data centre, and most requests never leave their region.
Regional partitioning has costs. A user who travels needs their account in a new region. Global queries ("all rides yesterday") must combine regions. Data-residency laws may decide where data must live. See Multi-Region Data.
Variation: when the URL is a short link#
Typing https://sho.rt/15ftgG follows every step above, but the server's job is just to look up the code and answer with a redirect. That makes the redirect path a good miniature of read-heavy design.
Several design decisions sit in this tiny flow:
- Redirect type. A
301 Moved Permanentlymay be cached by browsers and CDNs, so repeat clicks may never reach your servers. That means less load, but you lose click counts and cannot change the target later. A302 Found(or307) is temporary, so every click reaches you and can be counted, at the cost of more traffic. Many shorteners choose302for analytics. - Creating codes. One option hashes the long URL. First canonicalise it (lowercase the host, remove a default port such as
:443, normalise the trailing slash) so equivalent URLs map to the same code. Then hash it with a function such as SHA-256, encode the result in base62 and keep the first 7-8 characters. Base62 usesa-z,A-Zand0-9, and avoids the+and/of base64 because/separates path segments and+can mean a space in query strings. With n codes already used out of a space of size S, the next random code collides with probability n/S, so aUNIQUEconstraint and a few bounded retries with a salt are still required. The other option is a counter: a single atomic counter (RedisINCRreturns a distinct value to each caller because Redis runs commands one at a time) encoded in base62. One billion is15ftgGin base62, so six characters cover about 56.8 billion codes (62^6) and seven characters about 3.5 trillion (62^7). Sequential codes are guessable, so if enumeration matters, scramble the number with a reversible transform before encoding. - Caching. The mapping almost never changes, and popular links are clicked many times, so a cache (and the CDN for
301s) absorbs most reads.
The full design is the URL shortener case study.
Variation: when the URL is a large file#
When the URL points at a 2 GB video or a shared document, the naive path (browser to app server to disk) breaks in two ways.
- Uploading to the app server's own disk works for a prototype. But storage grows until one machine is full, and if that machine dies the files are gone or unreachable. Store files in an object store (S3, Google Cloud Storage, Azure Blob Storage) designed for durability and near-unlimited size, and keep only metadata in the database.
- Downloading through the app server (object store to server, then server to user) moves every byte twice, doubling latency and bandwidth cost and tying up server connections. Let the client fetch directly from the object store or a CDN using a pre-signed URL: a link that carries a signature and an expiry time and grants access to one object for a few minutes.
Large uploads must also survive flaky networks, which means resumable, chunked uploads:
Each chunk is small enough (5-10 MB) to retry cheaply, the fingerprint lets the server verify it, and the metadata row records progress, so a client that reconnects asks what is missing and skips the rest. Cloud object stores provide this as multipart upload. Knowing how it works shows real depth. See Handling Large Blobs and Object Storage.
Variation: when millions open the same URL at once#
When tickets for a huge concert go on sale, or a breaking news story spreads, millions of browsers request the same event page within minutes. Every step of the journey is multiplied, and the design goal becomes making the repeated reads cheap:
- Cache what is read often and changes rarely: event names, dates, venue details, performer bios and seat maps. Key the cache simply (for example
event:123holds the event object) in Redis or Memcached with read-through behaviour: a miss reads the database and fills the cache. - Keep the cache honest. Use database triggers or change events to delete entries when the event changes, plus TTLs as a safety net. TTLs can be long for static venue data and short for fast-changing data such as availability.
- Scale the stateless tier horizontally behind a load balancer using round robin or least connections, and let the CDN serve the shared HTML and assets.
- Protect against a stampede. If a hot entry expires, thousands of simultaneous misses can hit the database at the same moment. Request coalescing (one request rebuilds the entry while the others wait for its result) or refreshing the entry slightly before it expires keeps that from happening. See Cache Failure Modes.
A related trick applies when a page shows expensive aggregates, such as an advertiser's dashboard of clicks over a year. Instead of computing the answer when the URL is opened, pre-aggregate it: a nightly or streaming job writes daily and weekly totals into a separate table, and the page reads those, drilling down to finer data only when asked. This is caching in another form: storage is traded for speed on the most common queries.
When to Use It#
Use this mental model when:
- A page or API is slow and you need to know which step costs the time (DNS, connect, TLS, time to first byte, download, rendering).
- You are deciding whether a CDN, a DNS change, connection pooling, HTTP/2 or server optimisation will help most.
- You are debugging: DNS errors (
NXDOMAIN), certificate errors, connection timeouts,502/504and500codes each point to a different step. - You are designing a global product and need to estimate how much distance will cost users in each region.
- You are explaining in an interview where the CDN, DNS, load balancer and app servers sit in a design.
When NOT to Use It#
- For service-to-service calls inside one data center, DNS, TCP and TLS costs are tiny (well under a millisecond with connection pools). Focus on server time and the number of calls instead.
- For backend throughput problems (a database maxed out on writes), the client's path is not the bottleneck.
- Do not over-optimise the browser path for internal tools used by a few people on the office network.
How to Implement It#
To make this journey fast and reliable for your own site:
- Measure first. Use the browser's network panel and the Navigation Timing API to see DNS, connect, TLS, time to first byte (TTFB) and download times, and collect real-user metrics (Core Web Vitals) from the field.
- Use a fast, redundant DNS provider with anycast, and set TTLs of minutes to hours for stable records; lower them before planned migrations.
- Put a CDN in front: terminate TCP and TLS near users, cache static files and, where possible, whole pages.
- Enable TLS 1.3, HTTP/2 and HTTP/3; enable HSTS (and consider the preload list) to remove the
http→httpsredirect. - Reuse connections: keep-alive between browser and edge, and connection pools between edge, load balancer and app servers.
- Avoid redirect chains; link to the final URL.
- Keep the first response small: important HTML and inline critical CSS in the first ~14 KB, compressed with Brotli.
- Make CSS small and JavaScript non-blocking:
deferorasyncscripts, split bundles, and preload key resources. - Cache aggressively with versioned file names for static assets, and validators (
ETag) for pages. - Monitor each layer: DNS resolution success, certificate expiry, edge hit ratio, load balancer 5xx rates, app latency percentiles.
# Response headers for a static, versioned asset (app.3f9c1b.js)
Cache-Control: public, max-age=31536000, immutable
Content-Encoding: br
# Response headers for a personalised HTML page
Cache-Control: private, no-cache
ETag: "v42-9f1c"
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
# HTML hints
<link rel="preconnect" href="https://cdn.example.com">
<link rel="preload" href="/fonts/inter.woff2" as="font" crossorigin>
<script src="/app.3f9c1b.js" defer></script>| Technology | Fits when |
|---|---|
| Route 53, Cloudflare DNS, NS1 | Managed authoritative DNS with anycast, health checks and geo routing |
| Cloudflare, CloudFront, Fastly, Akamai | CDN, TLS termination and caching near users |
| NGINX, Envoy, HAProxy | Load balancing and reverse proxying in your own infrastructure |
| AWS ALB/NLB, Google Cloud Load Balancing, Azure Front Door | Managed load balancers |
| Let's Encrypt, AWS Certificate Manager | Free, automated TLS certificates with renewal |
| Lighthouse, WebPageTest, browser DevTools | Measuring the full page-load path |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| Long DNS TTL | Fewer lookups, resilient to DNS outages | Slow to move traffic during failover | Stable records |
| Short DNS TTL | Fast traffic shifts | More lookups, more load on DNS | Before migrations, active failover |
| TLS at the CDN edge | Short handshakes for users | Edge sees plaintext; edge-to-origin needs its own TLS | Almost always for public sites |
| HSTS preload | No insecure first request | Hard to undo; every subdomain must support HTTPS | Sites committed to HTTPS everywhere |
| Inlining critical CSS | Faster first paint | Not cached separately; duplicated across pages | Landing pages, first visits |
| Many small files over HTTP/2 | Better caching granularity | More requests and per-request overhead | Modern build tools with code splitting |
| 0-RTT resumption | One fewer round trip for returning users | Replay risk | Safe, idempotent requests only |
| Layer 4 load balancer | Fast, passes long-lived connections through | Cannot route by URL, header or cookie | WebSockets, raw TCP, very high throughput |
| Layer 7 load balancer | Routing by path, header or cookie, TLS termination, retries | More CPU per request, one more connection to manage | Ordinary HTTP APIs and websites |
| Client-side load balancing | No extra hop, the client picks the best server | Every client must track server changes | Internal services you control, or DNS-style coarse routing |
| 301 redirect | Browsers and CDNs cache it, little server load | Cannot change the target or count clicks later | Permanent moves, such as http to https |
| 302 redirect | Every click reaches you, target can change | More traffic to your servers | Short links that need analytics |
| Pre-signed URLs to the object store | File bytes skip your servers | Links can leak until they expire | Large uploads and downloads |
| Regional partitioning | Most requests stay inside one nearby region | Cross-region queries, users who travel, more complex operations | Users mostly interact with nearby data |
Common Pitfalls#
- Forgetting the fragment is never sent: servers cannot see
#reviews, so do not put data there that the server needs. - Setting DNS TTLs very low "just in case", which slows every new visitor and multiplies DNS queries.
- Ignoring round trips: three handshakes across an ocean cost 400-600 ms before the first byte.
- Redirect chains (
http→https→www→ localised path) adding a full round trip each. - Letting a certificate expire because renewal was manual; automate it and monitor expiry.
- Large render-blocking JavaScript bundles that delay first paint by seconds on mobile devices.
- Measuring only server latency, while users wait mostly on the network and the browser.
- Trusting identity fields in the request body (
userId) instead of deriving the user from a verified session or token. - Sending file uploads and downloads through application servers so every byte crosses them twice.
- Putting WebSocket servers behind a balancer that cannot hold long-lived connections, or balancing them with round robin so old servers accumulate all the connections.
- Relying on DNS changes for fast failover while records have long TTLs, or forgetting that some clients ignore TTLs.
- Creating short-link codes from an un-canonicalised URL, so
HTTP://Example.com:443/andhttps://example.comget different codes. - Using
301for links you later need to change or count, then discovering that browsers have cached the redirect. - Opening a new TCP and TLS connection per request between services instead of pooling them.
Real-World Examples#
Let's Encrypt, a free and automated certificate authority launched in 2015, made HTTPS practical for millions of sites by issuing short-lived certificates through the ACME protocol, with automatic renewal.
HTTP/3 and QUIC grew out of Google's experimental QUIC protocol and were standardised by the IETF in 2021 (RFC 9000) and 2022 (RFC 9114); major browsers and CDNs support HTTP/3 today.
Typical scenario: a user in India visits a site hosted only in the US. DNS, TCP and TLS each pay a ~200 ms round trip before the first byte, so the page takes well over a second. A CDN with edge TLS in Mumbai cuts each handshake to a few milliseconds, and the edge reuses a warm connection to the US origin for uncached requests.
Redis Cluster is a widely used example of client-side load balancing. Cluster-aware clients cache the mapping of 16,384 hash slots to nodes and send each command straight to the owning node. When slots move during resharding, nodes reply with MOVED or ASK redirections, and the client updates its map, so there is no central proxy in the data path.
Cloud object stores expose resumable, chunked uploads as a standard API. Amazon S3's multipart upload, for example, lets a client upload parts independently and in parallel, retry any failed part, and then complete the upload as one object. That is why large-file products build on it rather than inventing their own chunking protocol.
In the Interview#
Using this journey in a design interview#
"What happens when you type a URL and press Enter?" used to be a common stand-alone interview question. It is asked less often today at large technology companies, but its content still shows up in every design interview in smaller pieces. Three ways to use it well:
- As the skeleton of your high-level design. The left edge of almost every diagram is this journey: client, DNS, CDN, load balancer, stateless services. Draw it in a minute and move on to the parts that are specific to the problem. Interviewers rarely ask about the lines between services unless you invite it.
- As the answer to latency questions. When asked "how do we make this fast for users in Asia?", reason from round trips: distance times handshakes, then fix it with edge termination, warm connections, caching at the edge and regional data.
- As a source of precise small choices. "WebSockets behind a layer-4 balancer with least connections", "pre-signed URLs so file bytes skip our servers", "rate limiting at the gateway with a 429", "client-side balancing for internal gRPC calls". Each one-line choice shows you know what happens on the wire.
Know where to stop. A performance-minded interviewer may enjoy a sentence about QUIC and HTTP/3 or TCP slow start, but most interviews reward spending the time on the problem's real bottleneck rather than on packet-level detail.
Deep Dive: Connection reuse, slow start and the 14 KB ruleShow
Why the first 14 KB matter. RFC 6928 raised TCP's recommended initial congestion window to 10 segments. With a typical maximum segment size of about 1,460 bytes, that is about 14.6 KB in the first round trip. A server that fits the critical HTML (and inline critical CSS) into that much compressed data lets the browser start rendering after one round trip of response time. A 100 KB page might need four or five round trips during slow start.
Warm connections. A connection that has been used for a while has a larger congestion window and an established TLS session. CDNs keep pools of warm connections from edge to origin, so a cache miss pays only the edge-origin RTT once, not three handshakes. Inside data centers, connection pools to databases and services do the same: setting up a new TLS connection costs a few milliseconds of CPU and at least two round trips, while reusing one costs nothing.
Head-of-line blocking. With HTTP/2 over TCP, all streams share one byte stream. If one packet is lost, every stream waits for its retransmission, even streams whose data arrived. On lossy mobile networks this can make HTTP/2 slower than several HTTP/1.1 connections. QUIC solves it by tracking each stream separately on top of UDP, so a loss only stalls the affected stream.
Connection migration. A QUIC connection is identified by a connection ID, not by the IP-port tuple, so a phone moving from Wi-Fi to mobile data can keep its connection without a new handshake.
Deep Dive: Failure modes along the pathShow
| Step | What fails | What the user sees | Typical fix |
|---|---|---|---|
| DNS | Provider outage, wrong record, expired domain | "Server not found" | Anycast DNS, a secondary provider, monitoring of records |
| TCP | Firewall, server overloaded, SYN flood | Connection timeout | Load balancers, SYN cookies, DDoS protection |
| TLS | Expired or wrong certificate, old TLS versions | Full-page browser warning | Automated renewal, expiry alerts, modern configs |
| CDN / LB | Misconfiguration, no healthy backends | 502, 503, 504 | Health checks, gradual config rollout, failover |
| App server | Bugs, overload, slow dependencies | 500, slow pages | Timeouts, autoscaling, circuit breakers |
| Database | Overload, failover | Slow pages, errors | Caches, replicas, connection limits |
| Browser | Huge JS, third-party scripts | Blank page, frozen UI | Code splitting, async loading, budgets |
Large, widely reported outages have come from configuration changes at this layer: a bad DNS or routing change, or a CDN configuration that triggers a bug, can make many sites unreachable at once even though their servers are healthy. This is why such changes are rolled out gradually and why some companies use more than one DNS provider or CDN.
Deep Dive: A latency model you can computeShow
You can estimate the time to the first useful byte with a simple model:
T ≈ DNS + RTT × (handshake round trips + 1 + slow-start rounds) + server time
- Handshake round trips: 1 for TCP plus 1 for TLS 1.3 gives 2. TLS 1.2 gives 3. QUIC combines transport and TLS into 1, and a resumed QUIC connection with 0-RTT data gives 0.
- The +1 is the request and the first part of the response.
- Slow-start rounds are the extra round trips needed because the congestion window starts small. With an initial window of 10 segments (about 14.6 KB) that doubles each round, the cumulative data delivered after 1, 2, 3 and 4 rounds is about 14.6, 44, 102 and 219 KB. A 100 KB compressed HTML page therefore needs about 3 rounds in total, which is 2 more than the first.
Worked example, for a user 150 ms RTT from the origin, an uncached DNS lookup of 60 ms, a 40 KB compressed page and 50 ms server time:
| Setup | Handshake RTTs | Extra slow-start RTTs | Time to full HTML |
|---|---|---|---|
| TCP + TLS 1.2, new connection | 3 | 1 | 60 + 150 × 5 + 50 = 860 ms |
| TCP + TLS 1.3, new connection | 2 | 1 | 60 + 150 × 4 + 50 = 710 ms |
| QUIC (HTTP/3), new connection | 1 | 1 | 60 + 150 × 3 + 50 = 560 ms |
| CDN edge 10 ms away terminates TLS, warm 150 ms link to origin | 2 to the edge | 0 on the warm link | 60 + 10 × 2 + (150 + 10) + 50 = 290 ms |
| Repeat visit, DNS cached, connection reused, page cached at edge | 0 | 0 | 10 + 5 = 15 ms |
Three lessons fall out of the arithmetic. First, the server's 50 ms is a small part of the total until the network part is fixed. Second, removing a round trip is worth more than any reasonable code optimisation when the RTT is 150 ms. Third, the CDN wins mostly by moving handshakes close to the user and reusing a warm connection for the long haul, even when the content itself is not cached.
The browser's Navigation Timing API exposes each of these phases (domainLookupStart, connectStart, secureConnectionStart, requestStart, responseStart and so on), so you can check the model against real users rather than guess.
Deep Dive: DNS details that bite in productionShow
Negative caching. If a name does not exist, the NXDOMAIN answer is also cached, for a time taken from the zone's SOA record. If you query a new hostname before creating its record, resolvers may keep saying "does not exist" for minutes after you create it.
TTL is a request, not a guarantee. Most resolvers honour TTLs, but some clamp very low values up to a minimum, some applications cache answers for their whole process lifetime, and mobile operating systems keep their own caches. When you fail over by changing a record with a 60-second TTL, most traffic moves within a few minutes, but a long tail may keep hitting the old address for much longer. Plan failover so the old target either keeps serving or fails fast.
Lowering a TTL takes time too. If a record currently has a one-day TTL and you want five-minute failover during a migration, lower the TTL at least a day before, so that every cache picks up the short TTL before you change the address.
DNS load balancing is coarse. One large resolver (a public resolver or a big ISP) may serve millions of users, so every user behind it gets the same answer. Traffic arrives in lumps, not in fine-grained shares. The EDNS Client Subnet extension lets a resolver pass part of the client's address to the authoritative server for better geographic answers, at some cost to privacy and cache efficiency.
Glue records. If example.com's name servers are ns1.example.com, a resolver could not look them up without already knowing them. The parent zone (.com) therefore also returns their IP addresses, called glue records, along with the delegation.
CNAME at the zone apex. The DNS standard forbids a CNAME on the bare domain (example.com) alongside the SOA and NS records that must live there. That is a problem when a CDN wants you to alias your domain to its hostname. Providers offer workarounds under names such as ALIAS, ANAME or "CNAME flattening", where the DNS provider resolves the target itself and returns plain A records.
Deep Dive: What the TLS 1.3 handshake actually provesShow
TLS has to achieve two things in as few round trips as possible: agree on secret keys that no eavesdropper can compute, and prove that the server really is shop.example.com.
Key agreement. In the ClientHello, the client sends an ephemeral Diffie-Hellman key share, usually on an elliptic curve such as X25519. The server answers with its own share in the ServerHello. Each side combines its private value with the other's public share and arrives at the same secret, while an observer who sees both public shares cannot compute it. Because the client guesses the key-exchange group up front and sends its share immediately, TLS 1.3 completes in one round trip. If the guess is wrong, the server asks for another share, costing an extra round trip. TLS 1.2 used a separate round trip to negotiate first.
Forward secrecy. The Diffie-Hellman values are fresh for every connection and thrown away afterwards. Even if the server's long-term private key is stolen later, recorded past traffic cannot be decrypted. TLS 1.3 removed the older RSA key-transport mode, which lacked this property.
Authentication. The server sends its certificate chain and a CertificateVerify message: a signature, made with the certificate's private key, over the handshake so far. Only the holder of that key can produce it, so a man in the middle with a copy of the certificate but no key fails here. The Finished messages then carry a MAC over the whole handshake, so any tampering with the negotiation (for example forcing a weaker cipher) is detected.
Resumption and 0-RTT. After a handshake, the server can give the client a session ticket. Next time, the client presents it and both sides derive new keys from the shared secret, skipping certificate checks. With 0-RTT, the client also sends application data in its first flight, encrypted with keys derived from the ticket. That early data has no protection against replay, because an attacker can capture and resend it, which is why servers accept only idempotent requests as 0-RTT data.
Who terminates TLS. In production, TLS usually ends at the CDN edge or load balancer, which holds the certificate. Traffic from there to the origin is re-encrypted with a separate TLS connection, and inside the network many companies use mutual TLS (both sides present certificates) between services. See Security Fundamentals.
Key Takeaways#
- A page load is: URL parsing and cache checks, DNS lookup, TCP handshake, TLS handshake, HTTP request and response through CDN, load balancer and servers, then browser rendering.
- A URL has a scheme, host, port, path, query and fragment; the fragment never reaches the server; URLs are a kind of URI.
- DNS answers are cached at many levels (browser, OS, resolver) according to TTLs; uncached lookups walk root, TLD and authoritative servers.
- Each handshake costs a network round trip, and TCP slow start limits how much data the first round trips carry, so distance dominates latency for far-away users.
- At scale, the IP points to a CDN edge or load balancer that forwards requests to healthy servers, which read caches and databases.
- The browser builds the DOM and CSSOM, lays out and paints; render-blocking CSS and parser-blocking JavaScript often delay the page more than the server does.
- CDNs, connection reuse, TLS 1.3, HTTP/2 or HTTP/3, HSTS and small critical payloads remove most of the avoidable delay.
- A TCP connection is state on both ends. Opening it costs a handshake, closing it is a four-step FIN and ACK exchange, so keep-alive, HTTP/2 multiplexing and connection pools matter.
- HTTP is stateless, which lets any server handle any request. GET, PUT and DELETE are idempotent and safe to retry, while POST needs an idempotency key. HTTPS secures the channel but never makes client input trustworthy.
- Load balancing can be client-side (Redis Cluster, gRPC, DNS) or dedicated. Use layer 4 for long-lived connections and layer 7 for HTTP routing, with health checks and least connections for persistent connections.
- The gateway or load balancer is the natural place to rate-limit, using only what the request carries: user token, IP or API key.
- Distance sets a hard floor of about 1 ms of round trip per 100 km of fibre. CDNs, regions and regional partitioning keep data close to users.
- Short links, large files and viral pages are the same journey with different bottlenecks: redirect caching, direct-to-object-store transfers with chunked uploads, and aggressive caching with stampede protection.