\n\n// server.mjs\nimport http from 'node:http';\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\n\nexport function makeServer(pool, faults = { loseResponses: 0 }) {\n const seen = new Map(); // id -> number of requests received\n const srv = http.createServer(async (req, res) => {\n const url = new URL(req.url, 'http://x');\n if (req.method === 'GET' && url.pathname === '/') { res.setHeader('content-type', 'text/html'); return res.end(fs.readFileSync('index.html')); }\n if (req.method === 'GET' && url.pathname === '/outbox.js') { res.setHeader('content-type', 'text/javascript'); return res.end(fs.readFileSync('outbox.js')); }\n const m = url.pathname.match(/^\\/v1\\/inspections\\/([0-9a-f-]{36})$/);\n if (!m || req.method !== 'PUT') { res.statusCode = 404; return res.end(); }\n const tech = Number(req.headers['x-demo-user']);\n if (!tech) { res.statusCode = 401; return res.end(); }\n let raw = ''; for await (const c of req) raw += c;\n let b; try { b = JSON.parse(raw); } catch { res.statusCode = 400; return res.end(); }\n if (typeof b.site !== 'string' || !b.site || typeof b.answers !== 'object' || isNaN(Date.parse(b.completed_at))) {\n res.statusCode = 422; return res.end(JSON.stringify({ error: 'invalid_checklist' }));\n }\n seen.set(m[1], (seen.get(m[1]) || 0) + 1);\n const hash = crypto.createHash('sha256').update(JSON.stringify([b.site, b.answers, b.completed_at])).digest('hex');\n const ins = await pool.query(\n `INSERT INTO inspections (id, technician_id, site, answers, payload_hash, completed_at)\n VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (id) DO NOTHING RETURNING id`,\n [m[1], tech, b.site, b.answers, hash, b.completed_at]);\n let status = 201;\n if (ins.rowCount === 0) { // this id was saved before: replay or clash?\n const { rows: [old] } = await pool.query('SELECT payload_hash, technician_id FROM inspections WHERE id=$1', [m[1]]);\n status = old.payload_hash === hash && old.technician_id === tech ? 200 : 409;\n }\n if (faults.loseResponses > 0) { faults.loseResponses--; return req.socket.destroy(); } // saved, but the answer never arrives\n res.statusCode = status; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ id: m[1] }));\n });\n srv.seen = seen; return srv;\n}\n\n// run.mjs\nimport pg from 'pg';\nimport fs from 'node:fs';\nimport { chromium } from 'playwright';\nimport { makeServer } from './server.mjs';\n\nconst pool = new pg.Pool({ host: 'demo-pg', user: 'postgres', password: 'pw', database: 'postgres' });\nawait pool.query(fs.readFileSync('schema.sql', 'utf8'));\nconst faults = { loseResponses: 1 };\nconst srv = makeServer(pool, faults).listen(3200);\nconst count = async () => (await pool.query('SELECT count(*)::int n FROM inspections')).rows[0].n;\nconst idb = (page) => page.evaluate(() => new Promise((ok) => {\n const r = indexedDB.open('inspections', 1);\n r.onsuccess = () => { const q = r.result.transaction('outbox').objectStore('outbox').getAll(); q.onsuccess = () => ok(q.result.map((i) => i.state + ':' + i.attempts)); };\n}));\nconst text = (page) => page.locator('#status').innerText();\n\nconst browser = await chromium.launch();\nconst ctx = await browser.newContext();\nawait ctx.addInitScript(() => { window.OUTBOX_RETRY = { base: 40, cap: 200 }; });\nconst page = await ctx.newPage();\nawait page.goto('http://127.0.0.1:3200/');\n\n// 1. Technician is in the basement: no signal\nawait page.route('/v1/', (r) => r.abort('internetdisconnected'));\nawait page.fill('#site', 'Plant room B2'); await page.check('#q1');\nawait page.click('#submit');\nconst shown = await (await page.waitForFunction(() => {\n const t = document.getElementById('status').innerText;\n return t.includes('retry automatically') ? t : false;\n})).jsonValue();\nconsole.log('1 offline submit | screen:', shown, '| server rows:', await count(), '| tablet outbox:', (await idb(page)).length);\n\n// 2. Page is reloaded (or the app killed) while still offline: the checklist survives\nawait page.reload();\nawait page.waitForFunction(() => document.getElementById('status').innerText.length > 0);\nconsole.log('2 reload offline | tablet outbox kept:', (await idb(page)).length === 1, '| server rows:', await count());\n\n// 3. Signal returns, but the first success response is lost after the server saved it\nawait page.unroute('/v1/');\nawait page.waitForFunction(() => document.getElementById('status').innerText.startsWith('Sent'));\nconst id = [...srv.seen.keys()][0];\nconsole.log('3 signal back | screen:', await text(page), '| server rows:', await count(), '| server received the same id more than once:', srv.seen.get(id) > 1, '| tablet outbox:', (await idb(page)).length);\n\n// 4. Same id, different content is a clash, not a replay\nconst clash = await fetch(http://127.0.0.1:3200/v1/inspections/${id}, { method: 'PUT', headers: { 'content-type': 'application/json', 'x-demo-user': '7' },\n body: JSON.stringify({ site: 'Other site', answers: {}, completed_at: new Date().toISOString() }) });\nconst bad = await fetch(http://127.0.0.1:3200/v1/inspections/${id}, { method: 'PUT', headers: { 'content-type': 'application/json', 'x-demo-user': '7' }, body: JSON.stringify({ site: '' }) });\nconsole.log('4 same id, other body ->', clash.status, '| empty site ->', bad.status, '| server rows:', await count());\nawait browser.close(); srv.close(); await pool.end();\n\nRun in the mcr.microsoft.com/playwright:v1.48.2-jammy container against postgres:16, it prints:\n\n1 offline submit | screen: Saved on this tablet. Will retry automatically. | server rows: 0 | tablet outbox: 1\n2 reload offline | tablet outbox kept: true | server rows: 0\n3 signal back | screen: Sent. The office has your checklist. | server rows: 1 | server received the same id more than once: true | tablet outbox: 0\n4 same id, other body -> 409 | empty site -> 422 | server rows: 1\n\nReading it: in step 1 the API is blocked, the checklist is on the tablet (outbox 1) and not on the server (0 rows). Step 2 reloads the page while still blocked and the record survives. In step 3 the block is lifted, and the server is told to save the first request and then drop the connection before replying, so the tablet never learns it succeeded. The tablet retries the same id; the server received it more than once yet holds one row, and the screen ends on \"Sent\". Step 4 shows the two refusals: same id with different content gets 409, an empty site gets 422. The four lines are deterministic: they print the same way on repeated runs, because every step waits for a specific screen text or response rather than for a fixed delay, and step 1 prints the text it matched rather than re-reading the screen afterwards (the retry timer can already have changed the screen to \"Sending...\" by then). The driver overrides the retry delays to a base of 40 ms and a cap of 200 ms (window.OUTBOX_RETRY) so the demo finishes in seconds; the shipped defaults are the 2 s and 300 s of the table above.\n\nThe concurrent case, two requests for one id at the same instant, is shown with two database sessions (race.sh, executed inside the Postgres container as the last command of the Running the code section):\n\nP=\"psql -U postgres -qAt\"\n$P -c \"TRUNCATE inspections\"\nINS=\"INSERT INTO inspections (id, technician_id, site, answers, payload_hash, completed_at) VALUES ('11111111-1111-1111-1111-111111111111', 7, 'Plant room B2', '{}', 'h', now()) ON CONFLICT (id) DO NOTHING RETURNING 'inserted'\"\nTS=\"SELECT extract(epoch FROM clock_timestamp())\"\nprintf \"BEGIN;\\n$INS;\\nSELECT pg_sleep(1.5);\\n$TS;\\nCOMMIT;\\n\" | $P > a.out &\nsleep 0.5\n$P -c \"$INS; $TS\" > b.out\nwait\necho \"session A rows inserted: $(grep -c inserted a.out)\"\necho \"session B rows inserted: $(grep -c inserted b.out)\"\necho \"session B returned after A reached its commit: $(awk 'NR==FNR{ if ($1+0>1e9) a=$1; next } { if ($1+0>1e9) b=$1 } END { print (b>a) ? \"true\" : \"false\" }' a.out b.out)\"\n$P -c \"SELECT 'rows in table: ' || count(*) FROM inspections\"\n\nsession A rows inserted: 1\nsession B rows inserted: 0\nsession B returned after A reached its commit: true\nrows in table: 1\n\nHow race.sh proves it, line by line: it empties the table, then starts session A, which opens a transaction, inserts the row, sleeps 1.5 s with pg_sleep and records a timestamp just before committing. Half a second later session B runs the same insert and records a timestamp when it returns. The shell then prints how many rows each session inserted, whether B's timestamp is later than A's (it can only be later if B waited for A's commit), and the row count. Session B's insert waited for session A to commit, then skipped, so the table holds one row. Without the unique key, nothing would make session B wait or skip, and both sessions could insert the same checklist.\n\nDesign choices and what would change them\n\nClient-generated id plus PUT, versus an Idempotency-Key header on POST. Either gives retries a stable identity; the path id makes the server record itself addressable and needs no key-expiry table. If the API must stay POST /inspections for other clients, keep a separate keys table with an expiry and store the first response to replay it.\nTablet clock. completed_at comes from the tablet and can be wrong; received_at is the server's. Show the technician the tablet time, sort and audit by the server time, and do not use completed_at for anything where being wrong has consequences.\nLarge queues. Send oldest first and one at a time, so a slow connection finishes whole checklists rather than starting many.\nAuthentication expiring while offline. The 401 branch in flush() keeps the record queued and prompts for sign-in; the run above does not trigger it. The demo's header user id stands in for a session.\n\nRunning the code\n\ncd work # holds outbox.js index.html server.mjs run.mjs schema.sql race.sh\necho '{\"type\":\"module\",\"dependencies\":{\"pg\":\"8.13.1\",\"playwright\":\"1.48.2\"}}' > package.json\ndocker network create demo-net\ndocker run -d --rm --name demo-pg --network demo-net -e POSTGRES_PASSWORD=pw postgres:16\nuntil docker exec demo-pg pg_isready -h 127.0.0.1 -q; do sleep 1; done\ndocker run --rm --ipc=host --network demo-net -v \"$PWD\":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c 'npm i --silent && node run.mjs'\ndocker cp race.sh demo-pg:/race.sh && docker exec -w /tmp demo-pg bash /race.sh"}},{"@type":"Question","name":"Discuss the trade-offs between keeping controllers thin (pushing logic into services) versus allowing fatter controllers that orchestrate use cases directly. When is the thin-controller approach clearly preferable, and what organizational or technical constraints might make fatter controllers an acceptable choice?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nDefault to thin controllers: the controller parses the request, calls one application-service (use-case) method, and maps the result to a response, while the business logic lives in the service. That default is clearly right as soon as the same logic is reachable from more than one entry point or carries rules worth unit testing. A fatter controller, one that orchestrates the use case itself (calls repositories, applies rules, sends notifications), is an acceptable, deliberate choice for simple CRUD (create, read, update, delete) endpoints with no real rules, for code with a known short life, and for single-entry-point handlers, provided the team knows the trigger that will force a refactor.\n\nThe forces in tension\n\nForce | Favours thin controllers | Favours fatter controllers\n\nReuse | Logic needed by HTTP, queue consumers, batch jobs, CLI | Exactly one entry point, now and foreseeably\nTestability | Rules testable without an HTTP request or web framework | Little logic to test; framework integration tests suffice\nReadability | Each class has one reason to change | Whole flow readable in one place, no jumping across files\nSpeed of delivery | Small upfront cost per feature | Fastest for prototypes and admin screens\nConsistency with codebase | Existing code is layered | Existing framework convention puts logic elsewhere (for example Rails, a popular web framework, keeps logic in models)\n\nWhen thin is clearly preferable\n\nTwo or more entry points. The same \"place order\" rule is triggered by the web API, a mobile API version, a CSV import job and a message consumer.\nNon-trivial rules. Pricing, eligibility, state transitions, money movement.\nTransactions spanning several writes. The unit of work belongs in one testable place, not spread across request-handling code.\nLong-lived product code with several teams. Clear seams (well-defined boundaries between pieces of code, each with one clear responsibility) reduce merge conflicts and review load.\n\nWhen a fatter controller is acceptable\n\nTechnical constraints\nThe endpoint is CRUD over one table with validation only; a service method would just forward the call.\nA serverless function (a cloud-run function that only executes in response to one triggering event, with no server process of your own to manage) handles a single event type and has one caller; the handler is the use case.\nThe framework already provides the layering you would build (validation annotations that declare a field's rules directly on the model, model callbacks that run code automatically before or after a save), and adding a service layer would duplicate it.\n\nOrganizational constraints\nA prototype or experiment with an agreed deletion or rewrite date.\nA small team where consistency with the existing codebase's conventions matters more than a locally better structure; mixing two styles in one codebase is worse than either.\nInternal admin tools whose failure is cheap and whose users are a handful of staff.\n\nIn every case, write down the trigger that ends the exception: \"the first time this logic is needed outside this controller, extract it.\"\n\nWorked example: the second entry point\n\nAn order-placement controller has grown to about 120 lines: it validates stock, applies a discount rule, writes the order, reserves inventory and sends an email. Over the next two quarters the team adds a bulk CSV import job, a mobile API version and a consumer for marketplace orders from a message queue. That is 4 entry points.\n\nOption A, copy the logic. Four copies of the discount rule. When finance changes the rule, the fix lands in 2 of the 4 copies, and marketplace orders keep the old discount for weeks. Nobody notices because each copy has its own tests.\nOption B, extract a PlaceOrder use case. One class with the rule and one set of unit tests; four thin adapters (small pieces of code, one per entry point, whose only job is translating that entry point's input into the call the use case expects). The discount change is one edit.\n\nThe cost of thin-from-the-start was a single extra class. The cost of fat-then-duplicated was a pricing defect. That asymmetry is why thin is the default once reuse is plausible, and why a CRUD admin screen, where reuse is implausible, is the right place to skip it.\n\nPitfalls on both sides\n\nOver-thin: the pass-through service. Every controller method calls a service method with the same name that calls a repository method with the same name. Three layers, zero logic. If a service method has no rule or orchestration, let the controller call the repository for that endpoint, or collapse the layer for that module.\nBusiness rules in request validation. \"Amount must be a number\" is controller work; \"amount must not exceed the credit limit\" is a rule, even though both look like validation.\nFat service, not thin controller. Moving 120 lines into one OrderService with 30 methods trades a fat controller for a god class (a single class that has taken on far too many responsibilities and knows too much about the system). Organize by use case, one class or function per operation.\nHTTP types leaking into services. A service that takes a request object or returns a status code has not actually been separated; it cannot be called from the queue consumer."}},{"@type":"Question","name":"Implement in Python a function that finds the maximum average subarray of length k in an array of floats. While coding, narrate each step, state assumptions, discuss time and space complexity, and walk through one example including k > n and negative numbers. Provide the implementation and explanation.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\nSlide a fixed-size window of length k across the array, maintaining a running SUM (add the element entering the window, subtract the one leaving), track the best sum seen, and divide by k exactly once at the end. Treat k > n as an explicit invalid-input error rather than guessing a fallback, since no window of that length exists. The time complexity is O(n) and the space complexity is O(1) extra.\n\nStructured elaboration, narrated step by step\n1. State the assumption up front. k must satisfy 1 <= k <= n; if k > n, there is no valid window, so raise explicitly rather than returning something like the whole-array average (which would silently answer a DIFFERENT question than the one asked).\n2. Seed the window. Compute the sum of the first k elements directly; this is the sum for the window starting at index 0.\n3. Slide. For each subsequent starting position, update the running sum in O(1): add the element newly entering the window on the right, subtract the element leaving on the left (window_sum += nums[i] - nums[i - k]). This avoids recomputing a fresh sum of k elements for every window, which is what makes the whole scan O(n) instead of O(n*k).\n4. Track the best. Compare each window's sum (not yet divided) against the running best sum.\n5. Divide once, at the end. Return best_sum / k after the loop finishes, rather than dividing inside the loop on every step; the comparison of sums doesn't need the division at all, since dividing by the same constant k never changes which sum is largest.\n6. All-negative arrays. The algorithm needs no special case here: the \"best\" window sum is still correctly the LEAST negative one, exactly analogous to the Kadane's-initialization trap, since nothing in this loop clamps the result toward 0.\n\nWorked example\ndef max_average_subarray(nums, k):\n n = len(nums)\n if k <= 0:\n raise ValueError(\"max_average_subarray: k must be positive\")\n if k > n:\n raise ValueError(f\"max_average_subarray: k={k} exceeds array length n={n}\")\n window_sum = sum(nums[:k])\n best_sum = window_sum\n for i in range(k, n):\n window_sum += nums[i] - nums[i - k]\n if window_sum > best_sum:\n best_sum = window_sum\n return best_sum / k\n\ndef max_average_subarray_brute_force(nums, k):\n n = len(nums)\n best = sum(nums[:k]) / k\n for i in range(1, n - k + 1):\n avg = sum(nums[i:i + k]) / k\n if avg > best:\n best = avg\n return best\n\ncases = [\n ([1.0, 12.0, -5.0, -6.0, 50.0, 3.0], 4),\n ([-1.0, -2.0, -3.0, -4.0], 2),\n ([5.0], 1),\n]\nfor nums, k in cases:\n result = max_average_subarray(nums, k)\n brute = max_average_subarray_brute_force(nums, k)\n print(f\"nums={nums}, k={k} -> max_average={result}\")\n assert abs(result - brute) < 1e-9\n\ntry:\n max_average_subarray([1.0, 2.0, 3.0], 5)\nexcept ValueError as e:\n print(f\"k > n raised ValueError as expected: {e}\")\nprint(\"brute-force cross-check passed for all cases\")\n\nOutput (executed, python3 s70_max_avg_subarray.py, cross-checked against a brute-force O(n*k) implementation for every case):\nnums=[1.0, 12.0, -5.0, -6.0, 50.0, 3.0], k=4 -> max_average=12.75\nnums=[-1.0, -2.0, -3.0, -4.0], k=2 -> max_average=-1.5\nnums=[5.0], k=1 -> max_average=5.0\nk > n raised ValueError as expected: max_average_subarray: k=5 exceeds array length n=3\nbrute-force cross-check passed for all cases\n\nThe all-negative case correctly reports -1.5 (the window [-1.0, -2.0], the least-bad pair), not 0 or an unclamped positive value, and the k > n case raises with a message naming both the offending k and the actual array length rather than failing somewhere less informative.\n\nTrade-offs & pitfalls\nAll-negative arrays. As with Kadane's, don't clamp the result toward 0; the least-negative window average is the CORRECT answer, and a version seeded with best_sum = 0 would silently and wrongly prefer an empty or zero-sum comparison over the true (negative) best.\nDividing inside the loop on every step, instead of once at the end, is unnecessary floating-point work and a common code-review nit, though not a correctness bug at this scale; it also makes the \"compare sums directly\" optimization harder to see.\nAt scale, the same technique underlies real trailing-moving-average code, for example computing a moving average of per-second request counts for rate-limiting or monitoring: the array becomes a live counter rather than a stored list, but the sliding-sum idea is identical. A Go port of that framing would typically keep the running sum as an integer type (e.g. int64, since request counts are naturally integers, and to avoid float accumulation error over a long-running process) and convert to float64 only at the final division, exactly mirroring the \"divide once, at the end\" principle above; it would also express the k > n check as an explicit returned error value rather than a raised exception, matching Go's idiomatic error-handling convention instead of Python's.\nA vectorized (numpy) equivalent trades the explicit Python loop for a cumulative-sum array and slicing, which is the same O(n) asymptotic work but with a much smaller constant factor in practice, useful once the array is large enough that Python's own per-iteration interpreter overhead dominates:\nimport numpy as np\n\ndef max_average_subarray_numpy(nums, k):\n arr = np.asarray(nums, dtype=float)\n n = arr.shape[0]\n if k <= 0 or k > n:\n raise ValueError(f\"max_average_subarray_numpy: invalid k={k} for n={n}\")\n csum = np.cumsum(arr)\n window_sums = np.empty(n - k + 1)\n window_sums[0] = csum[k - 1]\n window_sums[1:] = csum[k:] - csum[:-k]\n return float(window_sums.max() / k)\n\ncases = [\n ([1.0, 12.0, -5.0, -6.0, 50.0, 3.0], 4),\n ([-1.0, -2.0, -3.0, -4.0], 2),\n ([5.0], 1),\n]\nfor nums, k in cases:\n loop_result = max_average_subarray(nums, k)\n numpy_result = max_average_subarray_numpy(nums, k)\n print(f\"nums={nums}, k={k} -> loop={loop_result}, numpy={numpy_result}, match={abs(loop_result - numpy_result) < 1e-9}\")\n assert abs(loop_result - numpy_result) < 1e-9\nprint(\"numpy variant agrees with the loop-based version to within 1e-9 for all three cases\")\n\nOutput (executed, continuing in the same session as the loop-based version above):\nnums=[1.0, 12.0, -5.0, -6.0, 50.0, 3.0], k=4 -> loop=12.75, numpy=12.75, match=True\nnums=[-1.0, -2.0, -3.0, -4.0], k=2 -> loop=-1.5, numpy=-1.5, match=True\nnums=[5.0], k=1 -> loop=5.0, numpy=5.0, match=True\nnumpy variant agrees with the loop-based version to within 1e-9 for all three cases\n\nThe numpy variant agrees with the loop-based version to within 1e-9 for all three cases, confirmed by the explicit comparison above rather than asserted."}},{"@type":"Question","name":"Design a relational multi-tenant schema and deployment strategy for a SaaS product expected to grow to 100,000 tenants, where some tenants are tiny and some are very large. Compare three tenancy models: shared schema with a tenant_id column, a separate schema per tenant, and a separate database per tenant. Discuss indexing, partitioning, backups, cost, tenant migration, and performance isolation for each model, and recommend an approach based on scale and isolation needs.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\nFor a SaaS product scaling to 100,000 tenants of wildly varying size, the right approach is usually tiered: shared schema with a tenant_id column for the long tail of small tenants (cheapest to operate at that volume), with an option to graduate large tenants to their own schema or database as their scale or isolation needs justify the extra operational cost.\n\nStructured elaboration\nShared schema with tenant_id: every table carries a tenant_id column, and every query must filter by it; cheapest to operate (one schema, one connection pool, easy to provision a new tenant instantly), but every table needs tenant_id as a leading column in its indexes for tenant-scoped queries to stay efficient, and a single very large tenant can create a noisy-neighbor problem for everyone sharing the same tables.\nSeparate schema per tenant: isolates each tenant's tables under its own schema in a shared database instance; better isolation (an application bug scoped to the wrong schema fails loudly rather than silently leaking data across tenants) but migrations must run against every tenant schema, and very large tenant counts (100,000) make schema-per-tenant unwieldy to provision and migrate at that scale.\nSeparate database per tenant: the strongest isolation and the easiest tenant-level backup/restore and performance isolation, but the most operationally expensive per tenant, and running 100,000 separate databases is a significant infrastructure and tooling investment most platforms would only take on for their largest, highest-value tenants.\n\nWorked example\nA workable tiered policy: small and medium tenants (the vast majority of 100,000) default to shared-schema with tenant_id, indexed as (tenant_id, ...) on every table, giving cheap onboarding and low per-tenant overhead; the handful of largest tenants (who most need performance isolation and might negotiate dedicated infrastructure contractually) are migrated to their own database, with a defined migration path (export the tenant's rows, provision a dedicated database, replay/backfill, cut over) that the platform builds once and reuses whenever a tenant graduates.\n\nTrade-offs and pitfalls\nIndexing and partitioning: every shared-schema table needs tenant_id as the leading column of its primary access-pattern index; forgetting this on even one table means that table's tenant-scoped queries silently degrade to a full scan as data grows, a very common operational surprise in shared-schema multi-tenancy.\nBackups: shared-schema backups are all-or-nothing for the whole tenant population, so a single tenant needing point-in-time restore of just their own data requires either restoring the whole backup to a scratch environment and extracting their rows, or a per-tenant logical-backup process run on top of the shared physical backup, neither as clean as a genuinely separate database's native backup/restore.\nCost: the tiered approach itself has a real cost, migration tooling and the operational discipline to decide WHEN a tenant graduates tiers; a platform that never builds this graduation path risks either over-provisioning everyone into expensive per-tenant databases from day one, or under-serving its largest tenants by leaving them in a shared schema they've genuinely outgrown."}},{"@type":"Question","name":"You need to know exactly how a closed system behaves and all you have is what goes in and what comes out. How do you work out its rules, and how do you convince yourself and everyone else that what you concluded is right?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nWith a closed system I can only observe from the outside, I build a mental model through controlled experiments: change one input at a time, record what comes out, and form a hypothesis about the rule. What actually earns trust in that hypothesis is trying hard to break it with edge cases before I present it, and showing others the evidence and the attempts to disprove it, not just the concluded rule.\n\nStructured elaboration\n\nCapture a broad baseline first. Before designing experiments, I log a large sample of real input and output pairs so I'm reasoning from actual behavior rather than guessing blind.\nIsolate one variable at a time. I vary a single input dimension while holding everything else fixed and watch how the output moves. That's what actually reveals whether the relationship is linear, threshold-based, or made of distinct categorical rules, rather than assuming a shape and forcing the data to fit it.\nDeliberately probe the edges. Zero, negative numbers, empty values, and maximum-size inputs are where hidden rules usually live, so I test those specifically rather than only the typical middle-of-the-road cases.\nTry to break my own theory. Once I have a rule that explains everything I've seen, I go looking for the input that would prove it wrong, rather than stopping at the first explanation that fits. A rule that survives a real attempt to falsify it is much more trustworthy than one that simply matched three examples.\nBuild a translation layer that only encodes what's actually verified. If the goal is to reproduce or replace the system, I keep an explicit list of the input ranges I've tested versus the ones I haven't, instead of silently extrapolating the rule to territory I never checked.\nRun old and new in parallel before cutting over. Especially where the output is a business-critical number, I run the new logic alongside the original system for a stretch of time, comparing their outputs on the same real inputs, and only cut over once they agree closely enough.\nConvince others with the evidence, not just the conclusion. I show the actual input and output pairs and the specific edge cases I tried to break the theory with, and I put ongoing monitoring in place afterward, because a real closed system can drift or change under you even after you've characterized it once.\n\nWorked example\n\nI once had to characterize a legacy discount-calculation system for an e-commerce platform: no source code, no documentation, just an interface that took an order and returned a final price. I started by pulling a large sample of real orders and their calculated prices to look for patterns. Varying one thing at a time, I found the discount looked linear with order size, until I tested a very small order and got a flat discount instead of a proportional one, which told me there was a hidden minimum threshold I'd have missed by only testing typical-sized orders. I kept probing edges: an order with a single item, an order right at a suspiciously round total, and found the threshold sat at a specific total. To convince myself and the team, I deliberately tried inputs designed to break my rule rather than confirm it, and only once it survived did I trust it. Because this number fed directly into revenue reporting, I built a shadow version alongside the original system and compared their output on live orders for two weeks before anyone trusted the replacement, and documented the one input range (bulk wholesale orders) I genuinely hadn't been able to test, rather than pretending the rule covered it.\n\nTrade-offs and pitfalls\n\nThe main trap is overfitting to too few examples: a rule that explains the five cases you happened to look at can still be wrong, especially if those cases all avoided the actual edges. A close second is mistaking correlation for the system's real rule, for instance assuming a pattern is causal when it's actually a side effect of how the sample data happened to be distributed. Time-dependence and hidden state are the hardest to catch this way, since a system that behaves differently depending on something you can't observe (like time of day, or an internal counter) will look inconsistent no matter how carefully you isolate variables, and the only real defense is watching for that inconsistency and treating it as a signal rather than noise."}},{"@type":"Question","name":"A service calls a third-party API on a user-facing request path. How do you choose timeouts for connecting, waiting for a response, and the operation as a whole, and what should happen when each one fires?","acceptedAnswer":{"@type":"Answer","text":"The idea in plain words\n\nA call to a third-party API can stall in three different places, and each needs its own clock:\n\nConnect timeout: how long you wait to open the network connection (the TCP handshake, which opens a reliable connection, plus TLS, the encryption setup). If this fires, your request was never sent, so retrying is safe.\nResponse (read) timeout: how long you wait for the vendor to answer after the request is sent. In most HTTP client libraries this is the longest silent gap between bytes, not the whole response time, so a slow trickle can evade it. If this fires, the vendor may have processed the request, so retrying is only safe for idempotent calls (calls where repeating has the same effect as doing it once), or for writes protected by an idempotency key (a unique token the client creates once per operation and sends on every attempt, so the vendor treats repeats as one operation).\nOverall deadline: a cap on the whole operation, including every retry and every wait between retries. This is the one tied to the user: it is what stops a slow vendor from holding the user's request open forever.\n\nThe one insight: the timeouts are not independent numbers picked from a default. They are carved out of the budget the user-facing request is allowed to spend, and each one has a planned action when it fires.\n\nMethod, in the order I would do it\n\n1. Start from the user's budget. Assume (illustration) the page or endpoint should answer within 3,000 ms at the slow end, and that our own work takes 800 ms. That leaves 2,200 ms. Keep a safety margin of 700 ms for network and jitter on our side, so the vendor call as a whole gets an overall deadline of 1,500 ms.\n2. Measure the vendor, then set the read timeout just above its tail. The tail is the slowest few percent of calls, and tail latency is how long those take. Assume the vendor's observed 99th percentile (p99: 99 of 100 calls are faster) is 450 ms. A read timeout of 600 ms lets almost every healthy call through and cuts off the stalled ones. A timeout set at the median would cut off about half of the healthy calls; a timeout of 30 seconds (a common library default) means one stalled vendor ties up your workers (the threads or task slots that each handle one request at a time) for 30 seconds each.\n3. Set the connect timeout short. Opening a connection to a healthy host takes tens of milliseconds, so waiting long adds nothing. Assume 200 ms.\n4. Make each attempt's timeout the smaller of its own limit and what remains of the deadline: attempt timeout = min(read timeout, deadline minus time already spent). Never start an attempt you cannot finish: if the remaining budget is smaller than one connect plus a plausible response (here 200 ms is a floor in this illustration), stop.\n5. Decide the action for each timeout before writing code (table below).\n\nTimeout fires | What we know | Action\n\nConnect | Request never left; no side effect | Retry once after a short jittered wait (random delay so many clients do not retry together), if budget remains; count it toward the circuit breaker (described after this table)\nResponse (read) on a read-only call (GET) | Vendor may have worked, but repeating a read is harmless | Retry with the remaining budget, or serve a cached or degraded value\nResponse (read) on a write (POST) | Outcome unknown: the charge or record may exist | Retry only with the same idempotency key. Without one, do not retry blindly: return \"pending\", and reconcile (find out afterwards what really happened) by looking the record up by your own reference\nOverall deadline | Budget spent | Cancel the in-flight call, return a degraded answer to the user (a reduced but still useful reply, such as cached data, \"we will confirm by email\", a queued job), and record the failure\n\nThe circuit breaker is a small state machine kept per vendor, with illustrative settings. Closed: calls flow normally and timeouts are counted. After 5 timeouts in a row it opens: for the next 30 seconds every call fails immediately with no network attempt and goes straight to the degraded answer. After 30 seconds it goes half-open and lets one probe call through; if the probe succeeds the breaker closes, and if it times out the breaker opens for another 30 seconds. In Trace B below a stalled vendor costs each request 1,330 ms; once the breaker is open a request costs the vendor no time at all, and the worker is free for other work.\n\nWorked example: two traces on a 1,500 ms budget\n\nSettings (assumptions): overall deadline 1,500 ms, connect timeout 200 ms, read timeout 600 ms, one 50 ms jittered wait between attempts, no new attempt if less than 200 ms remains.\n\nTrace A, slow connect, then success (a GET).\nAttempt 1: connect timeout fires at 200 ms. Wait 50 ms. Attempt 2: connect takes 80 ms, the response takes 300 ms. Total: 200 + 50 + 80 + 300 = 630 ms, inside 1,500 ms. The user sees a slightly slow page.\n\nTrace B, stalled vendor (a GET).\n\nStep | Event | Clock | Remaining of 1,500\n\n1 | Connect succeeds in 40 ms | 40 ms | 1,460\n2 | Read timeout fires after 600 ms | 640 ms | 860\n3 | Wait 50 ms | 690 ms | 810\n4 | Second connect takes 40 ms | 730 ms | 770\n5 | Attempt timeout = min(600, 770) = 600 ms; vendor stalls again, fires | 1,330 ms | 170\n6 | 170 ms is below the 200 ms floor, so no third attempt: return the cached or degraded answer | 1,330 ms | 170\n\nThe user waits 1,330 ms in the worst case rather than 30 seconds. The same trace shows a cost: each stalled request occupies a worker for the whole 1,330 ms.\n\nWhy the numbers also protect your own capacity\n\nBy Little's law (average number of requests in flight equals arrival rate times average time each stays), if 50 requests per second call the vendor and each stays 0.3 s when healthy, about 50 x 0.3 = 15 are in flight. If every one stalls to the full 1.5 s deadline, about 50 x 1.5 = 75 are in flight, five times the healthy figure. A worker pool sized for 15 will be exhausted, and unrelated features start to fail. So the deadline is a capacity control as well as a latency control. Pair it with a separate, bounded worker pool for the vendor and a circuit breaker.\n\nJudgment calls and what would change them\n\nLong-running vendor operations (report generation, large uploads) do not fit a user-facing deadline. Use an asynchronous pattern: start the job, get an ID, poll or receive a webhook, and give the user a progress state. Timeouts then apply per call, not per job.\nStreaming responses need a read timeout on the gap between chunks plus an overall deadline, because a slow trickle can keep the connection technically alive.\nRetries cost budget: with a 1,500 ms deadline and a 600 ms read timeout, at most two full-length read attempts fit. Raising the retry count without raising the deadline changes nothing, and raising the deadline moves the cost to the user.\nDifferent calls, different budgets: a payment confirmation may justify a longer deadline than a \"suggested contacts\" widget that can simply be omitted.\n\nCommon mistakes\n\nUsing the library default (often no timeout, or tens of seconds) on a user-facing path.\nSetting only a read timeout and no overall deadline, so retries multiply the wait.\nRetrying a timed-out POST with no idempotency key, which can charge a customer twice.\nChoosing the read timeout from the median instead of the tail.\nForgetting to cancel the in-flight request when the deadline fires, so the worker is still held."}}]}

