Module 2 / Start with a simple system / Clients and servers

Lesson7 minModule 2 · lesson 1 of 7

Clients and servers

Who asks, who answers.

Nearly every system you will design is built on one simple pattern: a client asks, a server answers. The client is whatever the user touches: a phone app, a browser, even another program. The server is a program running on a machine somewhere that holds the logic and data the client does not. In a food-delivery app, the phone shows restaurants; the server knows which restaurants are open and which orders exist.

Phone appDNSServerDatabasewhere isapi.example.com?requestqueryrowsresponse
One request, one response.

Follow a single tap on Show restaurants. The phone first needs an address, so it asks DNS, the internet's phone book, to turn a name into an IP address. Then it opens a connection and sends an HTTP request over it. The server runs code, perhaps asking the database for rows, and builds a response. The client draws the result. Each hop costs time: a few milliseconds locally, over a hundred if the server is on another continent.

A key property of the usual web design is that the server is stateless between requests: it does not remember who you are from one request to the next unless the request itself carries that information. This sounds like a limitation but is a gift. Any one of ten identical servers can answer any request, so you can add more servers when traffic rises, and replace a crashed one without anyone losing their place. State lives in the database, not in the server's memory.

Why not let the client talk to the database directly? Because the client is in the hands of users and cannot be trusted. Anyone can read what an app sends, edit it, and replay it. The server is the place where rules are enforced: who may see which order, how much a delivery costs, whether a coupon is valid. Anything checked only on the client is only a suggestion.

GET /restaurants?city=pune HTTP/1.1
Host: api.example.com
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json

[{"id": 12, "name": "Spice Route", "open": true}]
A request line, headers, then a response with a status code and a body.
Question 1

Why can any of several identical stateless servers answer a request?

Question 2

Why enforce rules on the server rather than only in the app?

Your turn

Describe in order what happens when you open a food app and see a list of restaurants. Include at least four steps.

Stuck? Start with the name lookup and end with drawing the screen.

What to remember

  1. A client asks; a server answers over a request and response.

  2. DNS turns names into addresses before the request begins.

  3. Stateless servers are easy to copy and replace; state lives in the database.

  4. The server enforces rules because the client cannot be trusted.

  5. Every network hop costs time.