Courses / Frontend System Design, with JavaScript Foundations / Chapter 12
Module 5 · Performance and APIs · Chapter 12 of 21
API Styles, Protocols and Data Formats
Builds on Promises, Async Code and the Browser Event Loop, Frontend Fundamentals: Components, State, Data and Rendering and Performance and Optimisation. Next up: Frontend Design Patterns and Architectures.
Part 1 · REST over HTTP
Resources and methods
Every screen that shows live data depends on how the browser talks to its server. The choice of API style decides how many round trips a screen needs and what a retry does.
REST (representational state transfer) is the style most web APIs follow: the server exposes resources, things such as a product or an order, each with its own URL, and the client acts on them with the ordinary HTTP methods. The server keeps no conversation with the client between requests. Every request carries what the server needs.
A URL names a resource, a method says what to do with it, and the status code in the reply says what happened. That is the whole vocabulary. The meaning of each method comes from the HTTP semantics specification, RFC 9110, and two of its ideas decide how a frontend may behave when something goes wrong.
A method is safe when the client is not asking for any change: it is essentially read-only. A method is idempotent when sending the same request several times has the same intended effect on the server as sending it once. Idempotency is what makes a retry safe. If a tap on a flaky mobile network gets no answer, the client does not know whether the server received the request. It can only resend if resending does no harm.
| Method | Used to | Safe | Idempotent |
|---|---|---|---|
| GET | read a resource or a list | yes | yes |
| HEAD | read only the headers of a GET | yes | yes |
| OPTIONS | ask what is allowed | yes |
The same request, twice
The lab server keeps seven grocery products in memory and handles POST, PUT and DELETE on them. It is written with Express 5. The part to watch is how each handler answers. The listing handler is used again in the pagination page.
import express from 'express' const app = express() app.use(express.json()) const names = ['Masala tea 250 g', 'Table butter 100 g', 'Rice 5 kg', 'Toor dal 1 kg', 'Ghee 500 ml', 'Poha 500 g', 'Jaggery 1 kg'] const products = new Map( names.map((name, i) => [i + 1, { id: i + 1, name }])) let nextId = names.length + 1 const newestFirst = () => [...products.values()].sort((a, b) => b.id - a.id) const encode = (id) => Buffer.from(String(id)).toString('base64url') const decode = (s) => Number(Buffer.from(s, 'base64url').toString())
rest-server.mjs: set-up, with seven products in a map.
app.get('/products', (req, res) => { const limit = Number(req.query.limit ?? 3) const all = newestFirst() if ('after' in req.query) { // cursor mode const after = req.query.after ? decode(req.query.after) : Infinity const items = all.filter((p) => p.id < after).slice(0, limit) const last = items.at(-1) const more = last && all.some((p) => p.id < last.id) const nextCursor = more ? encode(last.id) : null return res.json({ items, nextCursor }) } const offset = Number(req.query.offset ?? 0) // offset mode const items = all.slice(offset, offset + limit) res.json({ items, total: all.length }) })
rest-server.mjs: listing, in two pagination modes.
app.post('/products', (req, res) => { const p = { id: nextId++, name: req.body.name } products.set(p.id, p) res.status(201).location(`/products/${p.id}`).json(p) }) app.put('/products/:id', (req, res) => { const p = { id: Number(req.params.id), name: req.body.name } products.set(p.id, p) res.json(p) }) app.delete('/products/:id', (req, res) => { const existed = products.delete(Number(req.params.id)) res.status(existed ? 204 : 404).end() }) app.listen(55800, '127.0.0.1')
rest-server.mjs: create, replace and delete.
The client below sends each request twice and prints the status, the Location header and the body.
const base = 'http://127.0.0.1:55800' const call = async (method, path, body) => { const r = await fetch(base + path, { method, headers: body ? { 'content-type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined, }) return { status: r.status, where: r.headers.get('location'), text: await r.text() } } const show = (label, r) => console.log(label.padEnd(12), r.status, r.where ?? '', r.text) const sugar = { name: 'Sugar 1 kg' } show('POST #1', await call('POST', '/products', sugar)) show('POST #2', await call('POST', '/products', sugar)) const rice = { name: 'Rice 10 kg' } show('PUT 3 #1', await call('PUT', '/products/3', rice)) show('PUT 3 #2', await call('PUT', '/products/3', rice)) show('DELETE 4 #1', await call('DELETE', '/products/4')) show('DELETE 4 #2', await call('DELETE', '/products/4'))
rest1.mjs: the client.
Status codes the client acts on
A status code belongs to a class: 2xx means success, 3xx redirection, 4xx the client's request was wrong, 5xx the server failed. Client code branches on the class first and on the exact code second.
| Code | Meaning | What the client does |
|---|---|---|
| 200 OK | the request worked, body follows | render the data |
| 201 Created | a new resource exists, Location names it | store the new URL or id |
| 400 Bad Request | the request is malformed | show a form error, do not retry as is |
| 401 Unauthorized | no valid credentials | send the user to sign in |
| 403 Forbidden | known user, not allowed | show a permission message |
| 404 Not Found | no such resource | show an empty state |
| 409 Conflict | clashes with the current state | refresh and ask the user to retry |
| 412 Precondition Failed | a condition such as If-Match was false | reload the latest version |
| 429 Too Many Requests | the client is sending too fast | wait, then retry with backoff |
| 500 and 503 | the server failed or is unavailable | show an error, retry safe requests |
Offset and cursor pagination
A list endpoint cannot return every row, so the client asks for a page. There are two common ways to say which page. With offset pagination the client sends how many rows to skip: ?limit=3&offset=3. With cursor pagination the client sends a marker for the last row it saw, and the server returns what comes after it.
The difference shows when the list changes between two reads, which on a live feed is always. The lab server lists products newest first. The script reads one page, adds a product, then reads the next page, once with offsets and once with a cursor. The cursor is the last id, encoded so that clients treat it as opaque.
const base = 'http://127.0.0.1:55800' const get = async (path) => (await fetch(base + path)).json() const ids = (page) => page.items.map((p) => p.id).join(',') const add = (name) => fetch(base + '/products', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name }), }) console.log('-- offset: a product is added between two reads') const o1 = await get('/products?limit=3&offset=0') console.log('page 1 ids:', ids(o1)) await add('Salt 1 kg') const o2 = await get('/products?limit=3&offset=3') console.log('page 2 ids:', ids(o2)) console.log('-- cursor: a product is added between two reads') const c1 = await get('/products?limit=3&after=') console.log('page 1 ids:', ids(c1), 'cursor', c1.nextCursor) await add('Pepper 100 g') const c2 = await get('/products?limit=3&after=' + c1.nextCursor) console.log('page 2 ids:', ids(c2), 'cursor', c2.nextCursor) const c3 = await get('/products?limit=3&after=' + c2.nextCursor) console.log('page 3 ids:', ids(c3), 'cursor', c3.nextCursor)
rest2.mjs: two pagination styles, a product added in between.
-- offset: a product is added between two reads page 1 ids: 7,6,5 page 2 ids: 5,4,3 -- cursor: a product is added between two reads page 1 ids: 8,7,6 cursor Ng page 2 ids: 5,4,3 cursor Mw page 3 ids: 2,1 cursor null
Output (Node 24)
With offsets, page 1 showed 7, 6, 5. The new product 8 pushed every row one place down, so offset 3 started again at 5, and the reader sees product 5 twice. If a product had been deleted instead, one would be skipped. With the cursor, the second page began after the last id the client had seen, so the new product at the top changed nothing, and the last page ended with a null cursor.
Part 2 · GraphQL
One endpoint, a typed schema
GraphQL is a query language for APIs and a runtime that runs the queries. Its specification is a deliverable of the GraphQL Specification Project, and spec.graphql.org publishes it in dated editions: the page lists September 2026 as the latest release, with October 2021 and June 2018 before it. The clauses used here (the three operation types, selection sets, validation, errors) have been in the specification for years. Instead of many URLs, a server usually exposes one endpoint. The client sends a query that names the fields it wants, and the reply has the same shape.
Two problems of resource-per-URL APIs explain why it exists. Over-fetching is receiving more than the screen needs: a product row with twenty fields when the card shows two. Under-fetching is needing several round trips: the product, then its seller, then the seller's other products. On a slow mobile network each round trip costs time, so a screen that needs three requests in a chain is slow before any single response is large.
The server describes everything it can answer in a schema: types, their fields, and the entry points. There are three kinds of operation. A query reads. A mutation changes data and returns the changed object. A subscription keeps a connection open and pushes results when something changes. The schema is the contract, and tools use it to check a query before it runs.
import { buildSchema, graphql } from 'graphql' import { inspect } from 'node:util' const schema = buildSchema(` type Seller { id: ID!, name: String!, city: String! } type Product { id: ID! name: String! pricePaise: Int! stock: Int! seller: Seller! } type Query { product(id: ID!): Product } type Mutation { setStock(id: ID!, stock: Int!): Product } `)
gql.mjs: the schema.
The schema is written in the GraphQL schema language. A ! after a type means the field is never null. The next block holds the data and the functions that answer each entry point. The script runs in Node with graphql 17 and needs no server: the library parses, validates and executes a query string directly.
const seller = { id: 's1', name: 'Kaveri Traders', city: 'Mysuru' } const db = [ { id: '1', name: 'Masala tea 250 g', pricePaise: 18000, stock: 40, seller }, { id: '2', name: 'Ghee 500 ml', pricePaise: 36500, stock: 12, seller }, { id: '3', name: 'Poha 500 g', pricePaise: 5500, stock: 0, seller }, ] const rootValue = { product: ({ id }) => db.find((p) => p.id === id), setStock: ({ id, stock }) => { if (stock < 0) throw new Error('stock cannot be negative') const p = db.find((x) => x.id === id) if (p) p.stock = stock return p }, } const run = async (label, source, variableValues) => { const r = await graphql({ schema, source, rootValue, variableValues }) console.log(`# ${label}`) console.log(inspect(JSON.parse(JSON.stringify(r)), { breakLength: 68, depth: 6 })) return r }
gql.mjs: data, resolvers and a helper that runs a query.
Asking for exactly what the screen needs
The queries below run against that schema. The comments say what each one shows. Because the output is a JavaScript object, Node prints it with util.inspect; on the wire the same data travels as JSON.
await run('only what the screen shows', '{ product(id: "2") { name pricePaise } }') await run('nested and aliased, one round trip', `{ tea: product(id: "1") { name seller { name city } } ghee: product(id: "2") { stock } }`) await run('variables', 'query Item($id: ID!) { product(id: $id) { name stock } }', { id: '3' }) await run('a mutation returns the changed object', 'mutation { setStock(id: "3", stock: 25) { id stock } }') await run('error inside a field: data and errors together', 'mutation { setStock(id: "3", stock: -1) { id stock } }') await run('invalid query: rejected before any resolver runs', '{ product(id: "1") { name colour } }')
gql.mjs: the queries.
# only what the screen shows
{
data: { product: { name: 'Ghee 500 ml', pricePaise: 36500 } }
}
# nested and aliased, one round trip
{
data: {
tea: {
name: 'Masala tea 250 g',
seller: { name: 'Kaveri Traders', city: 'Mysuru' }
},
ghee: { stock: 12 }
}
}
# variables
{ data: { product: { name: 'Poha 500 g', stock: 0 } } }
# a mutation returns the changed object
{ data: { setStock: { id: '3', stock: 25 } } }Output (Node 24), queries 1 to 4
# error inside a field: data and errors together
{
errors: [
{
message: 'stock cannot be negative',
locations: [ { line: 1, column: 12 } ],
path: [ 'setStock' ]
}
],
data: { setStock: null }
}
# invalid query: rejected before any resolver runs
{
errors: [
{
message: 'Cannot query field "colour" on type "Product".',
locations: [ { line: 1, column: 27 } ]
}
]
}Output (Node 24), the two error cases
const one = '{ product(id: "2") { name pricePaise } }' const sent = (await graphql({ schema, source: one, rootValue })).data console.log('# bytes for one screen') const size = (x) => Buffer.byteLength(JSON.stringify(x)) console.log('whole product object:', size(db[1])) console.log('selection set :', size(sent))
gql.mjs: the size of one reply, whole object against selection.
# bytes for one screen whole product object: 122 selection set : 53
Output (Node 24), bytes for one screen
The first query asks for two fields and receives two. The second is one request for two products, with the seller nested inside one of them and an alias (tea, ghee) so that both can sit in the same reply under different names. A REST API would need at least three calls for the same screen. The third query shows variables: the query text stays fixed and only the values change, which lets a server recognise and cache a query it has seen before.
Errors in a GraphQL reply
GraphQL replies usually come with a 200 status even when something went wrong, because the transport worked. Failures are reported inside the body. The run shows two kinds. A field error happens while a resolver runs: the reply has an errors list with a path, and data is null at that field, while other fields of the same query can still succeed. A validation error happens before anything runs: asking for a field the schema does not have, such as colour, is rejected with the position of the mistake and no resolver is called.
A client therefore checks errors on every reply, not just the HTTP status, and must decide what to show when part of a screen has data and another part has an error.
The price of one endpoint
Caching is the price of the single endpoint. With REST, a GET of /products/2 can be stored by the browser, a CDN and a proxy, because the URL identifies the content. A GraphQL query is usually sent as a POST to one URL, and HTTP caches do not store POST replies by default. Clients solve this themselves. They keep a normalised cache in memory, storing each object once under its type and id, so that a mutation returning id: 3 updates every screen that shows it. Servers can add persisted queries, where the client sends a short id for a query the server already knows, which makes a GET with a small URL possible.
| REST | GraphQL | |
|---|---|---|
| Shape of the reply | fixed by the server | chosen by the client |
| Round trips for a nested screen | often several | usually one |
| HTTP caching | works by URL | needs a client cache or persisted queries |
| Errors | status codes | 200 with an errors list |
| Contract | documents, optional schema | the schema itself |
| Risk | over- and under-fetching | costly queries: limit depth and cost |
The last row matters for the server. A client can write a deeply nested query that is cheap to type and costly to run, so production servers limit depth or cost. The news feed chapter uses the connection shape that GraphQL APIs follow for cursor pagination.
A GraphQL reply arrives with status 200 but contains an errors list. What should the client do?
Part 3 · Binary formats and gRPC-Web
Why a binary format
JSON is text. It is easy to read and every language parses it, but every message repeats its field names, writes numbers as digits and quotes every string. A binary format drops the names, packs numbers into as few bytes as it can and needs a schema known to both sides. The best known is Protocol Buffers, or protobuf, from Google.
In protobuf you describe a message in a .proto file. Each field has a type, a name and a field number. On the wire the name is gone, and only the number is sent. A field is written as a tag, which is the field number shifted left by three bits and combined with a wire type, followed by the value. Wire type 0 is a varint and wire type 2 is a length-delimited value such as a string.
A varint stores an integer in as many bytes as it needs. Each byte carries seven bits of the number, lowest bits first, and the top bit is 1 when another byte follows. So 1 takes one byte and 300 takes two. The script below writes the schema, builds a varint by hand to show the rule, and encodes one message with the protobufjs library.
import protobuf from 'protobufjs' import { gzipSync } from 'node:zlib' const { root } = protobuf.parse(` syntax = "proto3"; message Product { uint32 id = 1; string name = 2; uint32 price_paise = 3; uint32 stock = 4; bool in_stock = 5; } `) const Product = root.lookupType('Product') // a varint by hand: 7 bits per byte, low bits first, // the top bit says "another byte follows" const varint = (n) => { const out = [] while (n > 127) { out.push((n & 127) | 128); n >>>= 7 } out.push(n) return out } const hex = (b) => [...b].map((x) => x.toString(16).padStart(2, '0')).join(' ') console.log('varint(1) =', hex(varint(1))) console.log('varint(300) =', hex(varint(300))) console.log('tag, field 1, wire type 0 =', (1 << 3) | 0) console.log('tag, field 2, wire type 2 =', (2 << 3) | 2)
proto.mjs: the schema, a varint made by hand and the tags.
const msg = { id: 2, name: 'Ghee 500 ml', pricePaise: 36500, stock: 12, inStock: true } const bytes = Product.encode(Product.create(msg)).finish() console.log('protobuf bytes:', hex(bytes)) console.log('protobuf size :', bytes.length, 'bytes') const asJson = { id: 2, name: 'Ghee 500 ml', price_paise: 36500, stock: 12, in_stock: true } console.log('JSON size :', JSON.stringify(asJson).length) const d = Product.decode(bytes) console.log('decoded :', d.name, d.pricePaise, d.inStock)
proto.mjs: one message, in protobuf and as JSON.
What the bytes say, and what compression changes
Read the first lines of the output. Varint 300 is ac 02: the low seven bits of 300 are 0101100, and the top bit is set to mean more follows, giving ac. The remaining bits give 02. The tag for field 1 with wire type 0 is 8, and for field 2 with wire type 2 it is 18, which is hex 12.
The encoded message begins 08 02 12 0b. That is field 1 equal to 2, then field 2 with a length of 11, then the eleven bytes of the string Ghee 500 ml, then the three other fields. The whole message is 23 bytes, and the same data as JSON is 76.
// fifty products const many = Array.from({ length: 50 }, (_, i) => ({ id: i + 1, name: `Item number ${i + 1}`, pricePaise: 1000 + i * 25, stock: i % 7, inStock: i % 7 > 0, })) const enc = (m) => Product.encode(Product.create(m)).finish() const encoded = many.map(enc) const text = JSON.stringify(many.map((m) => ({ id: m.id, name: m.name, price_paise: m.pricePaise, stock: m.stock, in_stock: m.inStock, }))) const size = (b) => Buffer.from(b).length console.log('50 items, protobuf:', Buffer.concat(encoded).length) console.log('50 items, JSON :', size(text)) const joined = Buffer.concat(encoded) console.log('gzip, protobuf :', gzipSync(joined).length) console.log('gzip, JSON :', gzipSync(text).length)
proto.mjs: fifty products, with and without gzip.
50 items, protobuf: 1209 50 items, JSON : 3941 gzip, protobuf : 433 gzip, JSON : 542
Output (Node 24)
Fifty products take 1,209 bytes as protobuf and 3,941 as JSON, but compression changes the comparison. Web servers normally compress text with gzip, and repeated field names compress very well. After gzip the protobuf is 433 bytes and the JSON is 542. Compressed JSON is only about a quarter larger than compressed protobuf here. Binary is not free either: you cannot read it in the network panel without tooling, and both sides need the schema.
These sizes come from this message and these values. A message of large numbers and few strings would show a different gap. Measure your own payload before choosing a format for size alone.
A protobuf schema must never reuse a field number for a different meaning, because an old client would decode new bytes under the old definition. Removed fields keep their numbers reserved. That rule, rather than size, is why schema-first formats suit long-lived APIs with many clients.
gRPC and gRPC-Web
gRPC is a remote procedure call system. The client calls a method on a generated stub, and a protobuf message travels over HTTP/2. It supports four call shapes: one request and one reply (unary), a stream of replies, a stream of requests, and streams in both directions. Services talk to each other this way because the generated code is fast and typed.
A page cannot speak gRPC directly. The gRPC-Web protocol notes give the reason: HTTP/2 framing is not directly exposed by browsers, and gRPC is built on it. gRPC-Web is a variation of the protocol that a browser can speak, and the project's own README states two limits you must plan around.
- It needs a proxy between the browser and the gRPC service that translates the two protocols. The README names Envoy as the default, and lists others.
- It supports unary calls and server streaming only. Client streaming and bidirectional streaming are not supported. Server streaming works only in the
grpcwebtextmode, where payloads are base64 text. Thegrpcwebmode, with binary payloads, supports unary calls only.
This lab cannot run a gRPC-Web proxy, so no gRPC-Web call is run here. The facts above come from the project's README. For a frontend choosing a style, the practical reading is this. gRPC-Web fits a company whose services already speak gRPC and who want typed clients generated from the same schema. It is a poor fit when the browser needs to send a live stream of its own, and a worse fit when the API is public and developers expect to call it from a terminal.
| JSON over REST | GraphQL | gRPC-Web | |
|---|---|---|---|
| Format on the wire | JSON text | JSON text | protobuf, binary or base64 |
| Contract | optional |
Part 4 · HTTP/1.1, HTTP/2 and HTTP/3
One meaning, three ways of carrying it
Methods, status codes and headers mean the same in every version of HTTP, and RFC 9110 defines them once. What changed between versions is how messages are carried between browser and server. That decides how many requests a page can have in flight, and so how a frontend should be built.
In HTTP/1.1 a connection carries one request at a time. The server must finish its answer before the next answer on that connection can start. To get some parallelism a browser opens several connections to the same host. A slow answer at the front of a connection holds up everything behind it, which is called head-of-line blocking.
The lab shows the limit in Chrome. A page fires twenty requests at once, and the server takes 300 ms to answer each. The server counts how many connections it sees.
import http from 'node:http' import { chromium } from 'playwright-core' const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe' let connections = 0 let requests = 0 const page = `<!doctype html><title>h1</title><script> window.run = async () => { const t0 = performance.now() const all = Array.from({ length: 20 }, (_, i) => fetch('/slow?i=' + i).then((r) => r.text())) await Promise.all(all) return Math.round(performance.now() - t0) } </script>` const server = http.createServer((req, res) => { if (req.url === '/') { res.setHeader('content-type', 'text/html; charset=utf-8') return res.end(page) } if (!req.url.startsWith('/slow')) { // favicon and the like res.statusCode = 204 return res.end() } requests++ setTimeout(() => res.end('ok'), 300) // each answer takes 300 ms }) server.on('connection', () => connections++)
h1.mjs: the server and the page it serves.
await new Promise((r) => server.listen(55801, '127.0.0.1', r)) const browser = await chromium.launch({ executablePath: CHROME }) const tab = await browser.newPage() await tab.goto('http://127.0.0.1:55801/') const ms = await tab.evaluate(() => window.run()) const proto = await tab.evaluate( () => performance.getEntriesByType('resource')[0].nextHopProtocol) console.log('requests to /slow :', requests) console.log('each request waits : 300 ms on the server') console.log('total time :', ms, 'ms') console.log('connections opened :', connections) console.log('nextHopProtocol :', proto) await browser.close() server.close()
h1.mjs: Chrome runs the page and prints the result.
HTTP/2 and HTTP/3
HTTP/2, defined in RFC 9113, keeps the same meanings and changes the wire. Messages are cut into binary frames, and each request and response is a numbered stream. Many streams share one connection, and frames from different streams are interleaved. That is multiplexing. Headers are compressed with a scheme called HPACK, which matters because cookies and other headers repeat on every request. RFC 9113 replaced the older RFC 7540.
Browsers speak HTTP/2 only over TLS, so this lab cannot show it in Chrome. Node can speak the cleartext form, which is enough to show streams sharing one connection. The client sends the same twenty slow requests.
import http2 from 'node:http2' let sessions = 0 let streams = 0 const server = http2.createServer() // cleartext, demo only server.on('session', () => sessions++) server.on('stream', (stream) => { streams++ setTimeout(() => { stream.respond({ ':status': 200 }) stream.end('ok') }, 300) // each answer takes 300 ms }) await new Promise((r) => server.listen(55802, '127.0.0.1', r))
h2c.mjs: a cleartext HTTP/2 server.
const client = http2.connect('http://127.0.0.1:55802') const t0 = performance.now() const one = (i) => new Promise((resolve) => { const req = client.request({ ':path': '/slow?i=' + i }) req.on('data', () => {}) req.on('end', resolve) req.end() }) await Promise.all(Array.from({ length: 20 }, (_, i) => one(i))) const ms = Math.round(performance.now() - t0) console.log('requests (streams) :', streams) console.log('each request waits : 300 ms on the server') console.log('total time :', ms, 'ms') console.log('connections (sessions):', sessions) client.close() server.close()
h2c.mjs: the same twenty requests over one connection.
requests (streams) : 20 each request waits : 300 ms on the server total time : 319 ms connections (sessions): 1
Output (Node 24)
Twenty streams, one connection, and a total close to a single 300 ms wait. Each script was run five times on this machine: the Chrome total over HTTP/1.1 ranged from 1,232 to 1,241 ms with six connections every time, and the Node total over cleartext HTTP/2 from 315 to 319 ms with one session. The two scripts use different clients, so treat the comparison as an illustration of the mechanism, from one machine, and not as a benchmark of the two protocols.
HTTP/2 still runs on TCP, which delivers bytes in order. If one packet is lost, TCP holds back everything behind it, including data that belongs to other streams. The blocking has moved from HTTP down to TCP. HTTP/3, defined in RFC 9114, removes it. It runs over QUIC, a transport built on UDP that has streams of its own, so a lost packet delays only the stream it belonged to. QUIC also includes TLS 1.3. HTTP/3 compresses headers with QPACK instead of HPACK, because HPACK assumes in-order delivery and QUIC does not provide it across streams.
What it changes for frontend code
A frontend developer rarely selects the protocol, since the CDN or server does. The effect is on the habits that were built around HTTP/1.1.
| Habit | On HTTP/1.1 | On HTTP/2 and HTTP/3 |
|---|---|---|
| Several hostnames for assets | helped, more connections | hurts, each host needs its own connection |
| One big bundle | fewer requests | still saves per-request cost, but one change invalidates the file |
| Many small files | queue behind six connections | cheap to request, but compress less well |
| Request priority | whatever order the browser queues | the browser can signal priority per stream |
Fewer, larger files remain a reasonable default. What disappeared is the penalty for splitting a bundle by route or component, which the performance chapter used. Do not drop bundling advice without measuring, because each request still costs headers and scheduling.
It also changes how you read a waterfall in the network panel. Under HTTP/1.1 a long queue of waiting requests is often the connection limit. Under HTTP/2, waiting usually means the server was slow or the browser judged the request less important.
Why did Chrome need about 1,240 ms for twenty requests that each take 300 ms on the server?
- HTTP/1.1 carries one request at a time per connection and Chrome used six connections.
- Twenty requests over six connections make four rounds of 300 ms.
What does HTTP/2 multiplexing do, and what problem remains?
Part 5 · Real-time transports
Four ways to get new data
Some screens must change without the user asking: a chat, a score, a reply that is being written. The browser cannot receive a request from the server, so every technique below is a way to get an answer out of the server at the moment it has one.
- Short polling: the client asks on a timer, say every second, and the server answers at once with whatever is new, possibly nothing.
- Long polling: the client asks, and the server holds the request open until it has something. The client asks again straight away.
- Server-sent events (SSE): one long-lived HTTP response that the server keeps writing to. The browser exposes it as
EventSource. Data flows from server to client only. - WebSocket: a connection that starts as HTTP, is upgraded, and then carries messages in both directions.
The lab server publishes three updates, at 1.2, 2.7 and 4.1 seconds, and four clients listen for six seconds. The script prints how many requests each one made and how long each update waited after it was published. The server and the clients are in one process, so the timings use one clock.
import http from 'node:http' import { WebSocketServer, WebSocket } from 'ws' const PORT = 55803 const base = `http://127.0.0.1:${PORT}` const events = [] // { n, at }: what the server published const waiting = new Set() // long-poll responses on hold const sse = new Set() // open event streams const stats = { poll: 0, long: 0, sse: 0, ws: 0 } const since = (url) => Number(url.searchParams.get('since')) const after = (n) => JSON.stringify(events.filter((e) => e.n > n))
compare.mjs: shared state, and two helpers.
const server = http.createServer((req, res) => { const url = new URL(req.url, base) if (url.pathname === '/poll') { stats.poll++ return res.end(after(since(url))) } if (url.pathname === '/long') { stats.long++ if (after(since(url)) !== '[]') return res.end(after(since(url))) return void waiting.add({ n: since(url), res }) } if (url.pathname === '/sse') { stats.sse++ res.writeHead(200, { 'content-type': 'text/event-stream' }) res.write(': hello\n\n') return void sse.add(res) } res.statusCode = 404 res.end() }) const wss = new WebSocketServer({ server, path: '/ws' }) wss.on('connection', () => stats.ws++) await new Promise((r) => server.listen(PORT, '127.0.0.1', r))
compare.mjs: the server side.
What the run shows
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`) ws.on('message', (d) => record('ws', JSON.parse(d))) await new Promise((r) => ws.on('open', r)) shortPolling(); longPolling(); eventStream() await pause(200) // let every client connect setTimeout(() => publish(1), 1200) setTimeout(() => publish(2), 2700) setTimeout(() => publish(3), 4100) await pause(6300) const row = (name, n, k) => console.log(name.padEnd(14), String(n).padStart(3), ' ', got[k].join(', ')) console.log('transport reqs update, delay in ms') row('short polling', stats.poll, 'poll') row('long polling', stats.long, 'long') row('SSE', stats.sse, 'sse') row('WebSocket', stats.ws, 'ws') process.exit(0)
compare.mjs: the WebSocket client, the schedule and the report.
transport reqs update, delay in ms short polling 6 #1 646, #2 184, #3 848 long polling 4 #1 1, #2 1, #3 1 SSE 1 #1 2, #2 2, #3 1 WebSocket 1 #1 2, #2 2, #3 1
Output (Node 24, one run; the delays vary a little)
Short polling made six requests for three updates. Each update waited for the next poll, so delays of about 650, 180 and 850 ms (another run gave 650, 174 and 831) are really the distance to the next tick. Shorten the interval and the delay shrinks, but the request count grows. Long polling made four requests, three answered and one waiting, and delivered each update in a millisecond or two. SSE and WebSocket made one request each, and also delivered at once.
Watch for how many messages each style needs for three updates
Read it as steps
The WebSocket handshake and the SSE reconnect
A WebSocket starts as an ordinary HTTP request that asks to switch protocols. The script below sends the handshake by hand over a raw socket against a local ws server, so that the exact bytes are visible. It also computes the Sec-WebSocket-Accept value from the key to confirm how it is made.
import net from 'node:net' import crypto from 'node:crypto' import { WebSocketServer } from 'ws' const wss = new WebSocketServer({ port: 55804, host: '127.0.0.1' }) const key = Buffer.from('0123456789abcdef').toString('base64') const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' const sock = net.connect(55804, '127.0.0.1', () => { sock.write([ 'GET /chat HTTP/1.1', 'Host: 127.0.0.1:55804', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Key: ${key}`, 'Sec-WebSocket-Version: 13', '', '', ].join('\r\n')) }) sock.once('data', (d) => { console.log(d.toString().trim().replace(/\r/g, '')) console.log('--') const sha = crypto.createHash('sha1').update(key + GUID) console.log('SHA-1(key + GUID), base64:', sha.digest('base64')) sock.destroy() wss.close() })
handshake.mjs: the upgrade request, written by hand.
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: BACScCJPNqyz+UBoqMH89VmURoA= -- SHA-1(key + GUID), base64: BACScCJPNqyz+UBoqMH89VmURoA=
Output (Node 24)
The server answered 101 Switching Protocols, and its accept value is the SHA-1 of the client's key plus a fixed GUID from RFC 6455, base64 encoded. After the switch, the connection carries WebSocket frames. RFC 6455 requires frames from a client to be masked and frames from a server not to be, so a browser handles that itself and you never see it. MDN adds that the WebSocket interface does not support backpressure: if messages arrive faster than the page can handle them, they pile up in memory or the page becomes unresponsive. On the sending side, bufferedAmount reports how much is still queued.
Watch for the 101 answer: after it the connection is not HTTP any more
Read it as steps
Streaming a reply with fetch, and stopping it
As the first chapter showed in the browser, EventSource takes only a URL and withCredentials, so a streamed reply that needs a POST body and a token, such as text from an AI model, is read with fetch: the response body is a readable stream, and the client decodes and parses it as chunks arrive. Here the same reader runs in Node against a stub server, which reports what it sees when the user presses Stop.
import http from 'node:http' const words = 'Dispatch usually takes two working days in Karnataka' .split(' ') const server = http.createServer((req, res) => { res.writeHead(200, { 'content-type': 'text/event-stream' }) let i = 0 const timer = setInterval(() => { if (i < words.length) { const token = words[i++] + ' ' res.write(`data: ${JSON.stringify({ token })}\n\n`) } else { res.write('data: [DONE]\n\n') res.end() clearInterval(timer) } }, 100) req.on('close', () => { clearInterval(timer) console.log('server: client went away after', i, 'tokens') }) }) await new Promise((r) => server.listen(55806, '127.0.0.1', r))
stream.mjs: a stub that sends one word every 100 ms.
async function ask(signal, onToken) { const res = await fetch('http://127.0.0.1:55806/reply', { signal }) const text = res.body.pipeThrough(new TextDecoderStream()) const reader = text.getReader() for (;;) { const { value, done } = await reader.read() if (done) return for (const block of value.split('\n\n')) { if (block.startsWith('data: ') && block !== 'data: [DONE]') { onToken(JSON.parse(block.slice(6)).token) } } } } const ctl = new AbortController() let text = '' let count = 0 try { await ask(ctl.signal, (token) => { text += token console.log('client shows:', JSON.stringify(text)) if (++count === 3) ctl.abort() // the user pressed Stop }) } catch (err) { console.log('client caught:', err.name, '-', err.message) } await new Promise((r) => setTimeout(r, 300))
stream.mjs: the client reads the stream, and Stop aborts it.
client shows: "Dispatch " client shows: "Dispatch usually " client shows: "Dispatch usually takes " client caught: AbortError - This operation was aborted server: client went away after 3 tokens
Output (Node 24)
The user pressed Stop after the third word. controller.abort() rejected the pending read() with an AbortError, and the server noticed that the connection had closed and stopped producing. Without that, a cancelled reply would keep costing the server work. In a page you would also keep the text already shown and offer to continue.