Entry Level Full Stack Developer Interview Preparation Guide - FAANG Standards

Full-Stack Developer
entry
6 rounds
Updated 6/20/2026

This guide is based on general FAANG interview practices and may not reflect specific company procedures.

The entry-level full stack developer interview process at FAANG companies typically consists of 6 rounds designed to assess foundational technical skills across both frontend and backend domains, fundamental problem-solving abilities, end-to-end feature development capability, and cultural alignment. Entry-level candidates are evaluated on understanding core concepts, writing clean code, thinking through problems systematically, and demonstrating strong learning mindset. The process emphasizes fundamentals and versatility rather than deep expertise in either domain, but maintains rigorous standards across all technical rounds.

Interview Rounds

1

Recruiter Screening

2

Technical Phone Screen - Coding Fundamentals

3

Frontend Technical Interview

4

Backend Technical Interview

5

Full Stack Integration Round

6

Behavioral and Culture Fit Interview

Frequently Asked Full-Stack Developer Interview Questions

Cross-Functional CollaborationMediumTechnical
40 practiced

A cross-functional project you're on has a standing weekly meeting, but people are saying the meetings are unproductive and decisions keep stalling. What would you change?

JavaScript and TypeScript FundamentalsMediumTechnical
56 practiced

Write a custom hook that behaves like useState but is generic over the value type, accepts either a value or an updater function, and returns a typed tuple. How do you keep the setter's type honest, and what breaks when you expose a reducer's dispatch through context?

