Entry Level Full Stack Developer Interview Preparation Guide - FAANG Standards
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
Recruiter Screening
What to Expect
Initial 30-minute conversation with a recruiter to verify basic qualifications, assess communication skills, and gauge cultural alignment. The recruiter will discuss your background, motivation for full stack development, understanding of the role, and determine if you're ready for technical rounds. This is a qualifying round designed to ensure you meet minimum entry-level standards and have genuine interest in the position.
Tips & Advice
Be enthusiastic but realistic about your current skill level as an entry-level candidate. Prepare a concise explanation of your background (self-taught, bootcamp, university, etc.), specific projects demonstrating full-stack work, and why you're interested in full stack development specifically. Research the company beforehand and mention something specific you find interesting (a product, recent announcement, engineering blog). Have clear reasons for why you want to work there and for this role. Practice explaining your most impressive project in 2-3 minutes. Be natural and authentic rather than scripted. Ask thoughtful questions about the role and team. Remember this is also your chance to assess if the company is a good fit for you - ask about mentorship, learning opportunities, and team dynamics.
Focus Topics
Communication and Professional Presence
Clear communication, active listening, appropriate tone and energy level, and professional demeanor during the phone/video call. Ability to answer directly, ask clarifying questions, and engage naturally in conversation.
Practice Interview
Study Questions
Motivation for Full Stack Development Role
Clear explanation of why you're interested in full stack development specifically (versus frontend or backend only), why you're interested in the company, and how the role aligns with your career goals. Entry-level candidates should emphasize learning mindset and growth potential.
Practice Interview
Study Questions
Background and Full Stack Development Journey
Clear, concise articulation of your educational background, how you learned to code, any internships or bootcamp experience, and specific full-stack projects you've built. For entry-level, demonstrating genuine interest and foundational knowledge matters more than extensive experience. Focus on breadth (frontend and backend skills) rather than depth in one area.
Practice Interview
Study Questions
Technical Phone Screen - Coding Fundamentals
What to Expect
45-60 minute technical interview via phone or video featuring 1-2 coding problems of Easy to Medium difficulty on platforms like HackerRank, LeetCode, or CodeSignal. You'll solve problems using a shared online editor, typically without autocomplete or syntax hints. The interviewer assesses your problem-solving approach, code quality, communication, and ability to think through solutions. This round focuses on core data structures (arrays, strings, linked lists) and basic algorithms rather than full stack-specific knowledge.
Tips & Advice
Before coding, ask clarifying questions about inputs, constraints, edge cases, and expected output. State your approach and discuss trade-offs before starting to code. Think aloud so the interviewer can follow your reasoning. Write clean, readable code with meaningful variable names and appropriate comments. Start with a working solution even if not optimized, then optimize if time permits. Test your solution mentally with 2-3 test cases before declaring it complete. If you get stuck, explain your thought process and ask for hints - this is better than silence. For entry-level, correctness matters more than optimal Big O complexity, but show awareness of efficiency. Practice on LeetCode Easy and Medium problems focusing on arrays, strings, linked lists, sorting, and basic searching. Code in the language you're most comfortable with. Practice in realistic environments (Google Docs or CoderPad without autocomplete).
Focus Topics
Code Quality and Debugging
Writing clean, readable code with meaningful variable names, avoiding magic numbers, proper code organization, and mentally testing edge cases. Ability to catch and fix bugs in your own code and handle error cases appropriately.
Practice Interview
Study Questions
Communication and Collaboration During Technical Problem-Solving
Clearly explaining your thought process, asking clarifying questions before diving into code, discussing your approach and trade-offs with the interviewer, walking through test cases, and explaining your solution when complete.
Practice Interview
Study Questions
Arrays and String Manipulation
Fundamental operations on arrays and strings including indexing, iteration, searching, sorting, and basic transformations. Understanding how to manipulate these foundational data structures efficiently and writing clean code to solve common array/string problems.
Practice Interview
Study Questions
Basic Algorithm Design and Approach
Ability to break down a problem into logical steps, identify an appropriate solution strategy (brute force, iteration, recursion, etc.), and implement a working solution. Understanding time and space complexity at a basic level and recognizing obviously inefficient approaches.
Practice Interview
Study Questions
Frontend Technical Interview
What to Expect
60-90 minute technical interview focused on frontend technologies and full-stack developer responsibilities related to client-side development. You'll complete a coding task to build a UI component or feature using HTML, CSS, and JavaScript (possibly within a framework like React). Tasks might include building an interactive form with validation, creating a dynamic component with state management, implementing a specific CSS layout, or fetching data from an API and displaying it. You're evaluated on your ability to create semantic HTML, style effectively with CSS, implement interactivity with JavaScript, and understand modern frontend frameworks.
Tips & Advice
Start by clarifying requirements, design specifications, and browser compatibility expectations. Build incrementally - structure with HTML first, then add styling, then add JavaScript behavior. Use semantic HTML5 elements (header, nav, main, article, section, etc.) to show best practices. Demonstrate CSS knowledge by using modern layout techniques like flexbox or CSS Grid rather than floats. Write clean, event-driven JavaScript with proper event listeners and state management. If using a framework like React, focus on component composition, props, and state management fundamentals. Test your implementation as you work. Be prepared to discuss accessibility (ARIA attributes, keyboard navigation), responsive design for different screen sizes, and performance considerations. Show clear separation of concerns between HTML (structure), CSS (presentation), and JavaScript (behavior). Ask questions if requirements are unclear and explain your approach before coding.
Focus Topics
User Interface and User Experience Fundamentals
Basic understanding of UI/UX principles, creating intuitive and usable interfaces, visual hierarchy, color contrast and accessibility considerations, and designing forms that guide users effectively. Understanding why good UI/UX matters for applications.
Practice Interview
Study Questions
Frontend Framework Fundamentals (React, Vue, or Angular)
If applicable, understanding framework basics including component structure, component composition, props and state management, lifecycle methods or hooks, and how frameworks differ from vanilla JavaScript. Ability to build components that follow framework best practices.
Practice Interview
Study Questions
JavaScript Interactivity and DOM Manipulation
JavaScript fundamentals for frontend work including DOM selection and manipulation, event listeners and handlers, state management in vanilla JavaScript, and modern JavaScript syntax (ES6+ features like arrow functions, destructuring, template literals). Understanding the event loop basics and asynchronous operations with callbacks, promises, or async/await.
Practice Interview
Study Questions
CSS Styling, Layout, and Responsive Design
CSS fundamentals including selectors, specificity, cascading, box model, margins, padding, positioning, flexbox, CSS Grid, and media queries for responsive design. Ability to create effective layouts for different screen sizes and implement visual designs cleanly without bloated or repetitive code.
Practice Interview
Study Questions
HTML Structure and Semantic Elements
Understanding HTML fundamentals including proper document structure, semantic HTML5 elements (header, nav, main, article, section, footer), form elements, accessibility attributes (alt text, ARIA labels), and when to use semantic elements versus generic divs. Knowledge of what makes good, accessible HTML.
Practice Interview
Study Questions
Backend Technical Interview
What to Expect
60-90 minute technical interview focused on backend technologies, server-side logic, APIs, and database fundamentals. You'll complete a coding task such as building REST API endpoints, implementing business logic, querying a database, or solving a backend problem. Tasks are at entry-level complexity and might involve building simple CRUD endpoints, implementing validation and error handling, designing a basic database schema, or working with an existing codebase to add features. You'll code in a backend language (Node.js/JavaScript, Python, Java, etc.) and demonstrate understanding of API design, database basics, and server-side problem-solving.
Tips & Advice
Start by thoroughly understanding business requirements and clarifying any ambiguities. For API tasks, think about data models and design your database schema or data structure first - this helps organize your thinking. Design RESTful endpoints following conventions: GET for retrieval, POST for creation, PUT for updates, DELETE for deletion, with appropriate HTTP status codes. Write clean, organized backend code with proper error handling and validation. Show understanding of database operations and how to structure queries efficiently. For entry-level, a simple working solution is better than attempting complex optimization. Explain your approach before coding. Be prepared to discuss security considerations (input validation, error messages), authentication concepts, and scalability thinking even if simplified for the exercise. Ask clarifying questions about requirements, constraints, and assumptions. Demonstrate understanding of how backend code would integrate with frontend applications.
Focus Topics
Backend Framework and Ecosystem Fundamentals
Proficiency in a backend technology stack such as Node.js with Express, Python with Django or Flask, Java with Spring, or equivalent. Understanding of framework basics including routing, middleware, request handling, and project structure.
Practice Interview
Study Questions
Asynchronous Programming and External API Integration
Understanding asynchronous operations, promises, async/await syntax, and non-blocking I/O patterns. Ability to make external API calls, handle responses, and manage asynchronous tasks in backend code appropriately.
Practice Interview
Study Questions
RESTful API Design and HTTP Fundamentals
Understanding REST architectural principles including resource-based URLs, proper HTTP methods (GET for safe retrieval, POST for creation, PUT for updates, DELETE for deletion), appropriate status codes (200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error), and stateless communication patterns. Ability to design simple API endpoints following REST conventions.
Practice Interview
Study Questions
Database Fundamentals and Data Modeling
Understanding relational databases (SQL), basic schema design with tables and relationships, simple queries (SELECT, INSERT, UPDATE, DELETE), and fundamental normalization concepts. Familiarity with at least one database system (PostgreSQL, MySQL, or equivalent) and ability to structure data logically for application needs.
Practice Interview
Study Questions
Server-Side Logic and Business Logic Implementation
Writing backend code to implement business requirements, including data validation, transformations, conditional logic, and appropriate error handling. Understanding how to structure backend code with separation of concerns and maintainability in mind.
Practice Interview
Study Questions
Full Stack Integration Round
What to Expect
75-90 minute technical interview assessing your ability to build complete features combining frontend and backend. You'll receive a requirement to build a small full-stack feature such as a todo app with backend API, a form that submits data to a server with persistence, or a feature requiring UI + API + database interaction. You'll work in a shared coding environment or code locally and submit. The goal is to assess holistic thinking about systems, understanding of frontend-backend communication through APIs, end-to-end problem-solving, and ability to deliver working features that actually function from user click through to database storage.
Tips & Advice
Start by understanding complete requirements and sketching out a simple architecture (frontend components, backend endpoints, database schema) before coding. Prioritize getting a working end-to-end flow over perfect polish - a simple feature that fully works is better than a complex feature that's partially done. Build the backend API first or in parallel with frontend so you understand the data contract between layers. Design simple, clean data structures and validate input at both frontend (UX) and backend (security/reliability). Handle errors gracefully on both ends - show user-friendly messages on frontend and return appropriate HTTP status codes on backend. Think explicitly about how frontend and backend communicate - design APIs that match frontend needs and implement frontend code that properly uses those APIs. Show understanding of full-stack concepts like asynchronous API calls, data flow, state management across layers, and error handling across boundaries. Test the complete flow manually. Ask clarifying questions about requirements and explain your approach before diving into code.
Focus Topics
Debugging and Troubleshooting Across Layers
Ability to identify where issues occur in a full stack application (frontend, API, database, network communication), systematically debug using browser developer tools and logging, trace data flow to locate problems, and test interactions between components.
Practice Interview
Study Questions
System Architecture and Design Thinking
Ability to structure applications with appropriate separation of concerns, think about data flow through the system from UI through API to persistence, and make reasonable architectural decisions for entry-level applications. Basic awareness of design trade-offs between different approaches.
Practice Interview
Study Questions
Data Persistence and State Management Across Layers
Understanding how data persists through database interactions, how state moves between frontend and backend layers, ensuring data consistency across the application, and validating data appropriately at both frontend (for UX) and backend (for security and reliability).
Practice Interview
Study Questions
End-to-End Feature Development and Complete System Thinking
Taking a requirement and building a complete, working feature from user interface through API endpoints to database and back. Understanding user workflows, designing appropriate data models, creating UI to collect and display data, building APIs to process data, and querying databases appropriately to support the feature.
Practice Interview
Study Questions
Frontend-Backend Integration Through APIs
Understanding how frontend components interact with backend APIs using HTTP requests (fetch, axios, etc.), handling asynchronous responses and errors, managing data flow from API responses to UI updates. Ability to design APIs that frontend needs and implement corresponding client-side code to consume them properly.
Practice Interview
Study Questions
Behavioral and Culture Fit Interview
What to Expect
45-60 minute interview with a hiring manager, team member, or culture specialist focused on assessing cultural alignment, learning mindset, teamwork ability, communication skills, and how you handle challenges. This round uses behavioral questions to understand how you've approached learning in the past, overcome obstacles, collaborated with others, handled feedback, and navigated ambiguity. For entry-level candidates, the emphasis is on demonstrating coachability, intellectual curiosity, resilience, genuine interest in growing as an engineer, and ability to work effectively in a team.
Tips & Advice
Use the STAR method (Situation, Task, Action, Result) to structure responses to behavioral questions. Prepare 5-7 concrete stories from personal projects, school coursework, bootcamp experiences, or internships that demonstrate: overcoming a technical challenge, learning a new technology quickly, receiving feedback and improving, working effectively with others, dealing with failure or mistakes constructively, showing initiative or leadership in small ways, and why full stack development excites you. Be authentic and honest about your entry-level status - emphasize your learning mindset and show evidence of self-directed learning. Discuss challenges positively, focusing on what you learned rather than blame. Ask thoughtful questions that show you've thought about the role and company values. Show genuine curiosity about the work and team. Avoid memorized-sounding answers - have natural conversations instead.
Focus Topics
Genuine Interest in Full Stack Development and Company
Authentic enthusiasm for full stack development specifically (the combination of frontend and backend work) and why this interests you. Specific knowledge about the company's products, mission, or engineering challenges. Thoughtful questions about the role, team, and opportunities to grow. Demonstrating you've researched the company beyond just the job posting.
Practice Interview
Study Questions
Problem-Solving Approach and Resilience
How you approach challenging technical problems, examples of persisting through difficulties, strategies for when you're stuck, and viewing obstacles as learning opportunities rather than roadblocks. Evidence of breaking down complex problems into manageable steps and systematic troubleshooting.
Practice Interview
Study Questions
Receiving Feedback and Continuous Improvement
Specific examples of receiving feedback (from teachers, mentors, code reviews, or colleagues) and actively improving based on that feedback. Demonstrating maturity in handling criticism and openness to different perspectives. Growth from mistakes and learning from failures.
Practice Interview
Study Questions
Teamwork, Collaboration, and Communication
Ability to work effectively with others, ask for help when needed, give and receive feedback gracefully, and contribute to team success. Evidence of communication skills, willingness to help teammates, and understanding that software development is inherently collaborative. Examples of working through disagreements or different perspectives constructively.
Practice Interview
Study Questions
Growth Mindset and Learning Ability
Demonstrating genuine curiosity about technology and software development, willingness to learn new tools and languages, comfort with rapid learning and evolution. Evidence of self-directed learning (personal projects, online courses, technical reading) and ability to adapt when faced with unfamiliar technologies. Entry-level candidates should show enthusiasm for continuous improvement.
Practice Interview
Study Questions
Frequently Asked Full-Stack Developer Interview Questions
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?
Sample Answer
Direct answer
First diagnose why the meeting is stalling: usually it's because status-sharing and decision-making are mixed together, and no one is clearly accountable for closing a decision when people disagree. The fix separates the two (status moves async, meeting time is reserved for decisions), names a decision owner per topic, and tracks decisions in writing so they don't get relitigated the next week.
How to redesign it
Step 1: diagnose before redesigning. Ask whether people are status-updating instead of deciding, whether it's unclear whose call something is, or whether decisions do get made but aren't tracked so they resurface. Each cause has a different fix.
Step 2: separate status from decisions.
| Before | After |
|---|---|
| Round-robin status updates eat most of the meeting | Status posted async in a short template before the meeting |
| Decisions surface late, with little time left | Meeting time is reserved for items flagged as needing a live decision |
| Unclear who has the final call | Each agenda item has a named decision owner |
Step 3: track decisions so they don't restall. Keep a lightweight decision log: what was decided, who owns it, and the date. If an item can't close live, name a follow-up owner and a deadline instead of letting it silently carry over.
Step 4: reconsider the cadence. If most items now resolve async, a lower-frequency decision meeting paired with a written weekly status may serve the group better than a fixed weekly sync for everything.
Worked example
Situation: a cross-functional project with design, engineering, and data has a standing 60-minute weekly sync. Status updates take up 45 minutes, decisions surface in the last 15, and things 'decided' in the room get revisited the following week.
Action: introduced a pre-read posted 24 hours ahead covering status and any open decisions that need a live call; restructured the meeting to skip status entirely and spend the full time on flagged decisions, each with a named owner; started a shared decision log so a closed decision has a record to point back to.
Result: the meeting shortened from 60 to 30 minutes because status moved out of the room, and decisions stopped resurfacing because there was now a written record of what was actually agreed and by whom.
Trade-offs and pitfalls
- Cutting the meeting without giving people another outlet just moves the stalling into chat threads. Live time is still needed for genuine disagreement, don't eliminate it entirely.
- Naming a decision owner can feel like taking authority away from the group. Frame it as who is accountable if the call turns out wrong, not as a power grab.
- Async pre-reads fail without a light enforcement habit. If nobody protects the norm, it quietly reverts to status-in-the-room within a few weeks.
- Adding a decision log and a template is itself process. If it isn't paired with removing something (like the status round-robin), it just adds overhead on top of the original problem.
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?
Sample Answer
Direct answer. Type the hook as useValue<T>(initial: T | (() => T)): [T, Dispatch<SetStateAction<T>>], where SetStateAction<T> is T | ((prev: T) => T), and annotate the return type as a tuple (an array of fixed length where each position has its own type) so TypeScript does not widen it (infer the broader, less precise type) to a plain array of mixed elements. Dispatch<A> is React's type for a function that takes one argument of type A and returns nothing, which is the type of both a useState setter and a reducer's dispatch. The setter stays honest because T appears in every position: the value you pass, the argument the updater receives, and what it must return. A reducer is a function (state, action) => newState, and dispatch(action) is how a component asks React to run it. Exposing dispatch through context (React's way of making a value available to any component below a Provider, with each component that reads it called a consumer) works well, but it breaks in three ways: the context default is undefined unless you guard it, putting state and dispatch in one context value re-renders (calls again, to rebuild its output) every consumer on every state change, and the raw dispatch lets any component send any action.
A generic useState-like hook
A generic is a type parameter (T) filled in per call, so useValue(0) gives T = number and useValue<string | null>(null) gives T = string | null. An updater function is a function (prev) => next that React calls with the latest state, which is what makes two back-to-back updates compose instead of overwriting each other.
The hook is built on useReducer(reducer, undefined, init). The reducer turns each action (a value or an updater) into the next state; the second argument is an unused initial argument; and the third, init, is a function React calls once on the first render to produce the starting state, which gives lazy initialisation (the work runs only once) and a setter whose identity never changes. Three decisions keep the types honest:
- A tuple return type. Without the annotation,
return [value, set]is inferred as(T | Dispatch<...>)[], an array whose elements are either, so destructuredsetwould be uncallable. The[T, Dispatch<SetStateAction<T>>]annotation fixes position 0 to the value and position 1 to the setter. - One alias for both shapes.
SetStateAction<T>isT | ((prev: T) => T). A setter that accepts only that union rejectssetN("seven")and rejects an updater that returns the wrong type. - A runtime discriminator with a documented cast. Distinguishing "value" from "updater" at runtime means
typeof action === "function". TypeScript cannot prove that a function in aT | ((prev: T) => T)position is the updater (becauseTitself could be a function type), so the call needs a cast. The cast is safe only under React's own rule: a function argument is always treated as an updater, and a function-valued state must be stored by wrapping it (set(() => fn)). React documents exactly this foruseState: an initializer or updater is called, so to store a function you writeuseState(() => someFunction)andset(() => someOtherFunction).
A reducer with a discriminated union of actions
A discriminated union is a union whose members share a literal-typed property (here type) that identifies the member. Checking that property narrows the type (the compiler shrinks a broad type to the member that must apply in that branch): inside case "add": the compiler knows action.item exists. The default branch passes the leftover value to a function that takes never (the empty type). If every case is handled, the leftover is never and it compiles; if a new action is added and not handled, the leftover is that action and the compile fails. That is exhaustiveness checking.
Full runnable example
The demo section at the bottom of hook.tsx is test harness, not part of the hook. new JSDOM(...) creates a fake browser document so React can render in Node; Object.assign(globalThis, { window, document }) makes that document the global one that react-dom looks for; IS_REACT_ACT_ENVIRONMENT = true tells React it is running under tests, so it does not warn about updates made outside act; createRoot(...) mounts the React tree into the #root element; and await act(async () => { ... }) runs the code inside it and then waits until React has applied every resulting update and effect, so the next console.log reads the settled page. The counters (buttonRenders and the like) are incremented in the body of each component, so they count how many times React called it.
// hook.tsx
import {
createContext, useContext, useReducer, act,
type Dispatch, type ReactNode,
} from "react";
import { createRoot } from "react-dom/client";
import { JSDOM } from "jsdom";
// ---- 1. A generic useState-like hook -------------------------------------
type SetStateAction<T> = T | ((prev: T) => T);
function resolve<T>(action: SetStateAction<T>, prev: T): T {
return typeof action === "function" ? (action as (prev: T) => T)(prev) : action;
}
export function useValue<T>(initial: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
const [value, set] = useReducer(
(prev: T, action: SetStateAction<T>) => resolve(action, prev),
undefined,
() => (typeof initial === "function" ? (initial as () => T)() : initial),
);
return [value, set];
}
// ---- 2. A reducer with a discriminated union of actions -------------------
type CartItem = { id: number; name: string };
type CartAction =
| { type: "add"; item: CartItem }
| { type: "remove"; id: number }
| { type: "clear" };
function assertNever(x: never): never {
throw new Error(`Unhandled action: ${JSON.stringify(x)}`);
}
export function cartReducer(state: CartItem[], action: CartAction): CartItem[] {
switch (action.type) {
case "add": return [...state, action.item];
case "remove": return state.filter((i) => i.id !== action.id);
case "clear": return [];
default: return assertNever(action);
}
}
// ---- 3. Dispatch through context: two contexts, one hook each -------------
const CartStateContext = createContext<CartItem[] | undefined>(undefined);
const CartDispatchContext = createContext<Dispatch<CartAction> | undefined>(undefined);
export function CartProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(cartReducer, []);
return (
<CartDispatchContext.Provider value={dispatch}>
<CartStateContext.Provider value={state}>{children}</CartStateContext.Provider>
</CartDispatchContext.Provider>
);
}
// The single-context shape: one value object that carries both state and dispatch.
const CartCombinedContext = createContext<
{ state: CartItem[]; dispatch: Dispatch<CartAction> } | undefined
>(undefined);
export function CombinedProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(cartReducer, []);
return (
<CartCombinedContext.Provider value={{ state, dispatch }}>
{children}
</CartCombinedContext.Provider>
);
}
export function useCartDispatch(): Dispatch<CartAction> {
const d = useContext(CartDispatchContext);
if (d === undefined) throw new Error("useCartDispatch must be used inside <CartProvider>");
return d;
}
export function useCartState(): CartItem[] {
const s = useContext(CartStateContext);
if (s === undefined) throw new Error("useCartState must be used inside <CartProvider>");
return s;
}
// ---- Demo ------------------------------------------------------------------
const dom = new JSDOM("<div id=root></div>");
Object.assign(globalThis, { window: dom.window, document: dom.window.document });
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let buttonRenders = 0;
let combinedButtonRenders = 0;
let listRenders = 0;
let setCount!: Dispatch<SetStateAction<number>>;
function AddButton() {
buttonRenders++;
const dispatch = useCartDispatch();
return <button onClick={() => dispatch({ type: "add", item: { id: 1, name: "pen" } })}>add</button>;
}
function CombinedAddButton() {
combinedButtonRenders++;
const ctx = useContext(CartCombinedContext);
if (ctx === undefined) throw new Error("outside provider");
return <button onClick={() => ctx.dispatch({ type: "add", item: { id: 1, name: "pen" } })}>add</button>;
}
function List() {
listRenders++;
return <p>{useCartState().length} items</p>;
}
function FnHolder() {
// T is a function type here: pass an initializer that RETURNS the function.
const [fn, setFn] = useValue<() => string>(() => () => "first");
fnText = fn();
setFn_ = setFn;
return null;
}
let fnText = "";
let setFn_!: Dispatch<SetStateAction<() => string>>;
function Counter() {
const [n, set] = useValue(() => 10);
setCount = set;
return <span>{n}</span>;
}
const root = createRoot(dom.window.document.getElementById("root")!);
await act(async () => {
root.render(<><Counter /><FnHolder /><CartProvider><AddButton /><List /></CartProvider><CombinedProvider><CombinedAddButton /></CombinedProvider></>);
});
const read = () => dom.window.document.getElementById("root")!.textContent;
console.log("initial:", read());
await act(async () => { setCount(5); });
console.log("after set(5):", read());
await act(async () => { setCount((n) => n + 1); setCount((n) => n * 2); });
console.log("after two updaters:", read());
await act(async () => { setFn_(() => () => "second"); });
console.log("function-valued state:", fnText);
const buttons = dom.window.document.querySelectorAll("button");
await act(async () => {
buttons[0].dispatchEvent(new dom.window.MouseEvent("click", { bubbles: true }));
buttons[1].dispatchEvent(new dom.window.MouseEvent("click", { bubbles: true }));
});
console.log("after dispatch:", read());
console.log("split-context button renders:", buttonRenders, "| list renders:", listRenders);
console.log("combined-context button renders:", combinedButtonRenders);
await act(async () => { root.unmount(); });
Run with tsc --strict and then node out/hook.js, it compiles with no errors and prints:
initial: 10add0 itemsadd
after set(5): 5add0 itemsadd
after two updaters: 12add0 itemsadd
function-valued state: second
after dispatch: 12add1 itemsadd
split-context button renders: 1 | list renders: 2
combined-context button renders: 2
The two queued updaters (n + 1 then n * 2) turn 5 into 12, because each updater receives the result of the previous one.
The first line is page text (textContent) with no separators, so it is four components glued together in render order: 10 from Counter's <span>, add from AddButton, 0 items from List, and the final add from CombinedAddButton. FnHolder renders null, so it adds no text. After the dispatch the list reads 1 items and the counter still reads 12.
What the compiler says about misuse
The first line of each listing (// bad.tsx, // hook.tsx, // exhaust.tsx) is a label and not part of the file, so tsc numbers the first real line as line 1.
// bad.tsx
import { cartReducer, useValue } from "./hook.js";
const [n, setN] = useValue(0);
setN("seven");
setN((prev) => prev + "x");
export const bad = cartReducer([], { type: "remove", id: "3" });
function untupled<T>(v: T) {
return [v, (x: T) => {}];
}
const [v, set] = untupled(1);
set(2);
bad.tsx(4,6): error TS2345: Argument of type 'string' is not assignable to parameter of type 'SetStateAction<number>'.
bad.tsx(5,6): error TS2345: Argument of type '(prev: number) => string' is not assignable to parameter of type 'SetStateAction<number>'.
Type '(prev: number) => string' is not assignable to type '(prev: number) => number'.
Type 'string' is not assignable to type 'number'.
bad.tsx(7,54): error TS2322: Type 'string' is not assignable to type 'number'.
bad.tsx(13,1): error TS2349: This expression is not callable.
Not all constituents of type 'number | ((x: number) => void)' are callable.
Type 'number' has no call signatures.
The first two errors show the setter keeping T honest, the third shows the action union checking payload types, and the fourth is the un-annotated tuple problem from point 1.
Exhaustiveness check, in a separate file:
// exhaust.tsx
type A = { type: "add" } | { type: "remove" } | { type: "rename"; name: string };
function assertNever(x: never): never { throw new Error(String(x)); }
export function f(a: A): number {
switch (a.type) {
case "add": return 1;
case "remove": return 2;
default: return assertNever(a);
}
}
exhaust.tsx(7,33): error TS2345: Argument of type '{ type: "rename"; name: string; }' is not assignable to parameter of type 'never'.
The error lands on the assertNever(a) line and names the one unhandled member. In cartReducer the same thing happens: add { type: "rename" } to CartAction and the build fails until the reducer handles it.
What breaks when you expose dispatch through context
| Problem | Why it happens | Fix |
|---|---|---|
useContext returns Dispatch<CartAction> | undefined | createContext needs a default; there is no real dispatch outside a provider | Default to undefined and wrap in a hook (useCartDispatch) that throws a clear error, so callers get a non-undefined type |
| Every consumer re-renders on each state change | A context re-renders all its consumers when the provider's value changes by Object.is (the strict same-value comparison React uses: two different objects are never equal, even with identical contents); value={{ state, dispatch }} is a new object each render | Split into a state context and a dispatch context. React's dispatch identity is stable, so dispatch-only consumers are untouched |
| Components can dispatch any action | The context exposes the raw dispatch | Type the actions narrowly, or expose a small API (addItem, clear) built from dispatch |
In the run above, both buttons only call dispatch and hold no state of their own, and the demo clicks both. Each click changes the state held by that button's provider. Under the split contexts, the list (a state consumer) re-rendered (list renders: 2, mount plus one update) but the dispatch-only button did not (button renders: 1, the mount only). Under the combined context, the same kind of dispatch-only button re-rendered (combined-context button renders: 2, mount plus one) because the provider built a new { state, dispatch } object, so the button's context value changed even though the only part it reads, dispatch, did not.
Trade-offs and pitfalls
- Function-valued state has to be wrapped (
useValue<() => string>(() => () => "first")), the same asuseState. The demo'sFnHoldershows the stored function replaced byset(() => () => "second"). - Updaters must be pure (no side effects), because React may call them twice in Strict Mode (a development-only wrapper,
<React.StrictMode>, that deliberately double-invokes updaters and render functions to expose impure code). - Reuse React's own
Dispatch<SetStateAction<T>>in production; this hook exists to show the typing, sinceuseStatealready has the same signature.
Running the code
npm i react@18.3.1 react-dom@18.3.1 jsdom @types/react@18 @types/react-dom@18 @types/jsdom typescript@5
package.json: { "type": "module" }
tsconfig.json: { "compilerOptions": { "strict": true, "target": "ES2022", "module": "NodeNext",
"moduleResolution": "NodeNext", "jsx": "react-jsx", "outDir": "out", "skipLibCheck": true },
"include": ["*.tsx"] }
npx tsc -p . && node out/hook.js # keep bad.tsx and exhaust.tsx out of the folder: prints the output above
# add bad.tsx and exhaust.tsx back and run: npx tsc -p . --noEmit -> the errors above
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.
Sample Answer
Direct answer. REST models a system as a set of addressable resources you act on with a small, uniform set of HTTP verbs; RPC models a system as a set of named procedures you call directly (createOrder, cancelOrder), with the URL identifying the ACTION rather than a resource. Choose RPC when the operations you are exposing genuinely are not resource-shaped (a computation, a workflow trigger, a batch job kickoff) rather than forcing them into an artificial noun.
URL design. REST: POST /orders/{id}/cancel (a resource, acted on via a sub-action) or, more purely, a state change expressed as PATCH /orders/{id} with a status field. RPC: POST /cancelOrder with the order id in the body, where the URL itself names the verb.
HTTP verb usage. REST assigns meaning to the verb itself: GET always reads, DELETE always removes. RPC typically uses POST for nearly everything, since the "meaning" lives entirely in the URL's procedure name, not in which HTTP method was used; the HTTP verb becomes just a transport detail, not semantic information a client or an intermediary can reason about.
Statelessness. Both styles can be, and should be, stateless; this is not actually a distinguishing factor between them, statelessness is a property of how you design the API, independent of resource-vs-procedure framing.
Resource orientation. REST insists that everything be modeled as a resource, even things that are awkward as nouns (a "calculation" or a "search" is forced into being a resource you POST to create); RPC has no such constraint, an operation is simply named for what it does, which can be a more natural fit for a genuinely action-shaped API (a recommendation-generation service, an image-processing job).
Caching implications. Because REST's GET requests map directly onto HTTP caching semantics, a well-designed REST read endpoint gets CDN and browser caching essentially for free; an RPC-style API that funnels everything through POST (even reads) forfeits that entirely, since HTTP caching semantics are built around GET being safe and cacheable.
Client-server coupling. RPC tends to couple the client more tightly to the server's specific set of named operations (the client has to know the exact procedure name and its exact parameter shape); REST's uniform interface means a client that understands "resources + a few verbs" can reason about a NEW resource it has never seen before, without learning a new procedure name for it.
When to prefer each. Prefer REST for a public, resource-centric API (an e-commerce catalog, a user-management API) where caching and broad client tooling compatibility matter. Prefer RPC for an internal service exposing genuinely action-shaped operations (trigger a batch export, run a recommendation computation) where forcing the action into a resource-and-verb shape would be more awkward than useful, and where every caller is a service you control that can simply be told the procedure name and shape directly.
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.
Sample Answer
Direct answer
Mobile-first means the unqualified CSS describes the smallest layout and min-width media queries add to it as the viewport grows. Desktop-first means the unqualified CSS describes the wide layout and max-width media queries take things away as the viewport shrinks. Both end up at the same pixels; they differ in what you write, what you have to undo, and what a browser or device that ignores the queries ends up with. Default to mobile-first, and choose desktop-first when the product is genuinely desktop-led or when you are adapting an existing desktop-only stylesheet.
Terms: a media query is a condition on the environment (here, viewport width) that switches a block of CSS on or off, and the browser re-evaluates it as the window changes; specificity is the weight of a selector (inline style, then ids, then classes/attributes/pseudo-classes, then elements), and the cascade is the rule that decides which declaration wins: higher specificity first, then later source order when specificity is equal; critical CSS is the small set of rules needed to paint what the visitor sees first, usually inlined (written straight into a <style> element in the page's HTML instead of fetched as a separate file) so no extra request blocks rendering. A resource is render-blocking when the browser will not paint the page until it has downloaded and processed it; first render is the first moment pixels appear.
The two strategies side by side
Mobile-first (min-width) | Desktop-first (max-width) | |
|---|---|---|
| Base styles | narrow layout, simplest rules | wide layout, richest rules |
| Queries | add: @media (min-width: 48em) { ... } | remove: @media (max-width: 47.9375em) { ... } |
| What each query does | introduces new layout properties | undoes properties (reset grid-column, restore display) |
| Boundaries | one threshold per step | paired with the neighbouring query; an off-by-one gap or overlap is possible |
| Fallback if a query never applies | a usable narrow page | a desktop layout squeezed onto a phone |
| Natural for | audiences arriving on phones; touch-first products | desktop-led tools; retrofitting an old desktop site |
How the cascade and specificity treat the queries
A media query adds no specificity. Inside a matching query a rule is exactly as heavy as the same selector outside it, so the existing tie-breakers decide: higher specificity wins, and at equal specificity the later rule wins. That gives two rules for organizing breakpoints:
- Put the override after the base rule it modifies. If a
min-widthblock appears before the base rule it overrides, the base rule wins at every width, because it is later with equal specificity. The demo showswrong orderkeeping 8px padding at 768px. - Keep specificity equal or lower in the base, never higher. An override must be at least as specific as the rule it undoes. In the demo the base rule is
.layout .main. Specificity is written as three numbers, (ids, classes/attributes/pseudo-classes, element names), compared left to right, so one class plus one class is (0,2,0) and a single class is (0,1,0); the base rule is (0,2,0) and the override is.main(0,1,0), so the override loses and a phone still gets 24px of padding.
Desktop-first leans on rule 2 more, because its queries exist to undo base rules, and they often have to repeat selector parts to win. The same rule applies in mobile-first, where the base is the simplest set of rules and the queries mostly add properties rather than undo them.
min-width and max-width examples
For the same button, mobile-first writes .btn { padding: 8px; } followed by @media (min-width: 600px) { .btn { padding: 24px; } }. Desktop-first writes .btn { padding: 24px; } followed by @media (max-width: 599px) { .btn { padding: 8px; } }. Both give 8px at 375px and 24px at 768px, as the table below shows. The difference grows with the amount that has to be undone: the sample 12-column layout below needs 9 declarations written desktop-first and 7 mobile-first, because the desktop-first query has to restore grid-template-columns, gap and grid-column: auto before the narrow layout works.
import { chromium, firefox, webkit } from 'playwright';
// Variant A: base rule first, min-width override after it (mobile-first order).
const mobileFirst = `
.btn { padding: 8px; }
@media (min-width: 600px) { .btn { padding: 24px; } }`;
// Variant B: the same two rules in the opposite order.
const wrongOrder = `
@media (min-width: 600px) { .btn { padding: 24px; } }
.btn { padding: 8px; }`;
// Variant C: desktop-first: base is the wide design, max-width undoes it.
const desktopFirst = `
.btn { padding: 24px; }
@media (max-width: 599px) { .btn { padding: 8px; } }`;
// Variant D: the override is less specific than the rule it tries to undo.
const lowSpecificity = `
.layout .main { padding: 24px; }
@media (max-width: 599px) { .main { padding: 8px; } }`;
const padding = async (browser, css, width) => {
const page = await browser.newPage({ viewport: { width, height: 600 } });
await page.setContent(`<style>${css}</style><div class="layout"><button class="btn main">Go</button></div>`);
const p = await page.evaluate(() => getComputedStyle(document.querySelector('.btn')).paddingTop);
await page.close();
return p;
};
let failures = 0;
const expect = (ok, msg) => { if (!ok) { failures++; console.log(' FAIL', msg); } };
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const rows = {};
for (const [label, css] of [['mobile-first', mobileFirst], ['wrong order', wrongOrder], ['desktop-first', desktopFirst], ['weaker override', lowSpecificity]]) {
rows[label] = { 375: await padding(browser, css, 375), 768: await padding(browser, css, 768) };
}
expect(rows['mobile-first'][375] === '8px' && rows['mobile-first'][768] === '24px', `${name}: mobile-first`);
expect(rows['wrong order'][375] === '8px' && rows['wrong order'][768] === '8px', `${name}: wrong order lets the base rule win at 768`);
expect(rows['desktop-first'][375] === '8px' && rows['desktop-first'][768] === '24px', `${name}: desktop-first`);
expect(rows['weaker override'][375] === '24px', `${name}: a (0,1,0) override loses to a (0,2,0) rule inside the query`);
if (name === 'chromium') console.table(rows);
await browser.close();
}
console.log(failures === 0 ? 'ALL CHECKS PASSED' : `${failures} CHECK(S) FAILED`);
process.exit(failures ? 1 : 0);
┌─────────────────┬────────┬────────┐
│ (index) │ 375 │ 768 │
├─────────────────┼────────┼────────┤
│ mobile-first │ '8px' │ '24px' │
│ wrong order │ '8px' │ '8px' │
│ desktop-first │ '8px' │ '24px' │
│ weaker override │ '24px' │ '24px' │
└─────────────────┴────────┴────────┘
ALL CHECKS PASSED
// Counts the declarations each stylesheet needs for the same 12-column layout.
const desktopFirst = `
.layout { display: grid; grid-template-columns: repeat(12, 1fr); gap: 24px; }
.main { grid-column: 1 / 9; }
.side { grid-column: 9 / 13; }
.promo { grid-column: 1 / 13; }
@media (max-width: 767px) {
.layout { grid-template-columns: 1fr; gap: 16px; }
.main, .side, .promo { grid-column: auto; }
}`;
const mobileFirst = `
.layout { display: grid; gap: 16px; }
@media (min-width: 768px) {
.layout { grid-template-columns: repeat(12, 1fr); gap: 24px; }
.main { grid-column: 1 / 9; }
.side { grid-column: 9 / 13; }
.promo { grid-column: 1 / 13; }
}`;
const count = (css) => css.split(';').filter((d) => d.includes(':')).length;
console.log('desktop-first declarations:', count(desktopFirst));
console.log('mobile-first declarations:', count(mobileFirst));
desktop-first declarations: 9
mobile-first declarations: 7
The helper count splits the stylesheet text at every ; and keeps the pieces that contain a :. Each declaration (gap: 24px;) ends in a semicolon, so each piece holds exactly one declaration; any selector or @media text before it travels in the same piece (the piece @media (max-width: 767px) { .layout { grid-template-columns: 1fr still counts once), and the closing } leftovers have no colon and are dropped. That is why it gives the right answer here, and it would miscount a declaration without a trailing semicolon or a selector such as a:hover standing in a piece by itself. Tallying the sample by hand agrees: desktop-first has 3 + 1 + 1 + 1 = 6 base declarations plus 2 + 1 = 3 inside the query, 9 in all; mobile-first has 2 base and 2 + 3 = 5 inside the query, 7 in all. The 9 and 7 are counts of declarations in that sample, not a general ratio; they show the direction of the effect (undoing costs declarations) rather than its size on a real stylesheet.
When to choose each: practical cases
Mobile-first is the better call when:
- The audience arrives on phones and input is touch. A restaurant-ordering or booking product whose analytics show most sessions on phones should make the single-column, large-tap-target layout the base, and add side-by-side panels and hover-dependent menus only for widths and pointers that can use them.
- Features must degrade gracefully, and performance matters. A news or content site reached from search should render a readable page from the base CSS alone; wide-screen extras are optional layers, and if a query is not applied the visitor still gets a working page.
Desktop-first is the right call when:
- The product is a desktop tool. An internal analytics back office used on managed desktops, dense with wide tables and keyboard shortcuts, with phone support limited to read-only views: the base is the real product, and
max-widthqueries stack or hide the secondary panels. - You are retrofitting. An existing desktop-only stylesheet with thousands of rules cannot be inverted in one release; adding
max-widthqueries gets a usable small-screen layout shipped now, with a later migration to mobile-first one component at a time.
Bundle size and critical CSS
- Download size. web.dev states that "The browser downloads all CSS resources, regardless of blocking or non-blocking behavior", so one file with queries costs the same download either way. The size differences come only from the undo declarations shown above.
- Render blocking. web.dev: "By default, CSS is treated as a render-blocking resource", and media queries "allow us to mark some CSS resources as non-render blocking". A mobile-first split puts wide-screen rules in
<link rel="stylesheet" href="wide.css" media="(min-width: 48em)">; on a narrow screen that file does not match, so it does not block first render. On a wide screen it does match and blocks, so this helps the narrow device specifically. - Critical CSS. Tools that extract critical CSS need the viewport to evaluate. In a mobile-first file the base rules apply at every width, so they are the natural candidates to inline, and the
min-widthadditions follow in the stylesheet.
Trade-offs and pitfalls
- Breakpoint pairs.
max-width: 599pxplusmin-width: 600pxis fine at integer widths; mixing mismatched values leaves widths that match neither. - Do not mix directions in one stylesheet. A file with both
min-widthandmax-widthrules requires you to track which rules apply at which widths. - A query changes nothing about order. A responsive rule placed above its base rule silently does nothing.
- Edge cases: content-based breakpoints (where the design actually breaks) hold up better than device-based ones; and a fractional viewport width, such as 599.5px under browser zoom, matches neither
(max-width: 599px)nor(min-width: 600px), which is another reason to use one direction only.
Running the code
mkdir demo && cd demo # put check.mjs and count.mjs here
npm init -y && npm pkg set type=module
npm i playwright@1.48.2 && npx playwright install chromium firefox webkit
node check.mjs && node count.mjs
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.
Sample Answer
Direct answer
Treat the tablet as the first place the checklist is saved and the server as the second. When the technician taps Submit, the app writes the finished checklist to the browser's own database (IndexedDB) together with an id generated on the tablet, tells the technician "Saved on this tablet", and only then tries the network. A small background loop (the outbox) sends queued checklists with PUT /v1/inspections/{id}, retries failures with a growing, randomised pause, and deletes the local copy only after the server has confirmed. The server stores each id at most once, so a retry after a lost reply is harmless. The screen never says "Submitted" until the server has answered with a success.
The id is the key to the whole design. Because the tablet picks it before the first attempt, every retry of the same checklist carries the same id, and the database can recognise a repeat. Without it, a lost response ("did it save or not?") forces a choice between losing data and saving twice.
What the technician sees at each step
| Moment | What happens underneath | What the screen says |
|---|---|---|
| Fills the form in the basement | answers held in the form; optionally draft-saved to IndexedDB every few seconds | normal form, a small "Offline" badge |
| Taps Submit | record written to IndexedDB (state: queued), button disabled so one tap makes one record | "Saved on this tablet. It will be sent when there is a signal." |
Send attempt fails (no signal, timeout, 5xx) | attempt counter goes up, next try scheduled after a random pause | "Saved on this tablet. Will retry automatically." plus a count of waiting checklists |
Signal returns, PUT answered 201 or 200 | local record deleted | "Sent. The office has your checklist." with the time |
Server answers 401 (signed out while offline) | record stays queued, no timer; retried after the technician signs in | "Please sign in again. Your checklist is safe on this tablet." |
Server answers 409 or 422 | record kept, marked needs_attention, never retried automatically | "This checklist was rejected. Tap to review it." |
| App closed and reopened with items waiting | outbox loop starts again on page load | "1 checklist waiting to be sent." |
Two wording rules follow from this. "Saved" and "Sent" are different words for different facts, and a technician who leaves the building after seeing "Saved" must understand the office does not have it yet. And a waiting count must stay visible on the home screen, because the main failure in the field is a technician who believes everything was sent.
What the browser stores, and where
- IndexedDB holds the outbox. (An origin is the site's address: scheme, host and port. Browser storage belongs to one origin, so another site cannot read it.) It is an asynchronous browser database that stores structured data, including files and blobs, so a checklist with photo attachments fits. A Blob is a chunk of binary data such as a photo.
localStorageholds only strings and suits small settings, not a queue of records with photos. - A service worker (a script the browser runs separately from the page, able to answer requests from a cache) keeps the app's own files, so the app opens in the basement on a cold start (opened fresh, with the browser not already holding the page). The demo below blocks only the API calls; the service worker is what makes the page files available offline.
- Eviction means the browser deleting stored data to free space. By default, browser storage is best effort: the browser may delete an origin's data under storage pressure, and MDN notes Safari deletes script-created data for an origin with no user interaction in seven days of browser use when cross-site tracking prevention is on.
navigator.storage.persist()asks the browser to keep the data until the user clears it; the browser may or may not agree (Firefox asks the user; Safari and Chromium decide from the user's history with the site). So request persistence at startup, treat afalseresult as normal, and keep the sync window short: the sooner a checklist reaches the server, the less it depends on the tablet's storage. - Photos are Blobs in IndexedDB uploaded as separate requests with their own client-generated ids, and the checklist references them. The checklist is marked sent only after the server confirms it, and its photos are confirmed separately.
When and how it retries
Triggers: right after Submit, when the page loads, when the browser fires the online event, when the app returns to the foreground (the tab becomes visible again; the browser fires a visibilitychange event), and on a timer after a failure. Do not wait for online alone: navigator.onLine can be true on a network that reaches no internet (MDN: a LAN connection counts as online), and MDN calls the property inherently unreliable, so use it as a hint and let a real request failure be the truth. The Background Synchronization API (a service worker sync event that fires when connectivity returns) fits this problem, but MDN lists it as limited availability and not Baseline, so it is an enhancement on top of the triggers above rather than the mechanism.
What to retry: network errors, timeouts, 408, 429 and 5xx. What not to retry automatically: other 4xx. A 401 is the exception that waits for a person: flush() stops, keeps the record queued and asks for sign-in, then the next trigger sends it. A 422 means the content is invalid and sending it again changes nothing; a 409 means the id exists with different content. Those go to needs_attention for a human.
The pause grows with each failed attempt and is randomised ("exponential backoff with full jitter"): wait a random time between 0 and min(cap, base * 2^attempt). The randomisation matters at scale: if a depot of tablets regains signal together after a power cut, fixed delays make them all retry in the same instant. Worked numbers for the code below (base 2 s, cap 300 s; the wait after failed attempt n is a random value between 0 and min(300 s, 2 s * 2^n)):
| Failed attempt n | Upper limit of the random wait |
|---|---|
| 1 | 4 s |
| 2 | 8 s |
| 3 | 16 s |
| 4 | 32 s |
| 5 | 64 s |
| 6 | 128 s |
| 7 | 256 s |
| 8 and later | 300 s (512 s would exceed the cap) |
Each actual wait is drawn at random inside its range, so two tablets that failed together will retry at different moments. Retry-After is a response header telling the client when to try again, written either as a number of seconds (Retry-After: 120) or as an HTTP date (Retry-After: Wed, 21 Oct 2015 07:28:00 GMT); honour it when the server sends one, and take the later of it and the backoff wait. The code below keeps to the backoff alone for brevity.
How the server avoids saving it twice
PUT /v1/inspections/{id} (an alternative is POST plus an Idempotency-Key header, a client-chosen token the server uses to recognise repeats) with the client-generated UUID (universally unique identifier, a random 128-bit id) in the path. MDN describes PUT as idempotent (calling it once is no different from calling it several times), and says the server answers 201 Created when it creates the resource and 200 or 204 when the resource already existed and was modified. Here the server uses 201 for the first save and 200 for a replay of identical content, and the client treats both as success.
DROP TABLE IF EXISTS inspections;
CREATE TABLE inspections (
id uuid PRIMARY KEY, -- generated on the tablet, the idempotency key
technician_id integer NOT NULL,
site text NOT NULL,
answers jsonb NOT NULL,
payload_hash text NOT NULL, -- fingerprint of the body, to tell a replay from a clash
completed_at timestamptz NOT NULL, -- when the technician finished (tablet clock)
received_at timestamptz NOT NULL DEFAULT now()
);
The primary key on id is what makes a duplicate impossible, even when two requests for the same id arrive at the same moment (a retry while the first attempt is still in flight). The insert uses ON CONFLICT (id) DO NOTHING (if a row with that primary key already exists, skip the insert instead of raising an error). The answers column is jsonb, PostgreSQL's binary JSON type. When the insert stores nothing, the server compares the stored payload_hash (a fingerprint of the body) and the technician id with the new request: same content from the same technician is a replay (200), anything else is a clash (409 Conflict, which MDN defines as a conflict with the current state of the target resource).
The code
How to read the browser code: IndexedDB works through events. tx() in outbox.js opens the database, starts a transaction (a group of reads and writes that complete together) on the outbox object store (IndexedDB's name for a table), runs the function passed in, and wraps the callbacks in a promise: oncomplete means the transaction has committed so the promise resolves, onerror rejects it. By default the browser may report a commit before it has verified the bytes on the storage medium (a power cut can still lose the last write); passing { durability: 'strict' } to db.transaction asks it to wait for persistent storage first, which is worth the small cost for a record the technician believes is saved (the code below leaves the default durability for brevity). Every outbox read and write goes through it, and save() awaits it before any network call, which is why a submitted checklist survives the page or app being closed or crashing. In the server, faults.loseResponses is a fault injector for the demo: when above zero the server saves the checklist and then cuts the connection without replying, which reproduces a lost response on demand.
The outbox (browser side), the page that uses it, the server, and the driver that exercises all of it in a real Chromium:
// outbox.js
const cfg = () => window.OUTBOX_RETRY || { base: 2000, cap: 300000 }; // ms
const open = () => new Promise((ok, no) => {
const r = indexedDB.open('inspections', 1);
r.onupgradeneeded = () => r.result.createObjectStore('outbox', { keyPath: 'id' });
r.onsuccess = () => ok(r.result); r.onerror = () => no(r.error);
});
const tx = async (mode, fn) => {
const db = await open();
return new Promise((ok, no) => {
const t = db.transaction('outbox', mode); const out = fn(t.objectStore('outbox'));
t.oncomplete = () => { db.close(); ok(out.result); }; t.onerror = () => no(t.error);
});
};
export const requestPersistence = async () => (navigator.storage?.persist ? navigator.storage.persist() : false);
export const pending = () => tx('readonly', (s) => s.count());
export async function save({ site, answers }) {
const item = { id: crypto.randomUUID(), site, answers, completed_at: new Date().toISOString(), attempts: 0, state: 'queued' };
await tx('readwrite', (s) => s.put(item)); // durable on the tablet BEFORE any network call
return item.id;
}
let flushing = false, timer = null;
const say = (t) => window.dispatchEvent(new CustomEvent('outbox-state', { detail: t }));
export async function flush() {
if (flushing) return; flushing = true; clearTimeout(timer);
try {
const items = await tx('readonly', (s) => s.getAll());
for (const item of items.filter((i) => i.state === 'queued')) {
say('Sending...');
let res;
try {
res = await fetch(`/v1/inspections/${item.id}`, {
method: 'PUT', headers: { 'content-type': 'application/json', 'x-demo-user': '7' },
body: JSON.stringify({ site: item.site, answers: item.answers, completed_at: item.completed_at }),
signal: AbortSignal.timeout(15000) });
} catch { res = null; } // no signal, timeout, or lost response
if (res && (res.status === 200 || res.status === 201)) {
await tx('readwrite', (s) => s.delete(item.id)); // delete locally only after the server confirmed
say('Sent. The office has your checklist.');
} else if (res && res.status === 401) { // signed out while offline: keep the record, ask for sign-in, no timer
say('Please sign in again. Your checklist is safe on this tablet.');
break;
} else if (res && res.status >= 400 && res.status < 500 && res.status !== 429 && res.status !== 408) {
await tx('readwrite', (s) => s.put({ ...item, state: 'needs_attention', status: res.status }));
say('This checklist was rejected. Tap to review it.');
} else { // retryable: network error, 5xx, 429, 408
const n = item.attempts + 1;
await tx('readwrite', (s) => s.put({ ...item, attempts: n }));
const { base, cap } = cfg();
const wait = Math.random() * Math.min(cap, base * 2 ** n); // exponential backoff with full jitter
say('Saved on this tablet. Will retry automatically.');
timer = setTimeout(flush, wait);
break;
}
}
} finally { flushing = false; }
}
<!-- index.html -->
<!doctype html>
<meta charset="utf-8">
<title>Inspection</title>
<form id="f">
<label>Site <input id="site" required></label>
<label><input type="checkbox" id="q1"> Fire exit clear</label>
<label><input type="checkbox" id="q2"> Extinguisher in date</label>
<button id="submit">Submit checklist</button>
</form>
<p id="status" role="status" aria-live="polite"></p>
<script type="module">
import { save, flush, pending, requestPersistence } from '/outbox.js';
const status = document.getElementById('status');
const show = (t) => { status.textContent = t; };
window.addEventListener('outbox-state', (e) => show(e.detail));
await requestPersistence();
document.getElementById('f').addEventListener('submit', async (ev) => {
ev.preventDefault();
document.getElementById('submit').disabled = true; // one tap makes one record
await save({ site: site.value, answers: { q1: q1.checked, q2: q2.checked } });
show('Saved on this tablet. It will be sent when there is a signal.');
flush();
});
if ((await pending()) > 0) { show('1 checklist waiting to be sent.'); flush(); }
window.addEventListener('online', flush);
document.addEventListener('visibilitychange', () => { if (!document.hidden) flush(); });
</script>
// server.mjs
import http from 'node:http';
import crypto from 'node:crypto';
import fs from 'node:fs';
export function makeServer(pool, faults = { loseResponses: 0 }) {
const seen = new Map(); // id -> number of requests received
const srv = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://x');
if (req.method === 'GET' && url.pathname === '/') { res.setHeader('content-type', 'text/html'); return res.end(fs.readFileSync('index.html')); }
if (req.method === 'GET' && url.pathname === '/outbox.js') { res.setHeader('content-type', 'text/javascript'); return res.end(fs.readFileSync('outbox.js')); }
const m = url.pathname.match(/^\/v1\/inspections\/([0-9a-f-]{36})$/);
if (!m || req.method !== 'PUT') { res.statusCode = 404; return res.end(); }
const tech = Number(req.headers['x-demo-user']);
if (!tech) { res.statusCode = 401; return res.end(); }
let raw = ''; for await (const c of req) raw += c;
let b; try { b = JSON.parse(raw); } catch { res.statusCode = 400; return res.end(); }
if (typeof b.site !== 'string' || !b.site || typeof b.answers !== 'object' || isNaN(Date.parse(b.completed_at))) {
res.statusCode = 422; return res.end(JSON.stringify({ error: 'invalid_checklist' }));
}
seen.set(m[1], (seen.get(m[1]) || 0) + 1);
const hash = crypto.createHash('sha256').update(JSON.stringify([b.site, b.answers, b.completed_at])).digest('hex');
const ins = await pool.query(
`INSERT INTO inspections (id, technician_id, site, answers, payload_hash, completed_at)
VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (id) DO NOTHING RETURNING id`,
[m[1], tech, b.site, b.answers, hash, b.completed_at]);
let status = 201;
if (ins.rowCount === 0) { // this id was saved before: replay or clash?
const { rows: [old] } = await pool.query('SELECT payload_hash, technician_id FROM inspections WHERE id=$1', [m[1]]);
status = old.payload_hash === hash && old.technician_id === tech ? 200 : 409;
}
if (faults.loseResponses > 0) { faults.loseResponses--; return req.socket.destroy(); } // saved, but the answer never arrives
res.statusCode = status; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ id: m[1] }));
});
srv.seen = seen; return srv;
}
// run.mjs
import pg from 'pg';
import fs from 'node:fs';
import { chromium } from 'playwright';
import { makeServer } from './server.mjs';
const pool = new pg.Pool({ host: 'demo-pg', user: 'postgres', password: 'pw', database: 'postgres' });
await pool.query(fs.readFileSync('schema.sql', 'utf8'));
const faults = { loseResponses: 1 };
const srv = makeServer(pool, faults).listen(3200);
const count = async () => (await pool.query('SELECT count(*)::int n FROM inspections')).rows[0].n;
const idb = (page) => page.evaluate(() => new Promise((ok) => {
const r = indexedDB.open('inspections', 1);
r.onsuccess = () => { const q = r.result.transaction('outbox').objectStore('outbox').getAll(); q.onsuccess = () => ok(q.result.map((i) => i.state + ':' + i.attempts)); };
}));
const text = (page) => page.locator('#status').innerText();
const browser = await chromium.launch();
const ctx = await browser.newContext();
await ctx.addInitScript(() => { window.OUTBOX_RETRY = { base: 40, cap: 200 }; });
const page = await ctx.newPage();
await page.goto('http://127.0.0.1:3200/');
// 1. Technician is in the basement: no signal
await page.route('**/v1/**', (r) => r.abort('internetdisconnected'));
await page.fill('#site', 'Plant room B2'); await page.check('#q1');
await page.click('#submit');
const shown = await (await page.waitForFunction(() => {
const t = document.getElementById('status').innerText;
return t.includes('retry automatically') ? t : false;
})).jsonValue();
console.log('1 offline submit | screen:', shown, '| server rows:', await count(), '| tablet outbox:', (await idb(page)).length);
// 2. Page is reloaded (or the app killed) while still offline: the checklist survives
await page.reload();
await page.waitForFunction(() => document.getElementById('status').innerText.length > 0);
console.log('2 reload offline | tablet outbox kept:', (await idb(page)).length === 1, '| server rows:', await count());
// 3. Signal returns, but the first success response is lost after the server saved it
await page.unroute('**/v1/**');
await page.waitForFunction(() => document.getElementById('status').innerText.startsWith('Sent'));
const id = [...srv.seen.keys()][0];
console.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);
// 4. Same id, different content is a clash, not a replay
const clash = 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: 'Other site', answers: {}, completed_at: new Date().toISOString() }) });
const 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: '' }) });
console.log('4 same id, other body ->', clash.status, '| empty site ->', bad.status, '| server rows:', await count());
await browser.close(); srv.close(); await pool.end();
Run in the mcr.microsoft.com/playwright:v1.48.2-jammy container against postgres:16, it prints:
1 offline submit | screen: Saved on this tablet. Will retry automatically. | server rows: 0 | tablet outbox: 1
2 reload offline | tablet outbox kept: true | server rows: 0
3 signal back | screen: Sent. The office has your checklist. | server rows: 1 | server received the same id more than once: true | tablet outbox: 0
4 same id, other body -> 409 | empty site -> 422 | server rows: 1
Reading 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.
The 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):
P="psql -U postgres -qAt"
$P -c "TRUNCATE inspections"
INS="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'"
TS="SELECT extract(epoch FROM clock_timestamp())"
printf "BEGIN;\n$INS;\nSELECT pg_sleep(1.5);\n$TS;\nCOMMIT;\n" | $P > a.out &
sleep 0.5
$P -c "$INS; $TS" > b.out
wait
echo "session A rows inserted: $(grep -c inserted a.out)"
echo "session B rows inserted: $(grep -c inserted b.out)"
echo "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)"
$P -c "SELECT 'rows in table: ' || count(*) FROM inspections"
session A rows inserted: 1
session B rows inserted: 0
session B returned after A reached its commit: true
rows in table: 1
How 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.
Design choices and what would change them
- Client-generated id plus
PUT, versus anIdempotency-Keyheader onPOST. 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 stayPOST /inspectionsfor other clients, keep a separate keys table with an expiry and store the first response to replay it. - Tablet clock.
completed_atcomes from the tablet and can be wrong;received_atis the server's. Show the technician the tablet time, sort and audit by the server time, and do not usecompleted_atfor anything where being wrong has consequences. - Large queues. Send oldest first and one at a time, so a slow connection finishes whole checklists rather than starting many.
- Authentication expiring while offline. The
401branch inflush()keeps the recordqueuedand prompts for sign-in; the run above does not trigger it. The demo's header user id stands in for a session.
Running the code
cd work # holds outbox.js index.html server.mjs run.mjs schema.sql race.sh
echo '{"type":"module","dependencies":{"pg":"8.13.1","playwright":"1.48.2"}}' > package.json
docker network create demo-net
docker run -d --rm --name demo-pg --network demo-net -e POSTGRES_PASSWORD=pw postgres:16
until docker exec demo-pg pg_isready -h 127.0.0.1 -q; do sleep 1; done
docker 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'
docker cp race.sh demo-pg:/race.sh && docker exec -w /tmp demo-pg bash /race.sh
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?
Sample Answer
Direct answer
Default 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.
The forces in tension
| Force | Favours thin controllers | Favours fatter controllers |
|---|---|---|
| Reuse | Logic needed by HTTP, queue consumers, batch jobs, CLI | Exactly one entry point, now and foreseeably |
| Testability | Rules testable without an HTTP request or web framework | Little logic to test; framework integration tests suffice |
| Readability | Each class has one reason to change | Whole flow readable in one place, no jumping across files |
| Speed of delivery | Small upfront cost per feature | Fastest for prototypes and admin screens |
| Consistency with codebase | Existing code is layered | Existing framework convention puts logic elsewhere (for example Rails, a popular web framework, keeps logic in models) |
When thin is clearly preferable
- Two 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.
- Non-trivial rules. Pricing, eligibility, state transitions, money movement.
- Transactions spanning several writes. The unit of work belongs in one testable place, not spread across request-handling code.
- Long-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.
When a fatter controller is acceptable
Technical constraints
- The endpoint is CRUD over one table with validation only; a service method would just forward the call.
- A 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.
- The 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.
Organizational constraints
- A prototype or experiment with an agreed deletion or rewrite date.
- A 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.
- Internal admin tools whose failure is cheap and whose users are a handful of staff.
In every case, write down the trigger that ends the exception: "the first time this logic is needed outside this controller, extract it."
Worked example: the second entry point
An 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.
- Option 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.
- Option B, extract a
PlaceOrderuse 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.
The 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.
Pitfalls on both sides
- Over-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.
- Business 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.
- Fat service, not thin controller. Moving 120 lines into one
OrderServicewith 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. - HTTP 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.
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.
Sample Answer
Direct answer
Slide 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.
Structured elaboration, narrated step by step
- State the assumption up front.
kmust satisfy1 <= k <= n; ifk > 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). - Seed the window. Compute the sum of the first
kelements directly; this is the sum for the window starting at index 0. - 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 ofkelements for every window, which is what makes the whole scanO(n)instead ofO(n*k). - Track the best. Compare each window's sum (not yet divided) against the running best sum.
- Divide once, at the end. Return
best_sum / kafter 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 constantknever changes which sum is largest. - 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.
Worked example
def max_average_subarray(nums, k):
n = len(nums)
if k <= 0:
raise ValueError("max_average_subarray: k must be positive")
if k > n:
raise ValueError(f"max_average_subarray: k={k} exceeds array length n={n}")
window_sum = sum(nums[:k])
best_sum = window_sum
for i in range(k, n):
window_sum += nums[i] - nums[i - k]
if window_sum > best_sum:
best_sum = window_sum
return best_sum / k
def max_average_subarray_brute_force(nums, k):
n = len(nums)
best = sum(nums[:k]) / k
for i in range(1, n - k + 1):
avg = sum(nums[i:i + k]) / k
if avg > best:
best = avg
return best
cases = [
([1.0, 12.0, -5.0, -6.0, 50.0, 3.0], 4),
([-1.0, -2.0, -3.0, -4.0], 2),
([5.0], 1),
]
for nums, k in cases:
result = max_average_subarray(nums, k)
brute = max_average_subarray_brute_force(nums, k)
print(f"nums={nums}, k={k} -> max_average={result}")
assert abs(result - brute) < 1e-9
try:
max_average_subarray([1.0, 2.0, 3.0], 5)
except ValueError as e:
print(f"k > n raised ValueError as expected: {e}")
print("brute-force cross-check passed for all cases")
Output (executed, python3 s70_max_avg_subarray.py, cross-checked against a brute-force O(n*k) implementation for every case):
nums=[1.0, 12.0, -5.0, -6.0, 50.0, 3.0], k=4 -> max_average=12.75
nums=[-1.0, -2.0, -3.0, -4.0], k=2 -> max_average=-1.5
nums=[5.0], k=1 -> max_average=5.0
k > n raised ValueError as expected: max_average_subarray: k=5 exceeds array length n=3
brute-force cross-check passed for all cases
The 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.
Trade-offs & pitfalls
- All-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 withbest_sum = 0would silently and wrongly prefer an empty or zero-sum comparison over the true (negative) best. - Dividing 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.
- At 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 tofloat64only at the final division, exactly mirroring the "divide once, at the end" principle above; it would also express thek > ncheck as an explicit returnederrorvalue rather than a raised exception, matching Go's idiomatic error-handling convention instead of Python's. - A 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:
import numpy as np
def max_average_subarray_numpy(nums, k):
arr = np.asarray(nums, dtype=float)
n = arr.shape[0]
if k <= 0 or k > n:
raise ValueError(f"max_average_subarray_numpy: invalid k={k} for n={n}")
csum = np.cumsum(arr)
window_sums = np.empty(n - k + 1)
window_sums[0] = csum[k - 1]
window_sums[1:] = csum[k:] - csum[:-k]
return float(window_sums.max() / k)
cases = [
([1.0, 12.0, -5.0, -6.0, 50.0, 3.0], 4),
([-1.0, -2.0, -3.0, -4.0], 2),
([5.0], 1),
]
for nums, k in cases:
loop_result = max_average_subarray(nums, k)
numpy_result = max_average_subarray_numpy(nums, k)
print(f"nums={nums}, k={k} -> loop={loop_result}, numpy={numpy_result}, match={abs(loop_result - numpy_result) < 1e-9}")
assert abs(loop_result - numpy_result) < 1e-9
print("numpy variant agrees with the loop-based version to within 1e-9 for all three cases")
Output (executed, continuing in the same session as the loop-based version above):
nums=[1.0, 12.0, -5.0, -6.0, 50.0, 3.0], k=4 -> loop=12.75, numpy=12.75, match=True
nums=[-1.0, -2.0, -3.0, -4.0], k=2 -> loop=-1.5, numpy=-1.5, match=True
nums=[5.0], k=1 -> loop=5.0, numpy=5.0, match=True
numpy variant agrees with the loop-based version to within 1e-9 for all three cases
The 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.
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.
Sample Answer
Direct answer
For 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.
Structured elaboration
- Shared schema with tenant_id: every table carries a
tenant_idcolumn, 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 needstenant_idas 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. - Separate 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.
- Separate 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.
Worked example
A 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.
Trade-offs and pitfalls
- Indexing and partitioning: every shared-schema table needs
tenant_idas 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. - Backups: 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.
- Cost: 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.
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?
Sample Answer
Direct answer
With 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.
Structured elaboration
- Capture 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.
- Isolate 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.
- Deliberately 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.
- Try 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.
- Build 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.
- Run 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.
- Convince 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.
Worked example
I 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.
Trade-offs and pitfalls
The 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.
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?
Sample Answer
The idea in plain words
A call to a third-party API can stall in three different places, and each needs its own clock:
- Connect 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.
- Response (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).
- Overall 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.
The 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.
Method, in the order I would do it
- 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.
- 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.
- Set the connect timeout short. Opening a connection to a healthy host takes tens of milliseconds, so waiting long adds nothing. Assume 200 ms.
- 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.
- Decide the action for each timeout before writing code (table below).
| Timeout fires | What we know | Action |
|---|---|---|
| Connect | 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) |
| Response (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 |
| Response (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 |
| Overall 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 |
The 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.
Worked example: two traces on a 1,500 ms budget
Settings (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.
Trace A, slow connect, then success (a GET).
Attempt 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.
Trace B, stalled vendor (a GET).
| Step | Event | Clock | Remaining of 1,500 |
|---|---|---|---|
| 1 | Connect succeeds in 40 ms | 40 ms | 1,460 |
| 2 | Read timeout fires after 600 ms | 640 ms | 860 |
| 3 | Wait 50 ms | 690 ms | 810 |
| 4 | Second connect takes 40 ms | 730 ms | 770 |
| 5 | Attempt timeout = min(600, 770) = 600 ms; vendor stalls again, fires | 1,330 ms | 170 |
| 6 | 170 ms is below the 200 ms floor, so no third attempt: return the cached or degraded answer | 1,330 ms | 170 |
The 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.
Why the numbers also protect your own capacity
By 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.
Judgment calls and what would change them
- Long-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.
- Streaming responses need a read timeout on the gap between chunks plus an overall deadline, because a slow trickle can keep the connection technically alive.
- Retries 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.
- Different calls, different budgets: a payment confirmation may justify a longer deadline than a "suggested contacts" widget that can simply be omitted.
Common mistakes
- Using the library default (often no timeout, or tens of seconds) on a user-facing path.
- Setting only a read timeout and no overall deadline, so retries multiply the wait.
- Retrying a timed-out POST with no idempotency key, which can charge a customer twice.
- Choosing the read timeout from the median instead of the tail.
- Forgetting to cancel the in-flight request when the deadline fires, so the worker is still held.
Recommended Additional Resources
- LeetCode.com - Practice coding problems starting with Easy and Medium difficulty for entry-level preparation
- Cracking the Coding Interview by Gayle Laakmann McDowell - Comprehensive guide to technical interview preparation including sample questions and strategies
- JavaScript.info - Free, comprehensive JavaScript tutorial from basics through advanced concepts
- MDN Web Docs (developer.mozilla.org) - Authoritative reference documentation for HTML, CSS, JavaScript, and Web APIs maintained by Mozilla
- Full Stack Open (fullstackopen.com) - Free comprehensive course covering modern full-stack web development with React, Node.js, and databases
- React Official Documentation (react.dev) - Official React learning resources and API documentation with interactive examples
- Node.js Official Documentation - Comprehensive Node.js API documentation and guides for backend development
- Python Documentation and Real Python tutorials - For Python backend development learners
- SQL Tutorial resources (Mode Analytics, W3Schools, or PostgreSQL documentation) - Essential database fundamentals and query writing
- Eloquent JavaScript by Marijn Haverbeke (free online) - Deep dive into JavaScript concepts with interactive examples
- CSS-Tricks and web.dev - Resources for CSS, layout techniques, and web development best practices
- YouTube channels: Traversy Media, The Net Ninja, Kevin Powell (CSS specialist) - High-quality video tutorials for hands-on learning
- GitHub - Build personal projects and contribute to open source to demonstrate real-world application of skills
- FAANG company engineering blogs (Google Engineering Blog, Meta Engineering, AWS Architecture Blog) - Learn about technologies and problems these companies solve
- HackerRank, CodeSignal, or CodeWars - Alternative platforms for coding practice with interview-style problems and discussion forums
- System Design Primer GitHub repository - While entry-level typically doesn't require deep system design, understanding architecture thinking is valuable for full stack developers
- Behavioral interview preparation - Prepare STAR stories covering: technical challenge overcome, learning new technology quickly, receiving feedback and improving, working in a team, dealing with failure, and what excites you about full stack development
Search Results
Top 24 Full Stack Developer Interview Questions & Answers
Basic Full Stack Developer Interview Questions · 1. Mention all the ways by which we can include the CSS code in an HTML code. · 2. Explain in brief what is meant ...
Google Software Engineer Early Career Interview Questions [2024]
How would you design Google's database for web indexing? What approach would you take when designing a task scheduling system? How would you design Google Home ...
Top 10 Angular Developer Interview Questions - Full Scale
1. What is Angular, and why do you use it? What are the biggest pros and cons of using Angular? 2. How long have you been coding Angular as the primary language ...
50+ DevSecOps Interview Questions and Answers for 2025
How do you handle automated incident response? How do you automate compliance checks? How do you handle secrets management? How do you handle security debt ...
Top 70 Coding Interview Questions and Answers for 2026
1. What is a Data Structure? · 2. What is an Array? · 3. What is a Graph? · 4. What is a Tree? · 5. What is a Linked List? · 6. What are LIFO and FIFO? · 7. What is a ...
Meta Software Engineer Interview (questions, process, prep)
Ace the Meta software engineer interviews with this preparation guide. See updates to the interview process, example coding interview questions and ...
HTML Interview Questions and Answers - GeeksforGeeks
1. What are HTML tags? · 2. What's the difference between HTML and HTML5? · 3. What's the basic structure of an HTML document? · 4. What's the difference between a ...
This interview preparation guide was generated using AI-powered research from the sources listed above. While we strive for accuracy, we recommend verifying critical information from official company sources.
Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Full-Stack Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs