Web Architecture, Protocols & Rendering

The HTTP request cycle, statelessness, rendering location and scaling vocabulary.

4 lessons · 11 past questions · 23 marks in the papers collected here

Open the interactive lessons →Web Architecture, Protocols & Rendering past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. The request cycle and HTTP methods
  2. Statelessness and cookies
  3. Server-side and client-side rendering
  4. Cloud models and scaling

1. The request cycle and HTTP methods

Find the server, ask it, get an answer, draw it.

the steps from typing a URL to seeing the page, and what GET, HEAD, POST, PUT and DELETE mean

The question this lesson answers. You type an address and press Enter. What happens, in order, before the page appears?

Picture it

Ordering by post: find the address, send the request, then open the parcel that comes back.

A URL such as https://example.com/home.html names a host (example.com) and a resource (/home.html). Computers on the internet are reached by IP address, so the name must first be turned into an address by the DNS (Domain Name System).

Why it works this way. Computers reach each other by number, so the name must be turned into an address before any request can be sent.

HTTP methods

MethodAsks the server toResponse has a body?
GETsend a resourceyes
HEADsend only the headers GET would sendno
POSTaccept new data (a form, JSON)usually
PUTstore or replace a resourceusually
DELETEdelete a resourceusually
GET versus HEAD

GET retrieves a resource: status line, headers and body. HEAD is identical except the server sends no body, only the headers. HEAD is used to check whether something exists or has changed without downloading it.

HEAD has the same headers but no body

from flask import Flask
app = Flask(__name__)

@app.route("/page")
def page():
    return "Hello there"

c = app.test_client()
g, h = c.get("/page"), c.head("/page")
print(g.status_code, len(g.data), g.headers["Content-Length"])
print(h.status_code, len(h.data), h.headers["Content-Length"])

Worked example: Ordering the steps

Problem.

Put these in order: (P) server responds, (Q) DNS lookup, (R) browser displays, (S) browser sends request.

Idea.

Each step needs the output of the one before it.

  1. The request needs an IP address, so DNS (Q) is first.
  2. With the address, the browser sends the request (S).
  3. The server responds (P).
  4. Only then can the browser display the page (R).

Answer.

Q, S, P, R

Common mistake.

Putting the request first: it has nowhere to go without an address.

Worked example: HEAD and POST

Problem.

Statement 1: HEAD returns the headers a GET would, without the body. Statement 2: POST is meant only for reading a resource and cannot send data.

Idea.

Match each method to its job.

  1. HEAD is GET without the body: true.
  2. POST sends data to the server, usually to create or change something: false.

Answer.

Only statement 1

Common mistake.

Mixing up which method carries a body.

Notice

HTTPS is HTTP sent through an encrypted connection (TLS). The steps are the same; a secure handshake is added before the request.

