Courses / Frontend System Design, with JavaScript Foundations / Chapter 15
Module 7 · Design Problems: Method, Feed and Video · Chapter 15 of 21
A Step-by-Step Method for Frontend Design Sessions
Builds on TypeScript for Frontend Engineers, Non-functional Requirements, Frontend Fundamentals: Components, State, Data and Rendering, Performance and Optimisation, API Styles, Protocols and Data Formats and Security in Frontend Systems. Next up: Design a News Feed.
Part 1 · Requirements
Why a method, and what step one produces
A design problem is open on purpose, and the first minutes of a design session decide whether the rest is useful. A fixed order of steps keeps you from starting to draw boxes before you know what they are for.
This chapter gives seven steps: requirements, architecture, data model, interfaces, deep dives, checks, and trade-offs. They are our own plan, in plain words. One well-known public handbook names its framework RADIO, for five steps: requirements exploration, architecture or high-level design, data model, interface definition (API), and optimisations and deep dive. The handbook gives no time for each step. The seven steps here and the timings are ours: they split the last RADIO step in three, and the last lesson explains the time plan. Every case chapter in this course follows them.
Requirements come first because every later choice depends on them. A feed for a million readers on slow phones needs a different design from a feed for fifty colleagues on a fast office network. The step produces three lists.
- Functional requirements: what the user can do, written as actions. Three to six are enough. "Read reviews, add a review with a rating, mark a review helpful."
- Quality requirements, also called non-functional ones: how well it must work. Performance targets, the devices and networks that matter, accessibility, languages, and whether it must work offline.
- Out of scope: what you are choosing not to build. Saying it aloud is part of the plan, because it shows that the list is a decision and not an oversight.
The questions are as important as the lists. A good first five minutes is mostly questions, and each one should change the design. If no answer would change what you build, do not ask it.
Questions that change the design
| Ask | Because the answer changes |
|---|---|
| Who uses it, on what devices and networks? | JavaScript budget, image sizes, offline support |
| How much data is there, and how fast does it grow? | pagination style, list virtualisation, caching |
| Does the page need to be found by search or shared as a link? | server rendering against client rendering |
| Which languages and regions? | text growth, right-to-left, number and date formats |
| Is it real time or does it refresh on demand? | polling, SSE or WebSocket |
| Who can see or change this data? | sign-in, authorisation, what the client may cache |
| What can already be assumed? | whether to design the design system, the API or the backend |
Write the answers down as you get them. A short structured note beats a paragraph, and a note in a structured format can even be checked. The file below is the requirements list for one small feature, product reviews on a shop page. Each non-functional item has a target and a way to check it, because a target that nobody can check is a wish.
{
"feature": "Product reviews on a shop page",
"functional": [
"read reviews for a product, newest first",
"add a review with a star rating and text",
"mark a review as helpful"
],
"nonfunctional": [
{ "area": "performance",
"target": "LCP 2.5 s or less at p75 on a mid-range phone",
"check": "field data, plus a lab run on every release" },
{ "area": "network",
"target": "usable on 4G with 300 ms round trips",
"check": "throttled Chrome run" },
{ "area": "accessibility",
"target": "rating and form work by keyboard and screen reader",
"check": "axe in CI and a manual keyboard pass" },
{ "area": "i18n",
"target": "English and Hindi, dates and numbers per locale",
"check": "render each page in both locales" },
{ "area": "offline",
"target": "an offline review is sent when the network returns",
"check": "test with the network switched off" }
],
"outOfScope": ["moderation tools", "photo uploads", "seller replies"],
"questions": [
"How many reviews does a popular product have?",
"Is the page rendered on a server today?"
]
}requirements.json: one feature, as data.
Scope changes, and what to write down
Scope will change during the session. Someone may say that offline support is not needed, or add that the list must work for ten thousand reviews. That is normal and it is useful, because real requirements keep moving. When scope changes, say what it changes in the design, and go back to the step it affects.
The worked example for this chapter is a star-rating input on a review form. Its requirements, in a few lines, are an example of the right size.
| List | Star rating input |
|---|---|
| Functional | choose a rating from 1 to 5; change it before submitting; show the chosen value |
| Non-functional | works by keyboard and screen reader; touch targets at least 24 by 24 CSS pixels; no layout shift when it loads; labels translatable |
| Out of scope | half stars; showing an average rating; server storage of the rating |
The touch target size comes from WCAG 2.2, the accessibility guideline from the requirements chapter, and it is a good example of a requirement taken from a standard and not invented for the case. A later lesson builds this example through the rest of the steps.
Why should each question in the first minutes be one whose answer would change the design?
- Time is limited, and a question with no effect on the design spends it for nothing.
- Questions about devices, data size, search and languages all lead to different architectures.
In the run, the weak requirements file failed on network with the target "should be fast". What was wrong?
- The target has no number, so nobody can tell whether it is met.
- A target such as 4G with 300 ms round trips can be tested with a throttled browser.
Part 2 · Architecture
The pieces of a client application
The second step turns the requirements into boxes. Every case in this course uses the same few boxes, so the diagram stays familiar and your attention goes to what is different about the problem.
A client application has six pieces and a boundary with the server. The views are the components that draw the screen and report what the user did. The state store holds what the views read. The data layer decides what to fetch and when. The cache keeps answers the data layer may reuse. The transport speaks the network protocol. An optional service worker sits between the page and the network, and can answer requests itself, for offline use. Beyond the transport is the server boundary: the API that owns the truth.
| Piece | Question it answers | Typical case-chapter detail |
|---|---|---|
| Views | what does the user see and do? | list, composer, player, map, grid |
| State store | what does the screen know right now? | selected item, pending actions |
| Data layer | what to fetch, when to refetch? | pagination, optimistic updates, retries |
| Cache | what can be reused without asking? | normalised entities, expiry |
| Transport | how do bytes move? | HTTP, a WebSocket, SSE |
| Service worker | what works with no network? | offline shell, outbox |
| Server boundary |
One diagram, reused
The scene is the standard diagram. It shows one request travelling through the pieces: a view asks for data, the data layer checks the cache and misses, and the request goes to the server through the transport. Then the same question is answered from the cache. The cases in this course reuse these boxes, adding or removing what the problem needs.
A view asks for reviews, and the question travels down
Read it as steps
A request passes through the layers. The second time the cache answers it.
The service worker is drawn between the transport and the server because it can answer a request before it reaches the network. The performance chapter covers service workers for repeat visits. Leave it out when the problem does not need offline use, and say that you did.
Annotate the arrows as you draw. Label each one with what travels along it: a request, a cached entity, an event from the user. Mark where state lives, and mark which calls are asynchronous, since those need loading and error states. Two annotations on the diagram are worth more than a long spoken description, because anyone in the session can point at them and ask about them. When you add a piece the problem needs, such as a WebSocket beside the HTTP transport, draw it in the same style so the diagram still reads as one picture.
Keeping the layers apart
A diagram is only as good as the code that follows it. The rule behind the scene is that each layer imports only the layer directly below it. A view that calls the transport knows an API URL, and a change to the API then reaches into every view. The rule is easy to check, and teams do check it with lint rules or small scripts.
The script below holds a tiny project as text, a table of what each layer may import, and a loop that reports violations. The project has two deliberate mistakes.
// Each layer may import only the layer directly below it. const allowed = { view: ['store'], store: ['data'], data: ['transport'], transport: [], } // a tiny project, as text: file path -> the files it imports const project = { 'view/reviews.js': ['store/reviews.js'], 'view/rating.js': [], 'store/reviews.js': ['data/reviews.js'], 'data/reviews.js': ['transport/http.js'], 'transport/http.js': [], 'view/helpful-button.js': ['transport/http.js'], // skips layers 'data/cache.js': ['view/rating.js'], // points upward }
layers.mjs: the allowed directions, and a small project.
const layer = (path) => path.split('/')[0] let violations = 0 for (const [file, imports] of Object.entries(project)) { for (const target of imports) { if (!allowed[layer(file)].includes(layer(target))) { violations++ console.log(`${file} imports ${target}`) console.log(` ${layer(file)} may import: ` + (allowed[layer(file)].join(', ') || 'nothing')) } } } const files = Object.keys(project).length console.log(`${violations} violations in ${files} files`)
layers.mjs: the check.
view/helpful-button.js imports transport/http.js view may import: store data/cache.js imports view/rating.js data may import: transport 2 violations in 7 files
Output (Node 24)
A view that imports the transport skips two layers, the store and the data layer, and a data file that imports a view points upward. Both are reported with the rule that was broken. The same idea scales up: write the allowed directions once, and let a tool enforce them on every change.
Why should a view not import the transport directly?
- The view would then know about API addresses and protocols, and every change to them would reach into the views.
- Keeping the data layer between them leaves one place to change.
Part 3 · Data model and state placement
Entities as types
The third step answers two questions. What are the things the screen is made of, and where does each piece of data live? Types make the first answer exact. The second needs a decision for each piece.
An entity is a thing with an identity: a review, a reviewer, a product. Writing entities as TypeScript types forces you to list their fields and choose what each field is. The types below are the reviews model of the running example.
// Entities as the server sends them export type Reviewer = { id: string; name: string } export type Review = { id: string productId: string author: Reviewer stars: 1 | 2 | 3 | 4 | 5 text: string helpful: number createdAt: string // ISO 8601, an instant } // The client keeps each entity once, keyed by id export type Store = { reviews: Record<string, Review> reviewerNames: Record<string, string> byProduct: Record<string, string[]> // newest first }
model.ts: the entities, and the shape the client keeps.
Three small choices in these types are worth saying aloud. Times are ISO 8601 strings, instants in UTC, which a view formats for the reader's own locale and time zone. Ids are strings and not numbers, so the client does not depend on how the server makes them. The rating is a union of five literal values and not a plain number, so a value outside one to five cannot be written by mistake.
The server sends each review with its author nested inside it. The client store keeps the same data differently. That is the next page.
Normalised state
A reviewer who wrote ten reviews appears ten times in the server's reply. If the client keeps ten copies and the reviewer changes their name, ten places need updating, and any that is missed shows stale data. Normalising keeps each entity once, in a table keyed by id, and keeps everything else as lists of ids.
export function normalize(list: Review[]): Store { const store: Store = { reviews: {}, reviewerNames: {}, byProduct: {} } for (const r of list) { store.reviews[r.id] = r store.reviewerNames[r.author.id] = r.author.name ;(store.byProduct[r.productId] ??= []).push(r.id) } return store } const sample: Review[] = [ { id: 'r2', productId: 'p1', author: { id: 'u7', name: 'Meena' }, stars: 5, text: 'Fresh', helpful: 3, createdAt: '2026-11-02T10:00:00Z' }, { id: 'r1', productId: 'p1', author: { id: 'u7', name: 'Meena' }, stars: 4, text: 'Strong', helpful: 0, createdAt: '2026-10-20T08:30:00Z' }, ] const store = normalize(sample) console.log('reviews stored once each:', Object.keys(store.reviews)) console.log('reviewer names :', store.reviewerNames) console.log('p1 order :', store.byProduct.p1) // like arrives: one write, every view that shows r2 updates store.reviews.r2 = { ...store.reviews.r2, helpful: 4 } console.log('r2 helpful now :', store.reviews.r2.helpful)
model.ts: normalising, and one update.
reviews stored once each: [ 'r2', 'r1' ] reviewer names : { u7: 'Meena' } p1 order : [ 'r2', 'r1' ] r2 helpful now : 4
Output (Node 24)
The two reviews by Meena produced one entry in reviewerNames. The list for product p1 holds ids in newest-first order, so the order belongs to the list and not to the reviews. When the helpful count changed, one write to reviews.r2 was enough for every screen that reads it. Node strips the types and runs the file as it is. The type checker is the second step, and it is silent when the file is correct.
import type { Review } from './model.ts' const bad: Review = { id: 'r3', productId: 'p1', author: { id: 'u9', name: 'Arun' }, stars: 6, text: 'Too good', createdAt: '2026-11-05T09:00:00Z', } console.log(bad)
model-bad.ts: a review with two mistakes.
model-bad.ts(7,3): error TS2322: Type '6' is not assignable to type '1 | 2 | 3 | 4 | 5'.
Output (tsc 7.0.2, --strict)
The compiler printed one error for this object: the rating of 6 is not one of 1 | 2 | 3 | 4 | 5. After correcting it, the same object got a second complaint.
Where each piece of state lives
The last part of this step is a decision for every piece of data: which of four places owns it. Putting the same data in two places is the usual cause of bugs where two screens disagree.
| Place | Holds | Survives a reload | Example from the reviews feature |
|---|---|---|---|
| Server | the truth | yes | the reviews, the helpful counts, who may post |
| Client cache | copies of server data, with an age | only if persisted | the normalised store above |
| Local UI state | what only one component needs | no | which review is expanded, the text in the box |
| URL | what a link should restore | yes, and shareable | the product, the sort order, the page cursor |
Holdsthe truth
Survives a reloadyes
Example from the reviews featurethe reviews, the helpful counts, who may post
Holdscopies of server data, with an age
Survives a reloadonly if persisted
Part 4 · Interfaces
The API the client needs
The fourth step defines the two kinds of interface the design depends on. The first is the contract with the server. The second is the contract between components.
For the server, sketch only what the screen needs: each call with its request, its success reply and its errors. Use the vocabulary from the API chapter: resources, methods, status codes, a cursor for lists. The two calls below are the reviews feature, written as HTTP exchanges. Notice the parts a reader of an interface sketch looks for: the cursor in the list, the key that makes the POST safe to repeat, and one shape for every error.
GET /api/products/p1/reviews?first=2&after=r2 200 OK { "edges": [ { "node": { "id": "r1", "stars": 3, "text": "Fine", "helpful": 0 }, "cursor": "r1" } ], "pageInfo": { "hasNextPage": false, "endCursor": "r1" } }
A page of reviews, in the connection style.
POST /api/products/p1/reviews Idempotency-Key: key-2 { "stars": 6, "text": "Too good" } 422 Unprocessable Content { "error": { "code": "invalid_stars", "message": "stars must be a whole number from 1 to 5" } }
A rejected post, with the shared error shape.
The status in that block is the one the stub on the next page returns, 422, which RFC 9110 names Unprocessable Content: the server understood the request but the values are invalid. A client acts on the code, which is stable, and shows the message only in a developer tool, since messages are not meant for translation.
A typed client, run against a stub
The types for the calls go in a file the client and the screens share. The Result type is a discriminated union: a success has ok: true and a value, a failure has ok: false, a status and the error. Code that uses it must handle both.
export type Review = { id: string stars: 1 | 2 | 3 | 4 | 5 text: string helpful: number } export type Page = { edges: { node: Review; cursor: string }[] pageInfo: { hasNextPage: boolean; endCursor: string | null } } export type ApiError = { code: string; message: string } export type Result<T> = | { ok: true; value: T } | { ok: false; status: number; error: ApiError }
reviews-api.ts: the shared types.
const base = 'http://127.0.0.1:55800' async function call<T>( path: string, init?: RequestInit, ): Promise<Result<T>> { const res = await fetch(base + path, init) const body = await res.json() return res.ok ? { ok: true, value: body as T } // a cast, not a check : { ok: false, status: res.status, error: body.error } } export const listReviews = (productId: string, after?: string) => call<Page>(`/api/products/${productId}/reviews?first=2` + (after ? `&after=${after}` : '')) export const addReview = (productId: string, stars: number, text: string, key: string) => call<Review>(`/api/products/${productId}/reviews`, { method: 'POST', headers: { 'content-type': 'application/json', 'idempotency-key': key }, body: JSON.stringify({ stars, text }), })
reviews-api.ts: one generic call, and two typed ones.
The cast on the success branch is a promise, not a check. The compiler trusts that the server sent a Page. The TypeScript chapter explained why: at run time nothing checks the shape. A real client validates untrusted replies or relies on a schema that both sides generate from. The sketch keeps the trust to show the typing.
A stub server implements the two calls from the previous page with three reviews, a cursor and an idempotency key map. The driver loads two pages, posts an invalid rating, and posts a valid one twice with the same key.
import { server } from './stub.mjs' import { listReviews, addReview } from './reviews-api.ts' await new Promise<void>((done) => { server.listen(55800, '127.0.0.1', done) }) const first = await listReviews('p1') if (first.ok) { const ids = first.value.edges.map((e) => e.node.id) console.log('page 1:', ids, first.value.pageInfo) const cursor = first.value.pageInfo.endCursor! const second = await listReviews('p1', cursor) if (second.ok) { console.log('page 2:', second.value.edges.map((e) => e.node.id), second.value.pageInfo) } }
run-api.ts: two pages of reviews.
Component interfaces: props in, events out
The second interface is between components. The rule is small: data flows into a component as props, and the component reports what happened with events. It does not reach out to change a parent's state. The contract is a type, and it is the first thing to write for any component you are asked to design.
export type Stars = 1 | 2 | 3 | 4 | 5 // props in, events out: the whole contract of the component export type RatingProps = { value: Stars | 0 // 0 means nothing chosen yet readOnly?: boolean onChange: (value: Stars) => void }
rating.ts: the rating contract.
export function nextRating( value: Stars | 0, key: string, ): Stars | null { const at = value === 0 ? 0 : value switch (key) { case 'ArrowRight': case 'ArrowUp': return Math.min(at + 1, 5) as Stars case 'ArrowLeft': case 'ArrowDown': return Math.max(at - 1, 1) as Stars case 'Home': return 1 case 'End': return 5 default: return null // not a rating key, leave the page alone } } export function ariaLabel(value: Stars | 0): string { return value === 0 ? 'Rating, not chosen' : `Rating, ${value} of 5` }
rating.ts: the keyboard rules and the label.
The props say what the component needs: a value, which is a rating of one to five or zero for nothing chosen yet, an optional read-only flag, and an onChange that receives a valid rating. The type makes a seven-star rating impossible to express. The compiler checks both sides. This file misuses the contract twice.
import type { RatingProps } from './rating.ts' const props: RatingProps = { value: 6, onChange: (v: string) => console.log(v), } console.log(props)
rating-bad.ts: a bad value and a wrong handler.
rating-bad.ts(4,3): error TS2322: Type '6' is not assignable to type '0 | Stars'. rating-bad.ts(5,3): error TS2322: Type '(v: string) => void' is not assignable to type '(value: Stars) => void'. Types of parameters 'v' and 'value' are incompatible. Type 'number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.
Output (tsc 7.0.2, --strict)
The first error is the same range check as before. The second says the handler must accept a Stars and this one accepts a string. The extra lines are the compiler explaining where the mismatch is. The contract, not a comment, is what stops the next developer from misusing the component.
Part 5 · Deep dives, checks and trade-offs
Choosing the deep dives
Steps five to seven are where most of the value of a design session lies. The first four steps are the same for every problem. Step five is where the problem itself shows.
A deep dive is a detailed look at one hard part. Choose two or three, and choose them for a reason: the parts where the requirements pull against each other, or where a simple answer fails. Each case chapter names its own. A feed has infinite scroll and optimistic updates. A video player has adaptive streaming. A chat has reconnection and ordering. A calendar has time zones and overlapping events.
A good deep dive has four moves. Name the problem and why the obvious answer fails. Give the approach and one alternative. Say how it behaves when something goes wrong. Say how you would check that it works, whether with a test, a measurement or a number. If you can show a small piece of code or a state diagram, do so.
The checks come next, in a fixed order so that none is forgotten. Spend one or two points on each.
| Check | Questions to answer in a point or two |
|---|---|
| Performance | what is on the critical path, what is lazy-loaded, what is cached, which metric is the target? |
| Accessibility | keyboard use, focus, names and roles, motion, colour contrast, announcements for changes |
| Internationalisation | text length, right-to-left, number and date formats, translated messages |
| Security | what user text reaches the page, where tokens live, which origins talk to each other |
| Observability | which errors and timings are reported, how a failed request shows up for the team |
Trade-offs and the time plan
The last step is a table of the choices made and the alternative rejected for each. Every decision in a design costs something, and naming the cost is what separates a design from a list of features.
| Choice | Alternative rejected | Reason | What it costs |
|---|---|---|---|
| Cursor pagination | offset pagination | the list changes while reading | no jump to page 7 |
| Normalised store | the server shape as it came | one update fixes every screen | more code to read and write |
| Server-rendered first page | client rendering only | content before the script runs | a server to run, hydration |
| Optimistic update | wait for the reply | the screen reacts at once | a rollback path to build |
Alternative rejectedoffset pagination
Reasonthe list changes while reading
What it costsno jump to page 7
Alternative rejectedthe server shape as it came
Reasonone update fixes every screen
A ten-minute worked example
The star-rating input from the first lesson shows the method at a small size. A component question is shorter, so the steps are compressed.
- Requirements (1 minute): choose 1 to 5, change before submit, keyboard and screen reader, touch targets of at least 24 by 24 CSS pixels, no layout shift. Out of scope: half stars, averages, storage.
- Architecture (1 minute): one component, no server boundary. It gets its value from the parent and reports changes. The form around it owns the value.
- Data model (1 minute): the value is a whole number from 1 to 5, or 0 for none chosen. It lives in the parent form, which is the source of truth, not inside the rating.
- Interface (2 minutes): the contract from the last lesson, a value and an
onChange, plus a read-only mode. It is a radio group, so it has a group label and five options with names such as "3 of 5". - Deep dive (3 minutes): keyboard. Arrows move and choose,
HomeandEndjump to the ends, and other keys are left alone. The rules are pure functions, so they can be tested without a browser. - Checks and trade-offs (2 minutes): colour is never the only signal, so the chosen stars also get a shape or a label. Text is translatable. A rating stored only on the client is lost on a reload, which is accepted for this scope.
The keyboard deep dive, run
The deep dive has a function behind it. The script feeds it a list of keys and records what the component would report. Keys that do nothing, because the rating is already at the end or the key is not a rating key, are reported and not turned into events.
import { nextRating, ariaLabel } from './rating.ts' import type { RatingProps } from './rating.ts' const log: string[] = [] const props: RatingProps = { value: 3, onChange: (v) => log.push(`chose ${v}`), } for (const key of ['ArrowRight', 'ArrowRight', 'ArrowRight', 'Home', 'ArrowLeft', 'End', 'Tab']) { const next = nextRating(props.value, key) if (next === null) { log.push(`${key}: ignored`); continue } if (next === props.value) { log.push(`${key}: no change`); continue } props.value = next props.onChange(next) } console.log(log.join('\n'))
rating-run.ts: the keyboard rules, driven by a list of keys.
chose 4 chose 5 ArrowRight: no change chose 1 ArrowLeft: no change chose 5 Tab: ignored Rating, not chosen Rating, 5 of 5
Output (Node 24)
Starting at 3, two presses of ArrowRight gave 4 and 5, and the third changed nothing. Home went to 1 and ArrowLeft then changed nothing. End went to 5, and Tab was ignored so that it can move focus away. The two labels are the text a screen reader would announce before and after a choice.
Watch for the scope change: it sends the session back to the first step