RESTful API DesignEasyTechnical
126 practiced

Explain the architectural difference between a RESTful API and an RPC-style API: how URLs are used, whether the HTTP verb carries meaning, statelessness, resource orientation, and what each style implies for caching and for how tightly the client and server are coupled. Give one situation where you would prefer RPC over REST in a backend service.

Frontend Fundamentals: HTML, CSS, and Responsive StylingEasyTechnical
85 practiced

Explain the mobile-first and desktop-first responsive design strategies. In your answer, define each approach, list pros and cons, and give two practical examples of when you would choose mobile-first over desktop-first for a web product (consider audience, performance, input methods, and feature parity). Also mention how breakpoints are typically organized in CSS (base styles vs overrides), how this affects the cascade and specificity, and implications for bundle size and critical CSS.

End-to-End Feature Design and DevelopmentHardSystem Design
34 practiced

Field technicians fill in an inspection checklist in a web app on tablets, often in basements with no signal. Walk me through how a submitted checklist reaches the server reliably: what the browser stores and where, how and when it retries, how the server avoids saving the same checklist twice, and what the technician sees at each step.

Architectural Patterns and Anti-PatternsMediumTechnical
121 practiced

Discuss the trade-offs between keeping controllers thin (pushing logic into services) versus allowing fatter controllers that orchestrate use cases directly. When is the thin-controller approach clearly preferable, and what organizational or technical constraints might make fatter controllers an acceptable choice?