The six parts of a URL. Every exam URL can be cut into the same pieces. The browser uses the host and port to find the server, sends the path and query string in the request, and keeps the fragment (after #) to itself: the server never sees it.

https://example.com:8443/shop/items?id=7&sort=price#reviews

PartValueUsed by
schemehttpsthe browser: which protocol (and encryption)
hostexample.comDNS, to find the server's address
port8443which program on that machine (default 443 for https, 80 for http)
path/shop/itemsthe server's routes
queryid=7&sort=pricethe server (request.args in Flask)
fragmentreviewsthe browser only: jump to part of the page

Worked example: What reaches the server?

Problem.

A user opens http://127.0.0.1:5000/user/7?tab=info#top.

Idea.

Path and query travel; the fragment stays in the browser.

  1. Port 5000 picks the Flask program.
  2. Flask sees the path /user/7 and request.args = {tab: info}.
  3. #top is never sent.

Answer.

Path /user/7 and query tab=info; not #top

Common mistake.

Expecting request.args to contain top: the fragment never leaves the browser.

Headers: the labels on every message. Both requests and responses carry headers: short name–value lines before the body. A few appear in almost every exam question, because they explain what the browser does next.

Headers you will meet

HeaderSent bySays
Hostbrowserwhich site on this server is wanted
User-Agentbrowserwhich browser is asking
Cookiebrowsercookies stored for this site
Content-Typeboththe format of the body, such as text/html or application/json
Content-Lengthboththe size of the body in bytes
Locationserverwhere to go next (redirects)
Set-Cookieservera cookie to store
Cache-Controlserverwhether and how long the response may be reused
@app.route("/")
def h():
    return "hi"          # Content-Type: text/html; charset=utf-8, Content-Length: 2

@app.route("/j")
def j():
    return {"a": 1}       # Content-Type: application/json, Content-Length: 8

Status codes by family

CodePhraseMeans
200 / 201 / 204OK / Created / No Contentit worked
301 / 302 / 304Moved Permanently / Found / Not Modifiedlook elsewhere, or use your cached copy
400 / 401 / 403Bad Request / Unauthorized / Forbiddenthe client's request is wrong or not allowed
404 / 405Not Found / Method Not Allowedno such path / wrong method for it
500 / 503Internal Server Error / Service Unavailablethe server failed or is overloaded

Worked example: The name cannot be found

Problem.

The browser cannot turn a host name into an address. Is an HTTP status code such as 404 returned?

Idea.

A status code comes from a web server.

  1. The lookup fails before any request is sent.
  2. No server receives anything.
  3. So no server can answer with a status.

Answer.

No: the browser shows its own error.

Common mistake.

Calling it a 404.

Tips and tricks
  • Order the steps: DNS, request, server work, response, display.
  • HEAD is GET without the body.
  • A status starting with 4 is the client's fault, 5 is the server's.
Memory line

Name to address, request, response, display.

Method for any exam question

StepDo this
1Resolve the name.
2Send the request with a method and path.
3Read the status code.
4Draw the body, if there is one.

2. Statelessness and cookies

HTTP has no memory; a cookie is a note the browser hands back every time.

why the server forgets you between requests, and how cookies let a site recognise you

The question this lesson answers. If the web forgets you after every request, how does a site know you are still logged in?

Stateless

A stateless server keeps no information about the client between requests. Each request must carry everything the server needs. HTTP is stateless by design: it makes servers simpler and easier to scale.

Why it works this way. A server that keeps no memory can handle each request on its own, which makes it easy to add more servers. The memory is carried by the browser instead.

Picture it

A stateless server is a shop assistant who forgets every customer the moment they leave. A cookie is a loyalty card the shop gives you; you show it each visit and the assistant knows who you are. The analogy stops working here: you can read and delete the card (cookies live in your browser).

Cookie

A cookie is a small name–value pair the server sends with Set-Cookie; the browser stores it and sends it back in the Cookie header with later requests to that site. Cookies let a web app recognise users and store things like login status, language or location preferences.

Setting and reading a cookie in Flask

from flask import Flask, request, make_response
app = Flask(__name__)

@app.route("/set")
def set_lang():
    r = make_response("saved")
    r.set_cookie("lang", "ta")
    return r

@app.route("/hello")
def hello():
    return "lang=" + request.cookies.get("lang", "none")

c = app.test_client()
print(c.get("/hello").data.decode())
c.get("/set")
print(c.get("/hello").data.decode())

Worked example: Two statements about cookies

Problem.

S1: the browser stores a cookie and sends it back with later requests to that site. S2: the server can read the browser's cookies even when the browser does not send them.

Idea.

The server only sees what a request carries.

  1. S1 is how cookies work: true.
  2. S2 would need the server to reach into the browser: false.

Answer.

Only S1

Common mistake.

Thinking the server owns the stored cookie.

Worked example: Why any server can answer

Problem.

Two requests from one user reach two different servers. Neither server remembers anything about users, and each request carries a login token.

Idea.

A stateless server relies on what the request carries, not on memory.

  1. Server 2 never saw the first request.
  2. The token in the second request identifies the user.
  3. So requests can go to any server, which makes adding servers easy.

Answer.

The request itself carries the needed information

Common mistake.

Believing the first server must pass its memory to the second.

A cookie's round trip. The server asks the browser to store a cookie by sending a Set-Cookie header. From then on, the browser adds that cookie to every request to the same site, and the server reads it (request.cookies in Flask). This is how a stateless protocol remembers a user.

Definition

Flask's session is a dictionary saved in a signed cookie. Flask signs it with app.secret_key, so the user can read it but not change it without breaking the signature. With a secret key, session["n"] counts 1, 2 across requests; without one, using the session raises RuntimeError.

Worked example: Cookies and statelessness

Problem.

A site keeps you logged in with a cookie. Does that mean HTTP now remembers you?

Idea.

Look at who supplies the information.

  1. Each request is still handled on its own.
  2. The browser sends the cookie again every time.
  3. The server recognises you from what that request carries.

Answer.

No: the protocol stays stateless.

Common mistake.

Saying cookies make HTTP stateful.

Tips and tricks
  • Stateless describes the protocol; a site can still remember you with cookies or sessions.
  • Ask who stores it: a cookie lives in the browser.
  • Reject options that say HTTP itself remembers earlier requests.
Memory line

The server forgets; the browser reminds.

Method for any exam question

StepDo this
1Ask what the server stored.
2Ask what the browser sent back.
3Without a cookie or similar, requests are strangers.

3. Server-side and client-side rendering

SSR sends a finished page; CSR sends a skeleton and builds the page in the browser.

where the page's HTML is built: on the server (SSR) or in the browser (CSR)

The question this lesson answers. Who builds the page you see: the server or your browser?

Picture it

Furniture delivered assembled (server rendering) or as a flat pack you assemble at home (client rendering).

Two places to build a page: browser asks for a page, then server rendering: full HTML arrives, then client rendering: skeleton and script arrive, then the browser shows the result

SSR and CSR

Server-side rendering (SSR): the server builds the complete HTML for each request (Flask + Jinja2 templates) and sends it ready to display. Client-side rendering (CSR): the server sends a nearly empty HTML page plus JavaScript; the browser runs the script, fetches data (usually JSON) and builds the page (the DOM) itself.

Why it works this way. The work of turning data into HTML must happen somewhere. Doing it on the server sends a readable page; doing it in the browser sends data and a program.

SSR versus CSR

SSR (e.g. Flask + Jinja2)CSR (JS + JSON API)
HTML arrivescompletenearly empty skeleton
First page loadfast: content is already thereslower: script must run and fetch
Search engines (SEO)easy to readharder: content appears only after JS
Server work per pagehigher: builds HTMLlower: sends data, browser renders
Later updatesoften a new pagesmall updates without reload

The same data, rendered two ways

from flask import Flask, render_template_string, jsonify
app = Flask(__name__)
items = ["tea", "milk"]

@app.route("/ssr")
def ssr():
    return render_template_string("<ul>{% for i in items %}<li>{{ i }}</li>{% endfor %}</ul>", items=items)

@app.route("/api")
def api():
    return jsonify(items)

c = app.test_client()
print(c.get("/ssr").data.decode())
print(c.get("/api").data.decode().strip())

Worked example: Which rendering fits?

Problem.

A news site wants text visible quickly on slow phones and readable by search engines.

Idea.

Server-side rendering sends finished content.

  1. With SSR the HTML already contains the article.
  2. The phone does not need to run script and fetch data before showing text.
  3. Search engines receive the text directly.

Answer.

Server-side rendering

Common mistake.

Claiming SSR means no request is ever made again.

Worked example: Two statements

Problem.

S1: in CSR the browser downloads data and builds the page with JavaScript. S2: in SSR the server never sends HTML, only JSON.

Idea.

Ask where the HTML is built.

  1. CSR builds it in the browser: S1 true.
  2. SSR builds HTML on the server and sends it: S2 false.

Answer.

Only statement 1

Common mistake.

Mixing up the two models.

Choosing where to render. The choice is about who does the work and when the user first sees content. With server-side rendering the first response is already a full page. With client-side rendering the first response is small, then JavaScript fetches data and builds the page, so later updates are fast without full reloads.

SSR and CSR side by side

Server-side (Flask + Jinja2)Client-side (JavaScript + an API)
First responsefull HTML pageHTML skeleton + script
First content visibleas soon as the HTML arrivesafter the script runs and the data arrives
Search enginesread the content directlymay see an empty skeleton
Later updatesa new page requestfetch JSON, update part of the page
Server's jobbuild HTML for each requestserve JSON from an API

Worked example: Which statement is false?

Problem.

(A) In CSR the browser builds the page with JavaScript. (B) In SSR the server sends complete HTML. (C) CSR needs no server at all. (D) SSR pages can still include JavaScript.

Idea.

CSR still needs a server for the files and the data.

  1. A and B are the definitions.
  2. D is true: a rendered page may run scripts.
  3. C is false: the data comes from an API on a server.

Answer.

C

Common mistake.

Reading client-side as server-free.

Worked example: Using JavaScript is not CSR

Problem.

A Flask app returns a complete HTML table and also a script that sorts it on click. How is the table rendered?

Idea.

Ask where the content was first built.

  1. The rows arrive inside the HTML.
  2. The script only changes the order later.

Answer.

Server-side rendered.

Common mistake.

Answering CSR because the page contains JavaScript.

Tips and tricks
  • Ask where the HTML is built: on the server or in the browser.
  • Search engines and slow devices favour server rendering.
  • Updating part of a page without a reload points to client-side work.
Memory line

SSR sends a page; CSR sends the parts.

Method for any exam question

StepDo this
1Look at what arrives first.
2Full content means SSR.
3An empty shell plus script means CSR.

4. Cloud models and scaling

Who manages what, bigger or more machines, strict or relaxed consistency, spares or copies.

SaaS, PaaS, IaaS; scaling up and out; ACID and BASE; redundancy and replication

The question this lesson answers. The statements sound alike: how do you tell service models, scaling and database guarantees apart?

Picture it

A busy shop can hire a stronger worker (scale up) or more workers (scale out).

Growing a system: load rises, then scale up: a bigger machine, then scale out: more machines, then share requests between them

Cloud service models

ModelProvider givesYou manageExample use
IaaSmachines, storage, networkOS, runtime, server, database, apprent a virtual machine
PaaSOS, runtime, web server, databaseyour code onlydeploy a Flask app without managing servers
SaaSthe whole applicationnothing; you use itweb email, online docs

Why it works this way. Each pair answers a different question: who manages what, whether one machine grows or more are added, and how fresh the data must be.

Scaling and consistency

TermMeaningTypical example
Scale up (vertical)make one machine biggeradd RAM, faster CPU
Scale out (horizontal)add more machinesmore servers behind a load balancer
ACIDatomic, consistent, isolated, durable transactionsbank and financial transactions
BASEbasically available, soft state, eventually consistentsocial media feeds

Redundancy versus replication

RedundancyReplication
Whatspare components that can take overcopies of the same data or service on several machines
Main goalkeep working when a part failsdata survives the loss of a copy; load can be shared
Improves speed?not by itselfcan, by spreading reads

Worked example: Which cloud model

Problem.

A college signs in to a ready-made video-meeting service in the browser. It installs nothing and writes no code.

Idea.

Ask what the customer still has to supply.

  1. IaaS would leave the operating system and software to the college.
  2. PaaS would leave the code to the college.
  3. Here the finished application is provided.

Answer.

SaaS

Common mistake.

Choosing PaaS because it runs "in the cloud".

Worked example: Is one server enough?

Problem.

Each server has a 1 Gbps connection; the shared backbone has 10 Gbps. The app serves 4,000 requests per second of 100 KB each (1 KB = 1000 B), with little CPU work.

Idea.

Compare the need with one server and with the shared link.

  1. Bytes per second: $4000 \times 100{,}000 = 4 \times 10^8$.
  2. Bits per second: $\times 8 = 3.2$ Gbps.
  3. One server carries only 1 Gbps, so one is not enough; the backbone's 10 Gbps is.
  4. At least $\lceil 3.2 / 1 \rceil = 4$ servers: scaling out helps because the backbone has room.

Answer.

3.2 Gbps; scale out to at least 4 servers

Common mistake.

Scaling out without checking the shared link, or stopping at 3 servers.

Trap

Read redundancy and replication questions word by word: redundancy is about surviving failures, replication is about copies (which also protect data and can share load). "Redundancy improves performance" is not its purpose.

Why two servers are much better than one. If one server is up 99% of the time and two independent servers stand in for each other, the site is down only when both are down: 0.01 × 0.01 = 0.0001. Availability rises from 99% to 99.99%, from about 87.6 hours of downtime a year to about 53 minutes.

Availability arithmetic

SetupDown fractionAvailabilityDowntime per year
one server at 99%0.0199%87.6 hours
two independent servers at 99%0.01 × 0.01 = 0.000199.99%about 52.6 minutes

Ways to grow

Vertical scalingHorizontal scaling
Howa bigger machine (more CPU, RAM)more machines behind a load balancer
Limitthe biggest machine you can buyhow well the app runs as many copies
One failuretakes the site downothers keep serving (redundancy)
Needsno code changestateless servers, shared data (replication)

Worked example: Pick the term

Problem.

A shop copies its database to a second region so that reads are fast there and the data survives if the first region fails.

Idea.

Copies of the same data in several places is replication.

  1. The data is copied: replication.
  2. No machine got bigger: not vertical scaling.

Answer.

Replication (which also gives redundancy)

Common mistake.

Calling it horizontal scaling: that is about adding machines that share the work.

Who manages what in the cloud. The three service models differ in how much of the stack you look after yourself. Moving from IaaS to SaaS, the provider takes over more and you control less.

Your job versus the provider's

LayerIaaSPaaSSaaS
the application and its datayouyouprovider
runtime (Python, libraries)youproviderprovider
operating systemyouproviderprovider
machines, network, storageproviderproviderprovider
examplea rented virtual machinean app platform you push code toweb email or a ready CRM

How a load balancer shares work. Horizontal scaling needs something in front of the servers that hands each request to one of them. The simplest rule is round robin: requests go to A, B, C, then A again. With three servers, seven requests are shared out as A B C A B C A.

Worked example: Who serves request 7?

Problem.

Round robin over servers A, B, C, starting with A.

Idea.

Requests cycle through the servers in order.

  1. Order: A B C A B C A.
  2. The 7th is A.
  3. A takes requests 1, 4 and 7: three.

Answer.

A; three requests

Common mistake.

Assuming each server takes the same number regardless of the total.

Consistency after replication

Strong consistencyEventual consistency
After a writeevery copy shows it at oncecopies catch up after a short delay
Costslower writes (copies must agree)fast writes
Fitsbank balances, seat bookinglikes, view counts, feeds

Worked example: More machines, but one database

Problem.

An app moves from one web server to four, all using one database server. What has been scaled out?

Idea.

Check each tier separately.

  1. The web tier went from one machine to four.
  2. The database is still one machine.

Answer.

Only the web tier.

Common mistake.

Saying the whole system was scaled out.

Tips and tricks
  • Bigger machine is up; more machines is out.
  • Ask what you manage yourself: most in IaaS, only code and data in PaaS, nearly nothing in SaaS.
  • Money transfers call for ACID.
Memory line

Platform means bring code; software means just use it.

Method for any exam question

StepDo this
1Decide which question the statement is about.
2Pick the matching pair.
3Test the claim against that pair only.

Practise this topic →

Weeks covering this topic

Other MAD 1 topics