This chapter is four timed practice prompts. Two are component questions, one small widget to design in 30 minutes. Two are application questions, a whole screen flow to design in 45. Each lesson gives the prompt, the questions worth asking, a model answer, code that was run, and a rubric. The prompts are chosen so that none repeats the five design chapters or the drills in the machine coding chapter. Nothing here describes what any company asks: the prompts and the scoring are our own.
Run it like this. Read the prompt only, close the lesson, and set a timer for the time box. Talk aloud and write on paper or a whiteboard, with the seven steps of the method chapter as the order. Record yourself if you can. When the timer ends, stop, then open the lesson and compare. Score yourself with the rubric before reading the model answer for the second time, because the second reading is where you start agreeing with it.
The time boxes follow the plan from the method chapter, which its script printed for 30 and 45 minutes. The plan is ours, not a published split.
Box
Requirements
Architecture
Data model
Interfaces
Deep dives
Checks and trade-offs
30 minutes
3
5
5
5
9
3
45 minutes
5
8
7
7
13
5
30 minutes
Requirements3
Architecture5
Data model5
Interfaces5
Deep dives9
Checks and trade-offs3
45 minutes
Requirements5
Architecture8
Data model7
Interfaces7
Deep dives13
Checks and trade-offs5
How to score yourself
The six signals are the ones from the first chapter. The 0, 1, 2 scale and the bands are this course's own, made for self-marking. Give each signal 0, 1 or 2. Zero means the signal was missing. One means it was there but thin. Two means it was clear enough that a listener could repeat it back. The total is out of 12, and the bands below are a rough guide for practice, not a published pass mark.
Signal
Strong looks like
Weak looks like
Clarifying
Questions that change the design
Questions asked for show, or none
Structure
A visible order and time awareness
Jumping between topics
Data and API
Types for entities, a stated pagination and error shape
Calls to "the backend" with no contract
Depth
Two or three hard parts explored with numbers and trade-offs
Everything touched, nothing explained
Cross-cutting care
Performance, accessibility, i18n and security raised unprompted
Raised only when asked
Communication
Thinking aloud, checking in, naming trade-offs
Long silences, defending a choice without alternatives
Total
Reading
10 to 12
Ready to move on to a harder prompt, or to a different box length
6 to 9
The structure is there; find the signals scored 1 and redo the step
0 to 5
Go back to the chapters named below, then repeat the same prompt in a week
Each prompt lesson repeats the six signal names with what a strong answer shows for that prompt, so that marking is a comparison and not a feeling.
Reviewing a run
Replay the recording with a pen, and mark where you went silent, where you passed the time plan, and where an assumption went unsaid. The usual causes map to chapters.
What went wrong
Read again
No questions before drawing
the method chapter, step one, and the requirements chapter
Nothing about the network, retries or caching
the API chapter and the performance chapter
Component state placed in the wrong home
the fundamentals chapter
No answer to "what if the page is attacked"
the security chapter
Dates, zones or text treated as simple
the calendar chapter and the foundations chapters
Real-time or live updates hand-waved
the chat and ride-hailing chapters
You score the signals 2, 2, 1, 1, 0, 2 for a prompt. What is the total, and what do you redo?
The total is 8, in the 6 to 9 band. Cross-cutting care scored 0, so redo that step first, then the two signals that scored 1, data and API and depth.
The course's advice is to repeat the same prompt before taking a new one.
Why close the lesson and read only the prompt before the timer starts?
The point is to practise producing the structure from nothing, in the time box. Reading the model answer first would only practise recognising it.
The 30-minute plan gives 9 minutes to deep dives. What is the first step to shorten if you fall behind?
The early steps: requirements, architecture, data model and interfaces. The deep dives are where depth is shown, so they keep their share.
Part 2 · Prompt 1: a resumable file uploader
The prompt
Design the front end of a file uploader for a web app that accepts files up to 2 GB over mobile networks. People must see progress, pause and resume, survive a lost connection, and end with a file that was received whole. Component question. Time box: 30 minutes.
Spend the first three minutes on questions. These are the ones that change the picture.
Question
Because the answer changes
Are files kept on the device between visits?
whether resume must survive a closed tab
How many uploads at once, and how many parts in flight?
the queue and the use of the connection
Does the server accept parts, or only a whole body?
whether resume is possible at all
What must the person see?
progress per file or per part, and the text for a screen reader
What can go wrong with the file itself?
size and type checks, and a hash at the end
Model answer, step by step. The summary is what you would say in the box.
Step
What you would say
1. Requirements
Choose a file, upload in parts, show progress, pause, resume, cancel, verify at the end. Phones on 4G, keyboard, screen readers. Out of scope: virus scanning.
2. Architecture
A file picker, a queue of parts, a worker pool of three, a status view, and a server that stores parts and can say which it has.
3. Data model
An upload has an id, a part size and a state. Each part is queued, sending, done or failed. The server knows which parts exist.
4. Interfaces
Four calls: list received parts, put a part, complete with a hash, and error shapes.
5. Deep dives
Retries and pause, because a lost reply must not duplicate or lose a part; and resume, by asking the server what it holds.
6. Checks
A labelled progress bar and text, a limit on parts in flight, a size check on the client and the server, no file names in logs.
7. Trade-offs
Parts over one big request, because a failure costs one part; three in flight over many, to leave room for the page.
The interface, and the states of a part
Putting the same part twice is harmless, which makes a retry safe. The lab server implements the last three calls of this sketch.
A part has four states. A part that fails with a timeout or a server error waits and is sent again, only a part that has used all its tries is failed for good, and a pause puts a part that was sending back in the queue.
Animated sceneThe life of one part0:15
Watch for a part being sent again after a server error
Read it as steps
A part is sent again after a 503, and a pause returns it to the queue.
The client, run against faults
Two small functions carry the design. sendPart sends one part and retries on a timeout, a lost connection, a 5xx, a 408 or a 429, while any other 4xx is final and a pause, an abort, is not a failure. upload first asks the server what it already holds, queues the rest, runs three workers, and ends with the hash. The lab hashes with node:crypto. In a page, per MDN, subtle.digest does not stream and needs the whole input in memory, so for 2 GB a real client would hash in chunks with a library or compare a hash per part. That was not run.
js
asyncfunction sendPart(url, bytes, signal, waits = [30, 60, 120]) {
let tries = 0for (let i = 0; i <= waits.length; i++) {
tries++
try {
const res = await fetch(url, {
method: 'PUT',
body: bytes,
signal,
})
if (res.ok) return { ok: true, tries }
if (res.status < 500 && ![408, 429].includes(res.status))
return { ok: false, tries, status: res.status }
} catch (e) {
if (signal?.aborted) throw e // a pause is not a failure
}
if (i < waits.length) await sleep(waits[i])
}
return { ok: false, tries, status: 0 }
}
uploader.mjs: one part, with retries.
js
exportasyncfunction upload(
base,
id,
file,
{ partSize, limit = 3, signal, onPart } = {},
) {
if (!Number.isInteger(partSize) || partSize < 1) {
thrownew RangeError('partSize must be a whole number above 0')
}
const count = Math.ceil(file.length / partSize)
const have = new Set(
(await (await again(`${base}/uploads/${id}`)).json()).received,
)
const todo = [...Array(count).keys()].filter((i) => !have.has(i))
const failed = []
let paused = false
The script uploads 6 MiB of random bytes as 12 parts of 512 KiB. It does it four times against a fresh server, with a different fault each time, and then sends three bad calls.
text
1 calm : done | puts 12 | most at once 32 faults : done | parts needing 2 tries: 1, 23 paused : paused | stored on the server 6 of 12
complete too early: 409 {"missing":[6,7,8,9,10,11]}
resumed : done | puts 12 | parts sent twice: none
4 corrupt : rejected 422 {"error":"hash_mismatch"}
5 bad calls :
complete, parts -1 : 422 {"error":"bad_parts"}
complete, not JSON : 400 {"error":"bad_json"}
part size 0 : RangeError: partSize must be a whole number above
0
parts held : []
Output (Node 24)
The calm run sent 12 parts, at most 3 at once, which is the pool limit. In the run with faults, part 1 got a 503 and part 2 had its connection cut, and both succeeded on a second try. In the pause run the client stopped after 4 parts it knew about, but the server held 6, because two were already on their way. A call to complete then got a 409 and the missing parts. The resume asked the server first and skipped the six it held. This run varies. Across more than ten runs the server held 4, 5 or 6 parts at the pause, and in two of eight runs one part was sent twice, because the abort cut its reply after the server stored it. The repeat is harmless. Run 4 corrupted a part on the server and the final check caught it with a 422. In run 5 a complete call with -1 parts got a 422, broken JSON got a 400, and a part size of 0 was refused by the client. The first version crashed the server on both bad bodies, sorted the received parts as text (0, 1, 10, 11, 2) and accepted a part size of 0.
Progress per finished part moves in jumps. Per MDN, XMLHttpRequest reports upload progress through its upload object. A Chrome check sends 4 MiB to a slow local sink, updates a <progress> element with a label, and reads its accessible name.
progress.html: a labelled bar and an XHR with progress.
text
Chrome 157
status 200 | progress events: many
never went backwards: true | last loaded == total: true
bar value at the end: 100
- progressbar "Uploading report.pdf"
Output (Chrome 157)
Progress events arrived in numbers, none went backwards, and the last one equalled the total. The bar has the implicit role progressbar, and MDN recommends a label for its name, which the snapshot shows.
Rubric and questions
Signal
Strong looks like, for this prompt
Clarifying
Asks about resume after a closed tab, server support for parts, and how many parts in flight
Structure
Moves through the seven steps in the 30 minute plan and says when it changes step
Data and API
Names the four calls, the part states and the 409 and 422 answers
Depth
Retries and pause kept apart; resume by asking the server; the hash at the end, with the run to show it
Cross-cutting care
Labelled progress, size limits, no names in logs, raised without being asked
Communication
Says why parts and why three, and what each alternative would cost
A part's reply is lost, so the client sends it again. Why is that safe here?
Putting the same part number again stores the same bytes, so the result is the same. The server answered 200 both times.
The pause run stored 6 parts on the server when the client knew of 4. How does the resume cope?
It asks the server which parts it holds, and queues only the rest.
If a part was already stored and is sent again, the server keeps the same bytes, so the repeat does no harm.
Why finish with a hash and not just a count of parts?
A part can arrive damaged. In the run a corrupted part passed every per-part check, and only the final hash refused it with a 422.
Part 3 · Prompt 2: a table of 50,000 rows
The prompt
Design a data table for an admin screen that lists 50,000 customer rows. People can sort by up to two columns, search, move between pages, and copy a link that opens the same view. Component question. Time box: 30 minutes.
Question
Because the answer changes
Where do the rows live, and how often do they change?
whether the client can hold them, and how a cache is kept fresh
What types are in the columns?
how each column sorts: text, number, date
Which languages are in the names?
whether a plain comparison gives the right order
Is the table edited in place?
row state, focus, and conflicts
Who uses it, and how?
keyboard use, screen readers, and a visible sort state
Step
What you would say
1. Requirements
View a page of rows, sort by up to two columns, search, page, and share the view as a link. 50,000 rows, keyboard and screen reader use, names in English and Hindi. Out of scope: editing, export, column resizing.
2. Architecture
A table, a pager and a search box over one view state kept in the address. A data layer fetches a page for a view and caches it by the canonical address.
3. Data model
A row type with ids, text, a number in paise and an ISO date. The view state is sort, q, page and size, and it lives in the URL.
4. Interfaces
GET /api/customers with the same four parameters, answering rows and a total, with one error shape. The table takes columns, rows, sort and an onSortChange event.
5. Deep dives
Where to sort and filter, decided with numbers; the view state in the URL, with bad input; and a comparison that orders names the way people do.
6. Checks
A caption and aria-sort on one header, paging so that the DOM stays small, collation by locale, search text treated as data, and failed requests logged.
7. Trade-offs
Server-side sort over client-side, because of payload size and freshness; pages over endless scroll, because a link must name a place.
Server or client: decide with numbers
The first deep dive is where the work happens. If the client held all the rows, sorting and search would be instant after the first load. The script builds 50,000 made-up rows and measures what that would cost.
sort-run.mjs: payload size, and two ways to compare.
js
const best = (fn, runs = 5) => {
const t = []
for (let i = 0; i < runs; i++) {
const copy = rows.slice()
const a = performance.now()
fn(copy)
t.push(performance.now() - a)
}
t.sort((x, y) => x - y)
return`${t[0].toFixed(0)} ms (worst ${t[runs - 1].toFixed(0)})`
}
console.log('sort 50,000 by name, best of 5, this machine:')
console.log(
' < ',
best((r) =>
r.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)),
),
)
console.log(
' localeCompare ',
best((r) => r.sort((a, b) => a.name.localeCompare(b.name, 'en-IN'))),
)
console.log(
' Collator.compare ',
best((r) => r.sort((a, b) => coll.compare(a.name, b.name))),
)
sort-run.mjs: timing, and the three comparers.
text
rows 50,000 | JSON 4.5 MB | gzip 0.7 MB
with < : Amit Zoya abhi item10 item2 Ábhi
Collator : abhi Ábhi Amit item2 item10 Zoya
sort 50,000 by name, best of 5, this machine:
< 15 ms (worst 21)
localeCompare 82 ms (worst 94)
Collator.compare 81 ms (worst 94)
stable two-key sort keeps amounts in order within a city: true
Output (Node 24, this machine)
The rows are 4.5 MB as JSON and 0.7 MB compressed. That is too much to download before the first row appears on a phone, and it is stale as soon as someone changes a customer. So the server sorts, filters and pages, and the client asks for 50 rows at a time. The sorting numbers still matter, because the same question comes up for a table of a few thousand rows that a client does hold.
The comparison is the part people get wrong. Comparing with < sorted Ábhi after Zoya and item10 before item2. A collator built with Intl.Collator and the numeric option put the accented name next to its plain spelling and ordered the item numbers as numbers. Over five runs of the script on this machine, sorting 50,000 rows took 15 to 34 ms with <, 82 to 116 ms with localeCompare and a locale argument, and 80 to 93 ms with the collator. Take the ratio and not the digits: the right order costs several times as much and is still about a tenth of a second at worst. Array sort is stable, which the last line checks: a second sort by city left the rows within a city in their amount order, so a two-column sort is two sorts, the less important column first.
The view lives in the address
A link that opens the same view is only possible if the whole view is in the address. The state is parsed from the query string and written back in one canonical form, so that two spellings of the same view give the same cache key. Anything outside the rules is replaced by a default, since the address is input from anywhere.
js
// table-url.mjs: the table's view state, kept in the address.const COLS = ['name', 'city', 'amount', 'joined']
const DEFAULTS = { sort: [], q: '', page: 1, size: 50 }
const whole = (v, lo, hi, dflt) => {
if (v === null || !/^\d{1,9}$/.test(v)) return dflt
return Math.min(Math.max(Number(v), lo), hi)
}
exportfunction parse(search) {
const p = new URLSearchParams(search)
const sort = []
for (const part of (p.get('sort') ?? '').split(',')) {
const [col, dir = 'asc'] = part.split(':')
if (!COLS.includes(col) || !['asc', 'desc'].includes(dir)) continueif (sort.some((s) => s.col === col) || sort.length === 2) continue
sort.push({ col, dir })
}
return {
sort,
q: (p.get('q') ?? '').trim().slice(0, 100),
page: whole(p.get('page'), 1, 1_000_000, DEFAULTS.page),
size: whole(p.get('size'), 10, 200, DEFAULTS.size),
}
}
table-url.mjs: read the view from the address.
js
exportfunction toSearch(s) {
const p = new URLSearchParams()
if (s.sort.length) {
p.set('sort', s.sort.map((x) => `${x.col}:${x.dir}`).join(','))
}
if (s.q) p.set('q', s.q)
if (s.page !== DEFAULTS.page) p.set('page', String(s.page))
if (s.size !== DEFAULTS.size) p.set('size', String(s.size))
return p.toString()
}
table-url.mjs: write it back, canonically.
text
sort [] q "" page 1 size 50
back to: (nothing)
?sort=name:asc,amount:desc&q=Asha&page=3
sort [name asc, amount desc] q "Asha" page 3 size 50
back to: sort=name%3Aasc%2Camount%3Adesc&q=Asha&page=3
?page=-1&size=1e9
sort [] q "" page 1 size 50
back to: (nothing)
?page=0&size=5
sort [] q "" page 1 size 10
back to: size=10
?size=500&page=2.5
sort [] q "" page 1 size 200
back to: size=200
?sort=password:asc,name:sideways
sort [] q "" page 1 size 50
back to: (nothing)
?sort=name,name:desc,city
sort [name asc, city asc] q "" page 1 size 50
back to: sort=name%3Aasc%2Ccity%3Aasc
?q=%20%20Pune%20
sort [] q "Pune" page 1 size 50
back to: q=Pune
round trip: sort=city%3Adesc&page=4&size=25
Output (Node 24)
Negative and fractional pages fell back to 1, and a size of 500 was held to 200 while 5 was raised to 10. A column that does not exist, such as password, was dropped. A repeated column kept its first direction and a third column was never taken. Spaces around the search text were trimmed. The round trip at the bottom returned the same view. This is also what the server must do with the same parameters, since the client is not the only caller.
The table for a screen reader, and the rubric
The table is a real table, with a caption that says how it is sorted. Per MDN, aria-sort goes on the header cell of the one sorted column and takes ascending, descending, none or other, and only one header should carry it at a time. The header label is a button, and the attribute stays on the cell, as in the MDN example. Row virtualisation is covered in the feed and performance chapters, and here paging keeps the DOM at 50 rows.
html
<table>
<caption>Customers, sorted by name, A to Z</caption>
<thead><tr>
<th aria-sort="ascending"><button>Name</button></th>
<th><button>City</button></th>
<th><button>Amount</button></th>
</tr></thead>
<tbody> ... 50 rows ... </tbody>
</table>
Markup for the sorted header. Not run as a test.
Signal
Strong looks like, for this prompt
Clarifying
Asks where the rows live, the column types and the languages before drawing
Structure
Gives each step its minutes, and keeps the deep dive on sorting and state
Data and API
States the four parameters, the response with a total, and the error shape
Depth
Decides server or client with numbers (4.5 MB, 0.7 MB) and shows a correct comparison
Cross-cutting care
Mentions aria-sort, a caption, small DOM, and clamping of the address
Communication
Says what server-side sorting costs, and what paging gives up
Why does the design sort on the server, when sorting 50,000 rows on the client took under a tenth of a second?
The cost is the download, not the sort: 4.5 MB as JSON and 0.7 MB compressed, and the data is stale when someone edits a row.
The address says ?page=-1&size=1e9. What does the table show?
Page 1 with 50 rows: the page fell back to its default and the size too, since 1e9 is not a whole number. The run showed both.
Why is the less important sort column applied first?
Array sort is stable, so a later sort leaves equal rows in the earlier order. The run showed amounts staying in order within each city.
Part 4 · Prompt 3: a shop with checkout
The prompt
Design the front end of a shopping site: a product listing with filters, a cart, and a checkout that pays on a payment page run by another company. Application question. Time box: 45 minutes.
Question
Because the answer changes
Guests or signed-in buyers only?
where the cart lives, and what a repeat visit shows
Do prices or stock change during a visit?
how the cart is re-checked before an order
Which payment flow: hosted page, or fields in our page?
what our pages may touch, and how a result comes back
Which devices and networks?
whether the listing is rendered on the server
Which languages and currency?
money in paise, and number formats
Step
What you would say
1. Requirements
Browse and filter, add to cart, change quantity, check out, and pay. Phones first, guests allowed, English and Hindi, rupees. Out of scope: tax rules, delivery, returns.
2. Architecture
A listing rendered on the server and cacheable, a client cart store, a checkout flow, and a server that owns prices, orders and payment results.
3. Data model
Products and prices from the server. A cart line is a product id, a quantity and the price seen. Money is whole paise. An order has a status the server sets.
4. Interfaces
A listing with a cursor, POST /api/orders with a key, GET /api/orders/:id, and a signed webhook from the payment company to the server.
5. Deep dives
Price changes between cart and order; the payment redirect and what the return page may trust.
6. Checks
Speed of the listing, a form that works by keyboard, rupee formatting, no card data in our pages, a token on the order request, and log every order status change.
7. Trade-offs
Server-rendered listing over client-only, for the first paint; a hosted payment page over our own fields, for what our pages never touch.
The interface, and a cart that can be wrong
The listing and the cart are the familiar part. The listing is rendered on the server, so that the first screen needs no script, and it takes its filters from the address and pages with the cursor shape of the method chapter. The cart lives in the browser as lines of product, quantity and priceSeen. What a price was when the shopper added it is not what the server will charge, so the order call carries priceSeen and the server decides.
shop-server.mjs: priced by the server, and the key.
The payment redirect
A hosted payment page means the buyer leaves our site, pays on the payment company's page, and comes back. Two things follow. Our pages never touch card details. And the browser is the wrong messenger for the result: the address of the return page can say anything, since anyone can type it. The result must come from the payment company to our server, signed, and the return page must ask our server what it knows.
Animated scenePaying on another page0:15
Watch for the return page asking the server, not reading its address
Read it as steps
The return page trusts the server, not its own address.
shop-server.mjs: the webhook checks signature, amount and order.
js
const RETURN_PAGE = `<!doctype html>
<meta charset="utf-8"><title>Order</title>
<p id="state" role="status">Checking your payment...</p>
<script>
const id = new URLSearchParams(location.search).get('order')
const say = (t) => {
const el = document.getElementById('state')
el.textContent = 'Order ' + id + ': ' + t
}
asyncfunction check(n) {
const o = await (await fetch('/api/orders/' + id)).json()
if (o.status !== 'pending') return say(o.status)
if (n === 0) return say('still pending')
setTimeout(() => check(n - 1), 100)
}
check(5)
</script>`
shop-server.mjs: the return page asks the server.
Four checks, run
The first script runs the API against a stub shop and a stub payment company, with the shared secret of the lab. The second drives Chrome through the redirect between two local origins, one for the shop and one for the payment page.
text
order, key k1 201 order o1, total 49800 paise
total ₹498.00
same key again 200 order o1, total 49800 paise
same order id: true
no key 400 missing_idempotency_key
quantity -3422 bad_lines
quantity 0.5422 bad_lines
no lines 422 bad_lines
unknown product 422 bad_lines
body is not JSON 400 bad_json
price rose, old price 409 price_changed, p1 now 26900
now ₹269.00 each
webhook, wrong signature 401 bad_signature
order is pending
webhook, right signature 200 ok
order is paid
webhook, sent again 200 ok
events handled: 1
paid, wrong amount 422 amount_mismatch
order is pending
paid, right amount 200 ok
late "failed" event 200 ok
order is paid
unknown order 422 bad_event
Output (Node 24)
The same key a second time returned the same order, so a double tap on Place order makes one order. An order with no key was refused with 400. After the price of the item rose, an order with the old price answered 409 and the new price, ₹269.00 each, and the screen must show it and ask. A webhook with a wrong signature got 401 and the order stayed pending. The right signature moved it to paid, and the same event sent again changed nothing. A signed event with the wrong amount got 422 and left the order pending, and a late failed event for an order already paid left it paid. An unknown order was refused. The first version of the server accepted a quantity of -3, which made a negative total, an empty order, an unknown product, and a signed paid event for any amount at all, and a broken JSON body stopped the whole process.
text
Chrome 1571 cart page : shop /
2 after Place : gateway /pay?order=o1&amount=49800
page says : Pay 498 for order o1
3 back at shop : shop /return?order=o1&status=succe
page says : Order o1: paid
order on server: paid
4 forged return : shop /return?order=o2&status=succe
page says : Order o2: still pending
order on server: pending
Output (Chrome 157)
The buyer went from the shop to the payment page and came back, and the page said paid, which the server confirmed. In case 4 the script made an order that nobody paid and opened its return address with status=success typed in. The page asked the server, which said pending, and the page said so. Pending does not prove that nothing was charged, since the webhook can arrive later, so a real return page keeps asking for a while. Order ids here are guessable counters, and a real server would use random ids and check that the order belongs to the caller.
Rubric and questions
Signal
Strong looks like, for this prompt
Clarifying
Asks about guests, price changes, the payment flow and devices
Structure
Keeps to the 45-minute plan, and says when it moves from the cart to the payment
Data and API
Names the order call with a key, the 409 answer, the status call and the signed webhook
Depth
Goes deep on price changes and on what the return page may trust, with the run to show it
Cross-cutting care
Mentions server rendering for the listing, a token on the order call, and no card data in our pages
Communication
Says why hosted payment and why server rendering, and what each costs
The return page is opened with ?status=success. Why does the page still say pending in the run?
The page asks the server for the order status and the server had not been told of a payment. A query parameter is typed by whoever opens the page.
What stops a stranger from marking an order paid by calling the webhook?
The signature: an HMAC of the body with a secret only the shop and the payment company hold. In the run a wrong signature got a 401 and the order stayed pending.
A price rose after the shopper added an item. What does the order call return, and what should the screen do?
A 409 with the new price, ₹269.00 in the run. The screen shows it and asks for confirmation, and does not book at a price nobody agreed to.
Part 5 · Prompt 4: a shared whiteboard
The prompt
Design the front end of a shared whiteboard: several people draw and move shapes on one canvas at the same time, and see each other's cursors. Application question. Time box: 45 minutes.
Question
Because the answer changes
How many people, and how many objects?
how often the screen redraws and what the transport must carry
Must it work offline, and merge later?
the model for conflicting edits
Is there undo, and whose?
whether an undo is a local step or a new edit
Which inputs: mouse, touch, pen?
how strokes are read, and gestures that clash with the page
What if someone cannot see the canvas?
a text alternative for the objects
Step
What you would say
1. Requirements
Draw strokes, move and delete objects, see others' cursors, pan and zoom, undo your own steps. Up to 20 people and 5,000 objects, with touch and pen. Out of scope: permissions, export.
2. Architecture
Two canvas layers, one for finished objects and one for the stroke in progress, an object store, a log of edits, and a socket as in the chat chapter. Cursors travel on a separate light channel.
3. Data model
An object has an id and a kind; an edit has an id, a client, a clock, an object id and a type. Cursors are never stored.
4. Interfaces
Socket messages: hello with the last seen edit, op, and presence. Reconnection and resume are as in the chat chapter.
5. Deep dives
How two edits to one object converge; and how to draw 5,000 objects without redrawing them on every frame.
6. Checks
Layered drawing, an object list as the text alternative, text direction for text objects, validating every edit from the socket, edits per second as a metric.
7. Trade-offs
Whole-object last-writer-wins over merging inside a stroke, for its simplicity; one edit per object per gesture, for a small log.
Edits that converge
Two people move or delete the same shape at the same moment, and every screen must end up the same. The simplest model that does this treats each object as one value that the newest edit replaces, which is a last-writer-wins register. "Newest" cannot come from the device clock, which may be wrong. Each client keeps a counter and moves it forward past any edit it sees. That is a Lamport clock. When two edits carry the same counter value, the client id breaks the tie, so every replica makes the same choice. A delete is an edit too, so a late move cannot bring a deleted shape back.
js
// board.mjs: a shared board; each object is a last-writer-wins value.const MAX_CLOCK = 2 ** 40// near 2 ** 53 a counter stops countingconst ok = (op) =>
op &&
typeof op.id === 'string' &&
typeof op.client === 'string' &&
Number.isInteger(op.clock) &&
op.clock > 0 &&
op.clock < MAX_CLOCK &&
typeof op.obj === 'string' &&
(op.type === 'del' || (op.type === 'put' && op.value !== undefined))
/** a is newer: the higher clock wins; a tie goes to the client id */const newer = (a, b, tieBreak) =>
a.clock !== b.clock
? a.clock > b.clock
: tieBreak && a.client > b.client
board.mjs: validate, order and apply edits.
js
exportclass Replica {
constructor(client, tieBreak = true) {
this.client = client
this.tieBreak = tieBreak
this.clock = 0this.n = 0this.seen = new Set()
this.objs = new Map() // object id -> the newest op for it
}
local(type, obj, value) {
const op = {
id: `${this.client}:${++this.n}`,
client: this.client,
clock: ++this.clock,
obj,
type,
value,
}
this.receive(op)
return op
}
board.mjs: the replica, and a local edit.
js
receive(op) {
// a damaged op, or one seen before, changes nothingif (!ok(op) || this.seen.has(op.id)) returnfalsethis.seen.add(op.id)
this.clock = Math.max(this.clock, op.clock)
const cur = this.objs.get(op.obj)
if (!cur || newer(op, cur, this.tieBreak)) this.objs.set(op.obj, op)
returntrue
}
view() {
const out = {}
for (const [k, op] of [...this.objs].sort()) {
if (op.type === 'put') out[k] = op.value
}
return JSON.stringify(out)
}
}
board.mjs: receive an edit, and read the board.
Convergence, run
The script shows a draw, a move and a delete that cross, and then a repeated edit, four damaged ones and a tie. After that it runs 1,000 random trials, each with three replicas and 40 edits, delivered late, twice and in shuffled order, and compares them at the end.
text
A draws s1, B receives it A: {"s1":"v1"} | B: {"s1":"v1"}
A moves s1 while B deletes it A: {"s1":"v2"} | B: {}
they exchange the two edits A: {} | B: {}
clocks: move 2 delete 2 -> a tie, so client b beats a
repeat of the move : ignored
damaged op (no clock) : ignored
clock 0 : ignored
clock 2 ** 53 - 1 : ignored
put with no value : ignored
same clock, two writers: 11 -> {"s2":"from b"} = {"s2":"from b"}
1000 random runs, 3 replicas, 40 edits each, converged:
with the client id as tie-break : 1000
tie-break removed (first one wins): 786
Output (Node 24)
A moved the shape while B deleted it, each at clock 2. Neither saw the other first, and the tie went to client b, so on both screens the shape was gone. A repeated edit and four damaged ones changed nothing: no clock, clock 0, a clock of 2 ** 53 - 1 and a put with no value. The first version accepted the huge clock, and after it the replica's own next two edits shared one clock value, so the second was lost. It also accepted a put with no value. All 1,000 random trials converged. With the tie-break removed, so that the first edit to arrive wins a tie, only 786 did, which shows the test can fail and that the client id is what makes replicas agree.
What the model gives up is merging inside an object. If two people edit the same text box, one edit is lost. For a whiteboard of strokes and shapes that is acceptable, and the trade-off table says so.
Drawing without redrawing everything
A canvas has no objects to move, only pixels. A simple board redraws every stroke on every frame, which costs more as the board fills. The MDN guide to canvas optimisation advises layering canvases and pre-rendering repeated content, and the design follows it: finished strokes are drawn once into a cache canvas, and each frame copies that cache and draws only the stroke in progress.
html
<script>
function strokes(n) {
const out = []
for (let i = 0; i < n; i++) {
const pts = []
const x = (i * 53) % 760
const y = (i * 97) % 560
for (let k = 0; k < 20; k++)
pts.push([x + k * 2, y + ((k * 7 + i) % 15)])
out.push(pts)
}
return out
}
const draw = (ctx, list) => {
ctx.beginPath()
for (const pts of list) {
ctx.moveTo(pts[0][0], pts[0][1])
for (let k = 1; k < pts.length; k++)
ctx.lineTo(pts[k][0], pts[k][1])
}
ctx.stroke()
}
canvas.html: made-up strokes, and one way to draw them.
html
window.runFull = (n, frames) =>
new Promise((done) => {
const ctx = document.getElementById('cv').getContext('2d')
const all = strokes(n)
let f = 0
const tick = () => {
ctx.clearRect(0, 0, 800, 600)
draw(ctx, all) // every stroke, on every frame
draw(ctx, [
[
[10, 10],
[10 + f * 5, 40],
],
]) // the live stroke
if (++f < frames) requestAnimationFrame(tick)
else done()
}
requestAnimationFrame(tick)
})
canvas.html: redraw all strokes, every frame.
html
window.runLayered = (n, frames) =>
new Promise((done) => {
const ctx = document.getElementById('cv').getContext('2d')
const cache = document.createElement('canvas')
cache.width = 800
cache.height = 600
draw(cache.getContext('2d'), strokes(n)) // once, when committed
let f = 0
const tick = () => {
ctx.clearRect(0, 0, 800, 600)
ctx.drawImage(cache, 0, 0) // one copy of the finished strokes
draw(ctx, [
[
[10, 10],
[10 + f * 5, 40],
],
])
if (++f < frames) requestAnimationFrame(tick)
else done()
}
requestAnimationFrame(tick)
})
</script>
canvas.html: copy the cache, draw only the live stroke.
text
Chrome 157, best-of-5 ms per frame, lowest to highest over 4 runs
strokes redraw all layered
1001.2 to 1.6 ms 1.1 to 1.5 ms
10002.6 to 3.2 ms 1.2 to 1.7 ms
500010.7 to 15.3 ms 1.4 to 1.8 ms
Output (Chrome 157, 4x CPU throttling)
Each stroke has 20 points. With 100 strokes the two are close. At 5,000 strokes, redrawing everything took 11 to 15 ms per frame and the layered version about 2 ms. Each cell is the best of five runs, shown as the lowest and highest over four runs of the script on this machine, so only the gap is worth quoting. A frame budget at 60 frames a second is about 16.7 ms, and the full redraw takes most of it before any input work.
For pen and touch there is a second detail. The browser merges many pointer updates into one pointermove, and per MDN getCoalescedEvents() returns the un-coalesced ones, which helps smooth curves in drawing apps. MDN marks it as limited availability and secure contexts only, so it is a progressive enhancement. It was not run here.
Rubric and questions
Signal
Strong looks like, for this prompt
Clarifying
Asks about people and object counts, offline merge, undo, and inputs
Structure
Names the steps, spends the deep-dive minutes on convergence and drawing, and stops on time
Data and API
Gives the edit shape, the three socket messages, and where cursors are kept
Depth
Explains the register, the clock and the tie-break, with the 1,000-trial run, and shows the layered redraw numbers
Cross-cutting care
Offers a text alternative, validates socket input, and keeps cursors out of storage
Communication
Names what last-writer-wins loses, and what the layered canvas costs in memory
Two clients make edits with the same clock value to the same shape. How does every replica pick the same winner?
The client id breaks the tie, so all replicas make the same choice. In the run, b beat a and both screens agreed.
Why is a delete sent as an edit instead of removing the object from the store?
A late move with a lower clock would otherwise bring the shape back. The delete is the newest edit and keeps winning.
At 5,000 strokes the layered canvas took about 2 ms a frame against 11 to 15 ms. Why?
The finished strokes are drawn once into a cache and copied each frame, so only the live stroke is drawn per frame.