Arrays, Strings, and HashingMediumTechnical
33 practiced

Implement in Python a function that finds the maximum average subarray of length k in an array of floats. While coding, narrate each step, state assumptions, discuss time and space complexity, and walk through one example including k > n and negative numbers. Provide the implementation and explanation.

Data Modeling and Schema DesignHardSystem Design
40 practiced

Design a relational multi-tenant schema and deployment strategy for a SaaS product expected to grow to 100,000 tenants, where some tenants are tiny and some are very large. Compare three tenancy models: shared schema with a tenant_id column, a separate schema per tenant, and a separate database per tenant. Discuss indexing, partitioning, backups, cost, tenant migration, and performance isolation for each model, and recommend an approach based on scale and isolation needs.

Growth Mindset and Learning AgilityHardTechnical
48 practiced

You need to know exactly how a closed system behaves and all you have is what goes in and what comes out. How do you work out its rules, and how do you convince yourself and everyone else that what you concluded is right?

Third-Party and SaaS IntegrationEasyTechnical
30 practiced

A service calls a third-party API on a user-facing request path. How do you choose timeouts for connecting, waiting for a response, and the operation as a whole, and what should happen when each one fires?

Additional Information

Want to create your own tailored preparation guide using our deep research?

Get Started for Free

Interview-Ready Courses

Visual-first, interactive, structured learning paths

Browse Full-Stack Developer jobs

AI-enriched listings across hundreds of company career pages

Explore Jobs