');\n}).listen(0);\n\nconst browser = await chromium.launch();\nconst page = await browser.newPage();\nawait page.goto(http://127.0.0.1:${server.address().port}/products);\nawait page.click('#b'); // an interaction, so INP has something to report\nawait page.evaluate(() => new Promise((r) => requestAnimationFrame(() => setTimeout(r, 100))));\nawait page.evaluate(() => { // simulate the user leaving: hidden pages flush their metrics\n Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });\n document.dispatchEvent(new Event('visibilitychange'));\n});\nconst deadline = Date.now() + 5000;\nwhile (Date.now() < deadline && new Set(received.map((m) => m.name)).size < 3) await new Promise((r) => setTimeout(r, 50));\nawait browser.close(); server.close();\nconsole.log('beacons received:', [...new Set(received.map((m) => m.name))].sort().join(', '), '| route:', received[0]?.route);\n\n// ---- 2. Judgement: p75 per route and metric, nearest-rank method ----\nconst p75 = (xs) => { const s = [...xs].sort((a, b) => a - b); return s[Math.ceil(0.75 * s.length) - 1]; };\nconst good = { LCP: LCPThresholds[0], INP: INPThresholds[0], CLS: CLSThresholds[0] };\nconsole.log('good thresholds from web-vitals:', JSON.stringify(good));\nconst samples = { // 8 page loads of /checkout, LCP in ms\n '/checkout': { LCP: [1900, 2100, 2200, 2300, 2400, 2600, 3100, 4200] },\n};\n// Known answers pin the nearest-rank method: a max, a floor index or a mean would give a different value.\nconst known = p75([1, 2, 3, 4, 5, 6, 7, 8]) === 6 && p75([10, 20, 30, 40]) === 30 && p75(samples['/checkout'].LCP) === 2600;\nconsole.log('nearest-rank known answers:', known ? 'ok' : 'WRONG');\nlet failed = !known || received.length === 0 || new Set(received.map((m) => m.name)).size < 3;\nfor (const [route, metrics] of Object.entries(samples)) for (const [name, xs] of Object.entries(metrics)) {\n const v = p75(xs); const bad = v > good[name];\n failed ||= bad !== true; // this sample is built to breach: the gate must flag it\n console.log(${route} ${name} p75 = ${v} ms (index ${Math.ceil(0.75 * xs.length) - 1} of ${xs.length} sorted) -> ${bad ? 'OVER' : 'ok'} (good <= ${good[name]}));\n}\nconsole.log(failed ? 'FAIL' : 'PASS: the over-budget sample was flagged');\nprocess.exit(failed ? 1 : 0);\n\nThe first command for this demo in the last section prints this (the /checkout samples are a made-up set of 8 loads chosen to breach the bar, not data from a site):\n\nbeacons received: CLS, INP, LCP | route: /products\ngood thresholds from web-vitals: {\"LCP\":2500,\"INP\":200,\"CLS\":0.1}\nnearest-rank known answers: ok\n/checkout LCP p75 = 2600 ms (index 5 of 8 sorted) -> OVER (good <= 2500)\nPASS: the over-budget sample was flagged\nexit=0\n\nRead the last two lines together: OVER says the route breached the bar, and PASS says the gate did its job by flagging it. This demo ends in PASS because the sample is built to breach; a sample whose p75 was at or under 2,500 ms would print ok and the script would print FAIL, since the point of the run is to prove the check can catch a breach.\n\nThe arithmetic: for 8 sorted values, nearest-rank p75 takes position ceil(0.75 x 8) = 6, which is index 5 counting from 0, so the 6th value, 2,600 ms. The slowest quarter of loads (3,100 and 4,200) is above it, which is why the p75 can exceed the typical load. One page-script detail: web-vitals reports CLS and INP when the page becomes hidden (LCP is final once the user's first input arrives or the page is hidden), so the demo overrides document.visibilityState to hidden and fires visibilitychange, which stands in for a user leaving the page and makes the metrics report without waiting. Browser coverage differs: the README of the pinned web-vitals 4.2.4 lists onCLS and onINP as Chromium-only and onLCP as Chromium and Firefox, and the current README on the main branch lists onCLS as Chromium-only and onINP and onLCP as Chromium, Firefox and Safari, so count how many sessions contribute to each metric's p75 before comparing routes or device classes.\n\nAssign ownership\n\nEvery number has one owner, written next to the budget (the owner field below), not in a wiki that goes stale. A feature team owns its route chunk and its route's field metrics. A platform team owns the shared shell, the vendor chunk, and the measurement itself.\nThird-party tags get an owner and an expiry date. An analytics or chat script nobody owns is a frequent source of drift, and nobody removes it.\nA breach opens a ticket for the named owner, with the deadline fixed by severity (a budget breach on a pull request blocks the merge; a RUM breach for two consecutive weeks goes to the owning team's backlog top and is reviewed in the weekly performance review).\nRaising a budget is a pull request to the budget file, reviewed by the platform owner and the team lead. That makes every increase an explicit, visible trade-off rather than a quiet erosion.\n\nEnforce in layers\n\n1. At pull request. budget-check.mjs reads budgets.json, measures the gzip size of each built chunk, fails the build when a chunk is over, and names the owners to contact. A chunk that has gone missing (renamed, or the build changed) also fails, so the check cannot pass by measuring nothing.\n2. At release. Roll out to a small share of traffic first (a canary: the new release served to a few percent of real visits) and compare its RUM p75 with the rest before going wider. This catches what a lab run cannot: real devices, real networks, real third-party behaviour.\n3. Continuously. Alert on p75 per route over a weekly window, with a minimum sample count so a quiet route does not raise false alarms. A route that spends its error budget (the agreed allowance of time out of target) triggers a feature-freeze on that route (no new features ship there, only changes that improve the metric) until it recovers.\n\n// make-fixture.mjs: writes three stand-in JS chunks with fixed pseudo-random content, so sizes are the same on every run.\nimport fs from 'node:fs';\nconst rng = (seed) => () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };\nconst chunk = (seed, rawKB) => { const r = rng(seed); let s = ''; while (s.length < rawKB 1024) s += 'v' + Math.floor(r() 1e6).toString(36) + (r() < 0.3 ? ';' : ','); return s; };\nfs.rmSync('dist', { recursive: true, force: true });\nfs.mkdirSync('dist/assets', { recursive: true });\nconst grow = process.env.GROW === '1'; // GROW=1 simulates a PR that adds a large library to the shell\nfs.writeFileSync('dist/assets/shell-1a2b.js', chunk(1, 90) + (grow ? chunk(9, 160) : ''));\nfs.writeFileSync('dist/assets/checkout-3c4d.js', chunk(2, 60));\nfs.writeFileSync('dist/assets/search-5e6f.js', chunk(3, 70));\n\nbudgets.json holds one entry per chunk:\n\n[\n { \"chunk\": \"shell\", \"owner\": \"@team-platform\", \"maxGzipKB\": 55 },\n { \"chunk\": \"checkout\", \"owner\": \"@team-payments\", \"maxGzipKB\": 40 },\n { \"chunk\": \"search\", \"owner\": \"@team-discovery\", \"maxGzipKB\": 45 }\n]\n\n// budget-check.mjs: fail the build when a chunk's gzip size is over its budget, and say which team owns it.\nimport fs from 'node:fs'; import zlib from 'node:zlib';\nconst budgets = JSON.parse(fs.readFileSync('budgets.json', 'utf8'));\nconst files = fs.readdirSync('dist/assets');\nconst owners = new Set();\nfor (const b of budgets) {\n const f = files.find((x) => x.startsWith(b.chunk + '-'));\n const kb = f ? zlib.gzipSync(fs.readFileSync(dist/assets/${f})).length / 1024 : NaN;\n const over = !(kb <= b.maxGzipKB); // a missing chunk (NaN) also fails, so a rename cannot hide a regression\n if (over) owners.add(b.owner);\n console.log(${over ? 'OVER' : 'ok '} ${b.chunk.padEnd(9)} ${Number.isNaN(kb) ? 'missing' : kb.toFixed(1).padStart(6) + ' KB'} / ${b.maxGzipKB} KB ${b.owner});\n}\nif (owners.size) { console.log('Blocked. Owners to contact:', [...owners].join(', ')); process.exit(1); }\nconsole.log('All chunks within budget.');\n\nThe second command in the last section runs three cases, with the fixture generator standing in for a build (the sizes are of synthetic chunks, so only the mechanics carry over). It prints:\n\n--- baseline\nok shell 51.7 KB / 55 KB @team-platform\nok checkout 34.6 KB / 40 KB @team-payments\nok search 40.3 KB / 45 KB @team-discovery\nAll chunks within budget.\nexit=0\n--- a pull request adds a large library to the shell\nOVER shell 142.9 KB / 55 KB @team-platform\nok checkout 34.6 KB / 40 KB @team-payments\nok search 40.3 KB / 45 KB @team-discovery\nBlocked. Owners to contact: @team-platform\nexit=1\n--- a chunk is renamed\nok shell 51.7 KB / 55 KB @team-platform\nok checkout 34.6 KB / 40 KB @team-payments\nOVER search missing / 45 KB @team-discovery\nBlocked. Owners to contact: @team-discovery\nexit=1\n\nTrade-offs and common wrong turns\n\nLab-only targets. A lab number can improve while real users get slower (a new third-party tag only fires for logged-in users). Keep RUM as the judge and use the lab as a smoke detector.\nBudgets that are only ever raised. Count budget raises as a metric; if most pull requests raise one, the budget is wrong or the culture is.\nOne shared global budget with no split. The first team to ship uses it up and the last team is blocked for a problem it did not cause. Split it per owner, with a small reserve held by the platform team.\nBlame in place of defaults. Make the fast path the default (the platform provides the image component, the script loader, the route template) so teams follow the budget by following the template.\n\nRunning the code\n\nfolder with the files above; package.json: {\"type\":\"module\",\"private\":true}\ndocker run --rm -v \"$PWD\":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c \\\n 'npm i playwright@1.48.2 web-vitals@4.2.4 && node rum-demo.mjs; echo exit=$?'\ndocker run --rm -v \"$PWD\":/w -w /w node:22 sh -c '\n echo \"--- baseline\"; node make-fixture.mjs && node budget-check.mjs; echo \"exit=$?\"\n echo \"--- a pull request adds a large library to the shell\"; GROW=1 node make-fixture.mjs && node budget-check.mjs; echo \"exit=$?\"\n echo \"--- a chunk is renamed\"; node make-fixture.mjs && mv dist/assets/search-5e6f.js dist/assets/find-5e6f.js && node budget-check.mjs; echo \"exit=$?\"'"}},{"@type":"Question","name":"Three internal microservices each use a different auth scheme, pagination style and error format, and your web app has to render screens from all of them. Design the Backend-for-Frontend that sits in front. What belongs in it, what should stay out of it, and when would you rather normalize in the frontend instead?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nThe BFF (Backend-for-Frontend, a server owned by the web team whose only customer is the web app) should absorb the differences between the services: authentication to each upstream, pagination, error format, timeouts and partial failure, plus the joining and trimming that one screen needs. It should not hold business rules, a database of record, or presentation concerns such as button labels. Normalize in the frontend only when the data comes from a single service, needs no secret, and is already shaped the way the UI wants it.\n\nThe three services in this scenario are a concrete example of the BFF's job: service A uses a bearer token (a credential sent in the Authorization: Bearer header), offset pagination and {error: \"...\"}; service B uses an API key header, cursor pagination and {errors: [{code, detail}]}; service C uses a session cookie (a service session the BFF holds), page numbers and plain-text errors.\n\nThe three pagination styles ask for \"the next page\" in three different ways. Using the same lists as the runnable skeleton below:\n\nStyle | Request for the next page | How the server says there is more\n\nOffset (skip this many items) | GET /orders?offset=3&limit=3 | total: 7, so the client works out that 6 is still below 7\nCursor (a bookmark the server hands back) | GET /tickets?cursor=2 | next_cursor: 4, or null on the last page\nPage number | GET /invoices?page=2 | pages: 2, so page 2 is the last\n\nThe UI wants one pager component, so the BFF turns all three into {items, nextCursor}. An opaque cursor is a string the client sends back unchanged without interpreting it; here \"3\" is an offset for orders while \"2\" is a page number for invoices, and the UI never needs to know.\n\nWhat the BFF does for a single browser request to an account screen: (1) check the browser's session with the BFF; (2) start three upstream calls at once, each with its own credential and a deadline; (3) rewrite each reply into the shared item and error shapes; (4) return one JSON object with one panel per service, so a failed service marks only its own panel.\n\nWhat belongs in the BFF\n\nConcern | What the BFF does | Why here\n\nUpstream authentication | Holds the credential each service wants (token, key, session) and attaches it; the browser only ever holds its own session with the BFF. | B's API key and C's service session cookie are credentials issued to the BFF, not to any user. They cannot be shipped to a browser at all, because anything in page JavaScript can be read by every visitor, so this is not a style choice.\nPagination | Presents one shape to the UI, {items, nextCursor}, with an opaque cursor string; the adapter translates it to offset, cursor or page number. | The UI needs one pager component, not three.\nError format | Maps every upstream failure to {code, message, retryable}. The message is the BFF's own wording; the upstream text stays on the server error object for logs and never reaches the panel. | Upstream messages can leak internals; the UI needs one error component.\nFan-out and failure | Calls upstreams in parallel, each with a deadline, and returns per-panel status instead of failing the whole screen. | One slow or broken service should degrade one panel.\nShaping | Renames and drops fields so the payload matches the screen. | Saves bytes and removes mapping code from the browser.\nRead caching | Caches upstream GETs briefly, and coalesces identical in-flight requests (when a second identical request arrives while the first is still waiting, it shares the first one's result instead of calling the service again). | Protects the services from a screen that fires the same call twice.\n\nWhat stays out\n\nBusiness rules and authorization decisions (is this refund allowed, what does this plan cost). The services own them; the BFF forwards the caller's identity and lets the service decide. If the BFF copies a rule, the next client re-implements it differently.\nIts own database of record. A cache is fine; the only copy of anything is not.\nCross-service transactions. If two writes must succeed together, that is a service-level workflow, not something the web BFF orchestrates.\nPresentation text and layout, such as formatted strings for a button. Keep the payload semantic and let the UI format; otherwise every copy change is a backend deploy.\nBlind retries of writes. Retry only idempotent reads (an idempotent request has the same effect whether it is sent once or five times, as a read does); a repeated POST can double-charge.\n\nA runnable BFF skeleton\n\nThree fake upstreams with the three styles, adapters that normalize them, and a screen function that returns partial results. Run in a node:22 container (Node 22.23.3) with node bff-aggregator.mjs; there is nothing to install.\n\n// Three upstream services with different auth, pagination and error formats,\n// and a BFF that normalizes them into one screen payload.\nimport http from 'node:http';\n\n// ---------- upstream services (stand-ins for internal microservices) ----------\nconst orders = Array.from({ length: 7 }, (_, i) => ({ oid: 100 + i, total: 10 * (i + 1) }));\nconst tickets = Array.from({ length: 5 }, (_, i) => ({ id: 't' + i, subject: 'Issue ' + i }));\nconst invoices = Array.from({ length: 4 }, (_, i) => ({ no: 9000 + i, amount_due: 5 * i }));\n\nfunction listen(handler) {\n return new Promise((res) => {\n const s = http.createServer(handler).listen(0, '127.0.0.1', () => res(s));\n });\n}\nconst json = (r, code, body) => { r.writeHead(code, { 'content-type': 'application/json' }); r.end(JSON.stringify(body)); };\n\n// Service A: bearer token, offset pagination, errors as {error:\"...\"}\nconst A = await listen((q, r) => {\n const u = new URL(q.url, 'http://x');\n if (q.headers.authorization !== 'Bearer svc-a-token') return json(r, 401, { error: 'bad token' });\n const off = +(u.searchParams.get('offset') ?? 0), lim = +(u.searchParams.get('limit') ?? 3);\n json(r, 200, { items: orders.slice(off, off + lim), total: orders.length });\n});\n// Service B: API key header, cursor pagination, errors as {errors:[{code,detail}]}\nconst B = await listen((q, r) => {\n const u = new URL(q.url, 'http://x');\n if (q.headers['x-api-key'] !== 'svc-b-key') return json(r, 403, { errors: [{ code: 'FORBIDDEN', detail: 'bad key' }] });\n const c = +(u.searchParams.get('cursor') ?? 0);\n const data = tickets.slice(c, c + 2);\n json(r, 200, { data, next_cursor: c + 2 < tickets.length ? c + 2 : null });\n});\n// Service C: session cookie, page-number pagination, errors as plain text. Mode: 'ok', 'down' (503) or 'hang' (never answers).\nlet cMode = 'ok';\nconst C = await listen((q, r) => {\n if (cMode === 'hang') return;\n if (cMode === 'down') { r.writeHead(503, { 'content-type': 'text/plain' }); return r.end('pool exhausted on db-7 (10.0.3.9)'); }\n const u = new URL(q.url, 'http://x');\n if (q.headers.cookie !== 'sid=svc-c-session') { r.writeHead(401, { 'content-type': 'text/plain' }); return r.end('login required'); }\n const p = +(u.searchParams.get('page') ?? 1), size = 2;\n json(r, 200, { results: invoices.slice((p - 1) size, p size), page: p, pages: Math.ceil(invoices.length / size) });\n});\nconst url = (s) => http://127.0.0.1:${s.address().port};\n\n// ---------- the BFF: adapters hide auth, pagination and error differences ----------\n// One normalized error shape and one normalized page shape: {items, nextCursor}\nclass UpstreamError extends Error {\n constructor(source, status, code, message) { super(message); Object.assign(this, { source, status, code }); }\n get retryable() { return this.status >= 500 || this.status === 429; }\n}\nasync function call(source, u, headers) {\n const ctl = AbortSignal.timeout(500); // every upstream call has a deadline\n const res = await fetch(u, { headers, signal: ctl });\n const text = await res.text();\n if (!res.ok) {\n let code = 'UPSTREAM_' + res.status, message = text;\n try { const j = JSON.parse(text); message = j.error ?? j.errors?.[0]?.detail ?? text; code = j.errors?.[0]?.code ?? code; } catch {}\n throw new UpstreamError(source, res.status, code, message);\n }\n return JSON.parse(text);\n}\nconst adapters = {\n orders: async (cursor) => { // cursor is the offset, encoded as a string\n const off = cursor ? +cursor : 0;\n const j = await call('orders', ${url(A)}/orders?offset=${off}&limit=3, { authorization: 'Bearer svc-a-token' });\n const next = off + j.items.length;\n return { items: j.items.map((o) => ({ id: String(o.oid), amount: o.total })), nextCursor: next < j.total ? String(next) : null };\n },\n tickets: async (cursor) => {\n const j = await call('tickets', ${url(B)}/tickets?cursor=${cursor ?? 0}, { 'x-api-key': 'svc-b-key' });\n return { items: j.data.map((t) => ({ id: t.id, title: t.subject })), nextCursor: j.next_cursor === null ? null : String(j.next_cursor) };\n },\n invoices: async (cursor) => {\n const p = cursor ? +cursor : 1;\n const j = await call('invoices', ${url(C)}/invoices?page=${p}, { cookie: 'sid=svc-c-session' });\n return { items: j.results.map((i) => ({ id: String(i.no), due: i.amount_due })), nextCursor: p < j.pages ? String(p + 1) : null };\n },\n};\n// The screen endpoint: one browser request, three parallel upstream calls, partial results allowed.\nasync function accountScreen() {\n const names = Object.keys(adapters);\n const settled = await Promise.allSettled(names.map((n) => adaptersn));\n const panels = {};\n settled.forEach((s, i) => {\n // Only UpstreamError is a normalized failure. A timeout (DOMException) or a refused connection (TypeError) is not,\n // and a DOMException has its own numeric code (23 for a timeout), so check the type instead of reading .code.\n const e = s.reason;\n panels[names[i]] = s.status === 'fulfilled'\n ? { status: 'ok', ...s.value }\n : { status: 'error', error: e instanceof UpstreamError\n ? { code: e.code, message: ${names[i]} service failed (HTTP ${e.status}), retryable: e.retryable } // e.message (the upstream text) stays server-side, for logs\n : { code: 'UNAVAILABLE', message: 'upstream did not answer', retryable: true } };\n });\n return panels;\n}\n\nconsole.log('--- all upstreams healthy ---');\nconsole.log(JSON.stringify(await accountScreen()));\nconsole.log('--- page 2 of orders through the same normalized cursor ---');\nconsole.log(JSON.stringify(await adapters.orders('3')));\nconsole.log('--- invoices service down ---');\ncMode = 'down';\nconst degraded = await accountScreen();\nconsole.log(JSON.stringify({ orders: degraded.orders.status, tickets: degraded.tickets.status, invoices: degraded.invoices }));\nconsole.log('--- invoices service hangs: the 500 ms deadline fires ---');\ncMode = 'hang';\nconst t0 = Date.now();\nconst hung = await accountScreen();\nconsole.log(JSON.stringify({ orders: hung.orders.status, invoices: hung.invoices }), 'waited under 1 s:', Date.now() - t0 < 1000);\nconsole.log('--- wrong credential on service A: the thrown error keeps the upstream detail for server logs ---');\ntry { await call('orders', ${url(A)}/orders, { authorization: 'Bearer nope' }); } catch (e) { console.log(e.source, e.status, e.code, e.message, 'retryable=' + e.retryable); }\n[A, B, C].forEach((s) => { s.closeAllConnections(); s.close(); });\n\nIt prints:\n\n--- all upstreams healthy ---\n{\"orders\":{\"status\":\"ok\",\"items\":[{\"id\":\"100\",\"amount\":10},{\"id\":\"101\",\"amount\":20},{\"id\":\"102\",\"amount\":30}],\"nextCursor\":\"3\"},\"tickets\":{\"status\":\"ok\",\"items\":[{\"id\":\"t0\",\"title\":\"Issue 0\"},{\"id\":\"t1\",\"title\":\"Issue 1\"}],\"nextCursor\":\"2\"},\"invoices\":{\"status\":\"ok\",\"items\":[{\"id\":\"9000\",\"due\":0},{\"id\":\"9001\",\"due\":5}],\"nextCursor\":\"2\"}}\n--- page 2 of orders through the same normalized cursor ---\n{\"items\":[{\"id\":\"103\",\"amount\":40},{\"id\":\"104\",\"amount\":50},{\"id\":\"105\",\"amount\":60}],\"nextCursor\":\"6\"}\n--- invoices service down ---\n{\"orders\":\"ok\",\"tickets\":\"ok\",\"invoices\":{\"status\":\"error\",\"error\":{\"code\":\"UPSTREAM_503\",\"message\":\"invoices service failed (HTTP 503)\",\"retryable\":true}}}\n--- invoices service hangs: the 500 ms deadline fires ---\n{\"orders\":\"ok\",\"invoices\":{\"status\":\"error\",\"error\":{\"code\":\"UNAVAILABLE\",\"message\":\"upstream did not answer\",\"retryable\":true}}} waited under 1 s: true\n--- wrong credential on service A: the thrown error keeps the upstream detail for server logs ---\norders 401 UPSTREAM_401 bad token retryable=false\n\nReading the code: AbortSignal.timeout(500) gives each upstream call a signal that aborts the fetch after 500 ms (MDN documents the abort reason as a TimeoutError), so a hung service cannot hold the screen. Promise.allSettled waits for all three adapter promises and returns one {status: 'fulfilled' | 'rejected'} entry per input, in input order, without rejecting itself when one input fails; that is why one dead service becomes one error panel instead of a failed screen. Only an UpstreamError is a normalized failure. A timeout rejects with a DOMException and a refused connection with a TypeError; neither is an UpstreamError, so the screen function checks the type with instanceof and labels them UNAVAILABLE, retryable: true, with a fixed message so no raw internals reach the UI. Reading reason.code instead would be a bug: a timeout's DOMException carries the legacy numeric code 23, which would leak into the panel as \"code\":23.\n\nReading the output: the screen came back from one function call with three panels, each carrying its own status. With service C returning 503 (its body, pool exhausted on db-7 (10.0.3.9), is internal detail), orders and tickets are still ok and invoices carries a normalized, retryable error whose message is the BFF's own invoices service failed (HTTP 503); the upstream text does not reach the panel. With service C hanging instead, the 500 ms deadline fires and the panel comes back as UNAVAILABLE in well under a second while orders stays ok. A wrong credential on service A (401) is an UpstreamError with retryable=false, because a client retry cannot fix a bad token; the last line prints bad token, the upstream detail that stays on the server-side error for logging, while the screen function would give the panel the BFF's own message. The normalized cursor for orders (\"3\") is the BFF's own opaque token; the UI never learns it is an offset.\n\nWhen pagination crosses services\n\nEach panel paginates itself, so no cross-service ordering is needed. If a screen needs one merged, sorted list across services, the BFF fetches a page from each, merges, and returns a cursor that encodes every source's position. Do that only when the product needs it: it multiplies upstream calls per page and makes the cursor fragile if any source reorders.\n\nWhen to normalize in the frontend instead\n\nChoose frontend normalization when all of these hold:\n\n1. The screen reads one service, so there is nothing to aggregate.\n2. The service needs no secret the browser cannot hold (public data, or the user's own login cookie where the browser and the service share a site, so the browser attaches the cookie itself and no secret sits in page JavaScript; this is different from a service credential such as C's session above).\n3. The difference is presentational: sorting, grouping or formatting data the UI already has, or interaction state such as an optimistic list update (showing a newly added row immediately, before the server has confirmed it).\n4. The BFF would add a hop and an owner for no gain, for example a prototype or a team without capacity to run one more service.\n\nAnything that needs a secret, a join, or a unified error contract across services goes in the BFF.\n\nTrade-offs and pitfalls\n\nThe BFF is a new single point of failure for the web app. Mitigate with deadlines per upstream, partial responses (as shown), and health checks per adapter.\nAdapters are the part that rots: when service B changes its error format the BFF breaks. Cover each adapter with contract tests (tests that feed the adapter a recorded or fake copy of the service's reply format and fail when the format changes), as the fake upstreams here do in miniature.\nKeep the BFF thin. When a feature request starts with \"the BFF should decide\", check whether the rule belongs in a service.\nDo not leak adapter differences through the contract: a panel field called nextOffset in one panel and next in another defeats the point."}},{"@type":"Question","name":"What is a promise and what states can it be in? Walk through what happens when you attach a handler before it settles and after it settles, why a handler never runs synchronously, and what a thenable is.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nA promise is an object that stands for the eventual result of an asynchronous operation. It starts pending and settles exactly once, either fulfilled (with a value) or rejected (with a reason, usually an Error). After it settles it never changes. You attach handlers with .then, .catch and .finally. A handler attached before the promise settles waits in the promise's reaction list (the promise's internal list of handlers waiting for it to settle); a handler attached after it settled is queued straight away. Either way the handler never runs synchronously: the engine always runs it later as a microtask, so a caller never sees a callback fire before the line that registered it has finished. A thenable is any object with a then method; resolve(), Promise.resolve() and await adopt it (take over its outcome, so the new promise settles however the thenable settles) by calling its then, which is how different promise libraries interoperate.\n\nStates and the one-way rule\n\nState | Meaning | Can change to\n\npending | Work not finished | fulfilled or rejected\nfulfilled | Finished with a value | nothing (final)\nrejected | Failed with a reason | nothing (final)\n\n\"Settled\" means fulfilled or rejected. Calling resolve or reject a second time has no effect, which the example below demonstrates.\n\nHandlers before and after settling, and why they are never synchronous\n\nThe program below puts every case in one run and prints the order.\n\nconst out = [];\nconst log = (m) => out.push(m);\n\n// 1. Handler attached after the promise already settled: it still runs later, never inline.\nconst settled = Promise.resolve('value');\nlog('sync: before then()');\nsettled.then((v) => log('handler on already-settled promise got ' + v));\nlog('sync: after then()');\n\n// 2. Handler attached before settlement: queued until resolve is called.\nlet resolveLater;\nconst pending = new Promise((res) => { resolveLater = res; });\npending.then((v) => log('handler attached while pending got ' + v));\nlog('sync: resolving now, handler has not run');\nresolveLater('later');\n\n// 3. A thenable: any object with a then method is adopted by resolve / await.\nconst thenable = { then(onFulfilled) { log('then() of the thenable called'); onFulfilled('from thenable'); } };\nPromise.resolve(thenable).then((v) => log('adopted value: ' + v));\n\n// 4. finally: runs on either outcome, gets no argument, passes the original result through.\nPromise.reject(new Error('boom'))\n .finally((...args) => log('finally ran with ' + args.length + ' arguments'))\n .catch((e) => log('catch still sees ' + e.message));\n\n// 5. Wrapping a callback API with new Promise\nfunction legacyRead(cb) { setTimeout(() => cb(null, 'file contents'), 1); }\nconst readP = () => new Promise((resolve, reject) => legacyRead((err, data) => (err ? reject(err) : resolve(data))));\nreadP().then((v) => log('wrapped callback API gave ' + v));\n\n// 6. States are one-way: a second resolve is ignored\nconst once = new Promise((res, rej) => { res('first'); res('second'); rej(new Error('ignored')); });\nonce.then((v) => log('settled once with ' + v));\n\nsetTimeout(() => {\n console.log(out.join('\\n'));\n console.log('handlers never ran inline:', out.indexOf('sync: after then()') < out.indexOf('handler on already-settled promise got value'));\n}, 30);\n\nRun in a Node 22 container, it prints:\n\nsync: before then()\nsync: after then()\nsync: resolving now, handler has not run\nhandler on already-settled promise got value\nhandler attached while pending got later\nthen() of the thenable called\nfinally ran with 0 arguments\nsettled once with first\nadopted value: from thenable\ncatch still sees boom\nwrapped callback API gave file contents\nhandlers never ran inline: true\n\nReading the output. Handlers go into the microtask queue in the order the promises were ready for them, and a job that queues more work puts it at the back. After the synchronous code finishes, the queue holds five jobs, in source order: the handler on the already-settled promise (case 1), the handler on the promise resolved by resolveLater (case 2), the job that will call the thenable's then (case 3), the finally handler (case 4) and the settled once handler (case 6). They run in that order, which gives lines 4 to 8, except that the thenable's handler is not in the queue yet:\n\nThe thenable job calls then() of the thenable (line 6). That call resolves the promise, and only then is the adopted value handler queued, at the back of the queue, behind the finally and settled once jobs. That is why adopted value (line 9) prints after settled once (line 8), and then() of the thenable called (line 6) prints before finally ran (line 7): the thenable job was queued before the finally handler, but its handler needs a second queue pass.\nThe catch still sees boom line (line 10) comes later still, because finally itself returns an internal promise that must settle before the rejection continues down the chain.\n\nAttached after settling: Promise.resolve('value').then(...) registers a handler on an already-fulfilled promise. The sync: lines show the handler did not run inline; it ran after the script's synchronous code finished.\nAttached before settling: the handler waits while the promise is pending; calling resolveLater moves it into the microtask queue, but still not inline.\nWhy never synchronous: if a handler could sometimes run immediately (already settled) and sometimes later (pending), the same code would have two different orderings depending on timing. Always deferring gives one predictable order, and callers can rely on finishing their own setup first. The same reason applies to the thenable line: Promise.resolve(thenable) does not call thenable.then immediately, it queues that call as a microtask, so the adopted value arrives one queue pass later than an ordinary resolved value: first a job calls the thenable's then, then the handler is queued.\nThenable: the object with a then(onFulfilled) method was adopted: its then was called with resolver functions, and its value became the promise's result.\nfinally: runs on success or failure, receives no argument (0 arguments in the output), and passes the original outcome through, so the following catch still saw the original boom error.\nSettle once: res('first'); res('second'); rej(...) kept only the first.\n\nWrapping a callback API with new Promise\n\nCallback APIs use cb(err, data). Wrap them once so the rest of the code can use promises or await:\n\nconst readP = () => new Promise((resolve, reject) =>\n legacyRead((err, data) => (err ? reject(err) : resolve(data))));\n\nThe executor is the function passed to new Promise((resolve, reject) => ...). It runs synchronously and immediately; only the handlers are deferred. For Node's standard error-first functions, util.promisify does this wrapping for you.\n\nCallbacks versus promises\n\nCallback | Promise\n\nWho controls when your code runs | The API that receives your function; it could call it twice, never, or synchronously | The promise: settles once, and handlers run once, asynchronously\nErrors | Passed as the first argument, you must check each time | A rejection travels down the chain to the next .catch\nComposition | Nested functions | Chains, Promise.all, and await\n\nPitfalls\n\nForgetting to return a promise inside a .then: the next step does not wait for it.\nThrowing inside a new Promise executor works (it rejects the promise), but throwing inside a plain callback inside it, after the executor returned, does not. The first promise below is rejected and caught; the second stays pending forever and the error escapes as a process-level uncaughtException.\n\nprocess.on('uncaughtException', (e) => console.log('uncaughtException:', e.message));\n\n// Throwing directly in the executor rejects the promise.\nnew Promise(() => { throw new Error('sync throw'); })\n .catch((e) => console.log('caught:', e.message));\n\n// Throwing inside a timer callback started by the executor does not: the executor\n// has already returned, so the error is not turned into a rejection.\nconst p = new Promise(() => { setTimeout(() => { throw new Error('late throw'); }, 0); });\np.catch(() => console.log('never printed'));\n\nRun in a node:22 container as late_throw.js (Node 22), it prints:\n\ncaught: sync throw\nuncaughtException: late throw\n\nTreating finally as a place to transform the result: its return value is ignored unless it throws or returns a rejected promise.\n\nRunning the code\n\ndocker run --rm --ulimit core=0 -v \"$PWD\":/w -w /w node:22 node promise_states.js\ndocker run --rm --ulimit core=0 -v \"$PWD\":/w -w /w node:22 node late_throw.js\n\nSave the large block as promise_states.js and the pitfall block as late_throw.js. Both are CommonJS files and need no install or config."}},{"@type":"Question","name":"Tell me about a time a stakeholder changed a core requirement, scope, or definition partway through a project you were running, for example a metric definition changed, scope was added or cut, or a new constraint appeared. Walk through how you assessed the impact, replanned the work, communicated the trade-offs to stakeholders, and what the outcome was.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nAssess the impact by measuring what actually changes downstream, not just describing the change; replan by cutting the lowest-value remaining piece first rather than sliding the whole date by default; give a specific revised estimate, not a vague one; and keep a durable, written record of the decision so the trade-off doesn't have to be relitigated later.\n\nSTAR skeleton to fill in\n\nSituation: the project, and exactly what a stakeholder changed (a metric definition, added or cut scope, or a new constraint).\nTask: what you owned delivering.\nAssess impact: what you measured to know how big the change actually was.\nReplan: what you cut, reordered, or descoped, and why that piece specifically.\nEstimate and documentation: the specific added-work estimate, the revised timeline, and where you recorded the decision so it's not lost.\nCommunicate trade-offs: the options you gave the stakeholder, with numbers attached.\nOutcome: what actually shipped, when, and how you validated it was correct.\n\nWorked example instance\n\nSituation: five weeks into an eight-week project building a customer-health-score dashboard, the sponsoring VP changed the definition of \"active customer\" (a core input) from \"logged in within 30 days\" to \"logged in within 30 days OR made an API call within 30 days,\" to better reflect API-heavy accounts. Assess impact: I pulled the actual data. Under the old definition, 62,000 of 90,000 customers counted as active on the same day; under the new definition, 74,000 did, a 19% increase (74,000 minus 62,000, divided by 62,000), both counts measured the same way, as a point-in-time snapshot of the same 90,000 customer base. That meant four of the dashboard's seven downstream metrics that use the active-customer denominator needed re-derivation, and two already-built visualizations needed re-validation. Replan: rather than push the whole delivery date, I cut one \"nice-to-have\" segmentation view that didn't depend on the changed definition, and sequenced the redefinition fix first since everything else depended on it. Estimate and documentation: I estimated three additional engineering days (roughly 0.75 days per affected metric, based on the team's own history with definition changes of similar scope) plus one day of quality-assurance (QA) re-validation, moving the ship date from week eight to week eight plus four working days. I logged the change in the team's existing requirement-change log, a shared record of what changed, who requested it, the impact assessment, and the decision made, including the sponsor's explicit sign-off on cutting the segmentation view. Communicate trade-offs: I gave the VP two options with the numbers above: slip under a week and keep full scope, or hit the original date by cutting the segmentation view. She chose the slip. Outcome: we shipped four working days late, with the corrected definition applied consistently across all seven metrics, validated by hand-checking 20 customer records against both definitions before sign-off. A month later, a different stakeholder asked why an old cached export didn't match the dashboard, and the change log was the exact record that answered it without re-litigating the decision from scratch.\n\nSecond example (different discipline): a recruiting operations lead running a hiring-pipeline redesign gets a new mid-project constraint: legal requires a specific data-retention limit on candidate records that wasn't in the original scope. She assesses impact (three of nine pipeline stages store data past the new limit), estimates two extra days of rework, documents the change and legal's sign-off in the project's decision log, and tells the hiring stakeholders about the two-day slip rather than silently absorbing it.\n\nTrade-offs and pitfalls\n\nThe mediocre move is skipping the actual measurement of impact (\"it affected a few things\") and skipping the estimate and revised timeline entirely, jumping straight from \"the requirement changed\" to \"we adjusted and it worked out.\" That's exactly the vague trade-off reasoning that fails to show real judgment. A subtler pitfall is treating the conversation as the record: without a written log, the same trade-off gets re-argued the next time someone notices the discrepancy."}},{"@type":"Question","name":"Describe a technical decision you had to make without complete information. Stakeholders disagreed on how much risk was acceptable. How did you reach a recommendation, and how did you communicate the uncertainty that remained?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nI separate the decision into what's actually unknown, what's knowable in the time available, and what we simply have to accept as risk, then I get stakeholders to state their risk tolerance in concrete terms instead of arguing about the plan in the abstract. I make the recommendation defensible by documenting the assumptions and the trigger conditions that would make us reverse it, so the reasoning survives even if the outcome doesn't.\n\nHow I structure a decision with incomplete information\n\nList the knowns, the unknowns, and what each unknown costs if it goes the wrong way. Not every unknown is worth resolving; the ones worth spending time on are the ones whose failure mode is expensive.\nTurn \"how much risk is acceptable\" into a concrete question. Instead of asking stakeholders whether they're comfortable with risk, I ask what specific loss they can tolerate and what signal would tell us we crossed the line. That turns a values disagreement into a measurable threshold people can actually agree on.\nPick the option whose worst case is recoverable, not the option with the best expected case, when the unknowns are large. A decision that can be cheaply undone is worth more than its expected value suggests, because it buys time to learn the thing you don't currently know.\nWrite the recommendation down with its assumptions and its reversal trigger, before the rollout starts, not after. If I'm wrong, the paper trail should make it obvious what changed, not just that it failed.\n\nWorked example\n\nA team was migrating a sharded datastore to a new partitioning scheme ahead of a growth push, and the traffic pattern for the new user segment driving that growth wasn't fully characterized yet: we had projections, not production data. Product wanted to cut over before the segment launched to avoid a second migration later; the SRE team wanted to wait for real traffic data before committing to a partition key, worried about a bad key choice causing hot shards that would need a second, more disruptive migration to fix.\n\nI laid out the actual unknowns: how skewed the new segment's access pattern would be, and how expensive a second migration would be if the first key choice was wrong. I asked the SRE team to state the concrete failure mode they were protecting against (sustained P99 latency degradation on the hottest shard) and asked product what loss was acceptable if we waited (a fixed number of weeks of delay to the growth push). Both were quantifiable once stated that way. I recommended a phased cutover: migrate on the best-available projected key, but keep the old sharding scheme's routing code live and instrument shard-level load so we would have real signal within the first two weeks of the new segment's traffic, with an explicit threshold (sustained shard imbalance past a set point) that would trigger a second, corrective repartition rather than an emergency one. I documented the projection we used, why we chose it over waiting, and the exact signal that would tell us it was wrong.\n\nTrade-offs and pitfalls\n\nTreating \"we don't have enough data\" as a reason to wait indefinitely. Waiting has a cost too; the discipline is comparing the cost of waiting against the cost of a wrong guess you can detect and correct quickly.\nLetting the loudest stakeholder's risk tolerance become the default. Stating tolerance in concrete, comparable terms is what prevents the decision from just reflecting whoever argued longest.\nSkipping the instrumentation that would tell you if you were wrong. A phased decision without a real signal to watch is not actually phased, it's just a delayed all-at-once bet.\nDocumenting the decision but not the trigger for reversing it. A record of \"why we chose this\" without \"what would make us change it\" doesn't actually reduce risk, it just explains the risk after the fact."}},{"@type":"Question","name":"Explain accessible form control patterns: explicit labels, label positioning, when to use aria-labelledby or aria-describedby, why placeholders are not substitutes for labels, required-field indicators, and how to associate error messages programmatically for screen readers.","acceptedAnswer":{"@type":"Answer","text":"Direct answer. Every form control needs a programmatically associated label, not just a visually adjacent one, using an explicit