In a restaurant, you never walk into the storeroom to get ingredients yourself. You order from the waiter, the kitchen cooks, and the ingredients come from the storeroom. The kitchen never sends food to your table without an order either.
Web applications are arranged the same way, and the arrangement is called client-server. The client (a browser, a phone app) starts the conversation by sending a request. The server provides a service or resource (data or a file), processes that request and sends back a response. In that restaurant, you are the client, your order is the request, the waiter who carries it is the network, and the dish brought to you is the response. The kitchen is the server, and the storeroom is the database. It's the most basic way to arrange a web application.
Client and server
- The client starts. It sends a request, waits, then shows the result. Budi's browser and the TicketTune phone app are clients.
- The server waits. It provides a service, such as concert data and ordering, and answers every request that comes in. The server never starts a conversation first.
One server serves many clients at once. Heavy work and important data live on the server, because the client is in the user's hands: it can be switched off, changed or faked. The user can't change the server.
The journey of one request
One term first: the RTT (round-trip time) is the time for a data packet to reach the server and for its answer to come back. The RTT from Kuala Lumpur to Singapore is about 20 ms. This is the journey of the request GET https://tickettune.test/api/events/42 (asking for the data of concert 42). Budi opens the page for the first time (example-model numbers):
| Stage | Takes | At ms |
|---|---|---|
DNS: look up the IP address of tickettune.test |
40 ms | 0 to 40 |
| TCP handshake: open the connection | 1 RTT = 20 ms | 40 to 60 |
| TLS 1.3 handshake: agree on HTTPS encryption | 1 RTT = 20 ms | 60 to 80 |
| Request travels to the server | ½ RTT = 10 ms | 80 to 90 |
| Server runs its code | 8 ms | 90 to 98 |
| Server runs 3 database queries | 3 × 4 ms = 12 ms | 98 to 110 |
| Response travels back to the browser | ½ RTT = 10 ms | 110 to 120 |
The total is 120 ms, and only 20 ms of it (8 + 12) is the server working. The rest is travel. Before the page content reaches Budi's browser, there are 3 round trips to Singapore: TCP, TLS, then the request and its response. DNS is travel too, but to a different server: the DNS resolver (a server that looks up IP addresses), not TicketTune's server.
The second request is much faster. The IP address is cached (stored, so it doesn't have to be looked up again), and the TCP and TLS connection stays open (keep-alive). So it's just 1 RTT + the server's work: 20 + 20 = 40 ms.
Now say TicketTune's server moved to Virginia, USA, with an RTT of 230 ms. The first request would take 40 (DNS) + 3 × 230 (three round trips) + 20 (server work) = 750 ms, with exactly the same code. So distance to users costs a lot of time. HTTP/3 (a newer version of HTTP that runs on QUIC) combines the connection and TLS handshakes into one round trip. With HTTP/3, that first request to Virginia takes about 40 + 2 × 230 + 20 = 520 ms. The condition: the browser already knows the server supports HTTP/3, from an earlier visit or from DNS.
Three tiers: presentation, application, data
Web applications are usually split into three layers, or tiers:
| Tier | In TicketTune | Its job |
|---|---|---|
| Presentation | browser, phone app | shows the pages and takes the clicks |
| Application | the app server |
business rules: at most 4 tickets, checking login, pricing |
| Data | PostgreSQL database | stores concerts, seats and orders |
In a 2-tier architecture, the client talks straight to the database. It's simpler, but it has two problems: the database password travels to the client, and a user who changes the client can skip the business rules. In 3-tier, each tier can be changed and scaled (given more capacity) on its own without disturbing the other tiers. For example, the application servers can grow to three without changing the UI, and the database can be replaced without changing the client.
Here are both sides in code, the client on top and the server below:
// client (browser): the presentation tier
const res = await fetch("https://tickettune.test/api/events/42");
const concert = await res.json();
console.log(concert.name, concert.seatsLeft);
// server (Node.js + Express + node-postgres): the application tier
app.get("/api/events/:id", async (req, res) => {
const id = req.params.id;
const event = await pool.query("SELECT id, name, date FROM events WHERE id = $1", [id]);
const categories = await pool.query("SELECT name, price FROM ticket_types WHERE event_id = $1", [id]);
const available = await pool.query("SELECT COUNT(*) AS n FROM seats WHERE event_id = $1 AND status = 'available'", [id]);
res.json({ ...event.rows[0], categories: categories.rows, seatsLeft: Number(available.rows[0].n) });
});
fetch(...)on the client only knows the API's address, the address the server provides for asking for data. The client doesn't know there's a database, let alone its password.app.get("/api/events/:id", ...)is the server code that waits for requests to that path, the part of the URL after the domain name.:idis a part of the path that can change, so for/api/events/42,req.params.idholds"42".- The three
pool.query(...)calls are three trips to the data tier. Those are the 3 database queries in the first table. res.json(...)on the server sends the response, and the client'sfetchreceives it.
Stateless and stateful
TicketTune now has two application servers, app-1 and app-2, behind a load balancer. Siti logs in, and app-1 keeps her session (the record that Siti is logged in) in app-1's memory. That's stateful: the server remembers client information between requests. The load balancer sends Siti's next request to app-2, which doesn't have that session, so the answer is 401 Unauthenticated (not logged in). Siti is suddenly logged out.
A stateless server doesn't keep client state (information about the client, such as the session) in its own memory. There are two ways. First, every request carries everything it needs, for example a signed token (a login pass whose authenticity any server can check). Second, the session lives in a shared place like Redis (a fast database all the servers share). Siti's request can land on any server and the result is the same. That's why stateless servers are easy to scale horizontally: just add servers. Details on sessions and tokens are in the Auth track.
🤔 REST, GraphQL, gRPC
How client and server talk is a choice too:
- REST: a URL per resource (
/api/events/42) and HTTP methods (GET, POST and others). Simple and easy to cache, it fits most APIs. - GraphQL: one endpoint (one API address), and the client writes a query naming the fields (pieces of data) it needs. Useful when every screen needs data in a different shape.
- gRPC: a binary format (Protocol Buffers, not text) over HTTP/2, fast and typed (the shape of the data is fixed in advance). Usually for conversations between servers inside a system, not from the browser.
⚠️ What makes pages slow or logs people out
- A server far from its users. The same code takes 120 ms from Singapore and 750 ms from Virginia. Put servers near users, or use a CDN (servers in many cities that keep copies of files) for static files such as images.
- Application server and database in different regions. Every query crosses a long distance to another region, so 3 queries × 23 ms = 69 ms instead of 12 ms. Keep them close together.
- Sessions in one server's memory. As soon as there's a second server, users get logged out at random. Make the servers stateless.
- The client talking straight to the database. The database credentials (its username and password) leak to the client, and the business rules can be skipped.
TL;DR: The client (a browser, a phone app) starts the conversation and displays the result. The server (a computer that runs the app) waits, provides a service and answers every request (a message asking for something). The first HTTPS request needs DNS (looking up the server's address), then 3 RTTs or 3 round trips to the server (TCP, TLS, request-response), plus the server's work. That's 120 ms from Kuala Lumpur to Singapore, and 750 ms to Virginia. Later requests reuse the connection (keep-alive), so it's 1 RTT + the server's work. A 3-tier architecture (three layers) separates presentation (browser), application (server) and data (database), so each tier can be changed and scaled (given more capacity) on its own. Stateful = the server keeps sessions (the record that a user is logged in) in its memory. Stateless = every request carries what it needs, so any server can answer and horizontal scaling (adding servers) becomes easy.
⚡ The client starts, the server answers
Meaning: The client (a browser, a phone app) starts the conversation by sending a request (a message asking for something). The server (a computer that runs the app) provides a service or resource (data or a file), answers every request that comes in, and never starts first.
⚡ The time goes on travel
Guess first: Budi's first request from Kuala Lumpur to a server in Singapore takes 120 ms. Before the server works, the browser has to look up the server's address and open a connection. How much of the 120 ms is the server working?
Only 20 ms. The rest is travel: DNS (looking up the server's address), then 3 round trips (TCP, TLS, the request and its response).
Meaning: The second request reuses the open connection (keep-alive), so it's just 1 RTT (one round trip, 20 ms) + the server's work: 40 ms. A server far from its users makes pages slow with exactly the same code.
⚡ The client only knows the API's address
Write:
// client (browser): the presentation tier
const res = await fetch("https://tickettune.test/api/events/42");
const concert = await res.json();
console.log(concert.name, concert.seatsLeft);
Meaning: This code runs in the browser: fetch asks the server's API address for the data of concert 42, then shows its name and seats left. The client doesn't know there's a database, let alone its password. In a 3-tier architecture (three layers), presentation (browser), application (server) and data (database) can each be changed and scaled (given more capacity) on their own.
⚡ Stateless, so adding servers is easy
Meaning: The ticket app TicketTune has two servers, app-1 and app-2. If Siti's session (the record that she is logged in) lives in app-1's memory, her request that lands on app-2 gets a 401 (not logged in). A stateless server keeps no client state (information such as the session): every request carries a token (a login pass), or the session lives in Redis (a shared database). So any server can answer.