Spotify Staff-Level Full-Stack Engineer Interview Preparation Guide
Spotify's interview process for Staff-level Full-Stack Engineers comprises multiple rounds focused on technical depth, system design, architectural thinking, cross-functional collaboration, and cultural fit. The process evaluates your ability to own complex, production-grade systems, mentor engineers, and drive technical direction across teams. Expect behavioral discussions around past projects, technical coding assessments, system design deep-dives, and culture alignment conversations.
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with a Spotify recruiter to discuss your background, interest in the Staff-level role, career trajectory, and overall fit. This round may be split into an initial screen and a follow-up conversation after initial technical evaluation. The recruiter will verify your location flexibility (North Americas region for this role), confirm timezone alignment (Eastern Standard Time), and discuss compensation expectations and equity.
Tips & Advice
Be clear about your Staff-level experience (12+ years) and highlight projects where you owned complete systems or drove architectural decisions. Discuss your interest in Spotify's podcast platform, creator ecosystem, or user platform initiatives. Ask thoughtful questions about team structure, mentorship opportunities, and how Staff engineers influence technical direction. Mention your interest in platform reliability and automation. Be prepared to discuss relocation flexibility and timezone compatibility.
Focus Topics
Location and Timezone Flexibility
Confirm your location within North Americas region and alignment with Eastern Standard Time zone for team collaboration.
Practice Interview
Study Questions
Interest in Spotify's Platform Mission
Demonstrate knowledge of Spotify's podcast platform, creator ecosystem, or user platform work. Reference specific initiatives mentioned in job descriptions.
Practice Interview
Study Questions
Career Progression to Staff Level
Articulate your journey to Staff-level engineering, key milestones, and growth in ownership, mentorship, and technical influence.
Practice Interview
Study Questions
Full-Stack System Ownership
Highlight past experience owning complete web applications or platform tooling from frontend to database, similar to responsibilities in the role.
Practice Interview
Study Questions
Technical Coding Round - Phone Screen
What to Expect
Remote technical interview where you solve a medium-to-hard coding problem in 60 minutes using an online shared IDE. You'll be evaluated on problem-solving approach, code quality, testing mindset, and communication. For Staff level, expect problems involving complex data structures, optimization, or distributed systems concepts. The interviewer will ask follow-up questions about edge cases, scalability, and how your solution would perform in production.
Tips & Advice
Practice problems involving optimization, concurrency, or systems thinking. Write clean, production-ready code with proper error handling and comments. Think aloud and explain your approach before coding. At Staff level, interviewers expect you to consider edge cases, optimize for time/space complexity, and discuss testing strategies. Be prepared to refactor or optimize your solution if prompted. Reference your experience building robust production systems. Use either JavaScript/TypeScript or Java depending on your strength; Spotify values both.
Focus Topics
Concurrency and Distributed Systems Concepts
Understanding of locking, thread safety, eventual consistency, and scalability trade-offs in distributed environments.
Practice Interview
Study Questions
Code Quality and Testability
Writing clean, readable code with proper error handling, unit testing considerations, and design patterns suitable for production systems.
Practice Interview
Study Questions
JavaScript/TypeScript or Java Proficiency
Deep fluency with your chosen language, including modern features, async patterns, and practical coding idioms.
Practice Interview
Study Questions
Advanced Data Structures and Algorithms
Trees, graphs, heaps, hash maps, and dynamic programming problems requiring optimization and efficient solutions.
Practice Interview
Study Questions
System Design Round - Phone Screen
What to Expect
60-minute technical interview focused on your ability to design large-scale systems. You'll be asked to design a system similar to components of Spotify's platform (e.g., podcast distribution platform, support tooling, creator onboarding system, or authorization platform). You should propose architecture, discuss trade-offs, address scalability and reliability concerns, and explain how you'd handle failure modes. Expect deep-dive questions on specific components and your rationale for design decisions.
Tips & Advice
Study distributed systems design patterns, databases (SQL and NoSQL), caching strategies, message queues, and microservices architecture. For Spotify context, think about how you'd design systems supporting millions of creators, billions of fans, and real-time operations. Discuss observability, monitoring, and alerting from the start. Be prepared to explain trade-offs (consistency vs. availability, latency vs. throughput). Draw diagrams and ask clarifying questions. At Staff level, interviewers expect strategic thinking about long-term scalability and resilience, not just immediate architecture.
Focus Topics
Real-Time and Async Processing
Message queues, event streaming, eventual consistency, workflow orchestration, and handling complex multi-step operations at scale.
Practice Interview
Study Questions
API Design and Integration Patterns
RESTful API design, versioning, rate limiting, contract testing, and integration with external systems and partner platforms.
Practice Interview
Study Questions
Distributed Systems Architecture
Designing systems at scale with microservices, API gateways, load balancing, database sharding, and handling millions of concurrent users.
Practice Interview
Study Questions
Reliability, Observability, and Operational Excellence
Designing for failure modes, implementing monitoring, logging, alerting, graceful degradation, and ensuring systems remain operational under stress.
Practice Interview
Study Questions
Database Design and Optimization
SQL and NoSQL database choices, schema design, indexing, query optimization, replication strategies, and consistency models.
Practice Interview
Study Questions
Onsite Technical Round 1 - Full-Stack Implementation
What to Expect
Comprehensive technical session (90 minutes) where you design and implement a full-stack feature or system. You may work across both frontend (React/TypeScript) and backend (Node.js or Java) within the same problem. The focus is on your ability to think end-to-end: how frontend requirements translate to backend APIs, database design implications, and deployment considerations. You'll be evaluated on architectural decisions, code quality, ability to handle ambiguity, and how you balance technical depth with pragmatism.
Tips & Advice
Prepare by building small full-stack projects combining React/TypeScript with Node.js or Java backends. Practice thinking about request flow from UI to database and back. Ask clarifying questions about scale, consistency requirements, and user experience. Propose a reasonable scope and explain trade-offs (e.g., choosing a simpler database design over perfect normalization for faster delivery). At Staff level, interviewers expect you to lead the conversation, explain your decisions confidently, and adapt based on feedback. Show your experience balancing perfectionism with pragmatism in production environments.
Focus Topics
Database Schema Design
Modeling entities, relationships, defining primary/foreign keys, indexes, and optimizing for queries and operational access patterns.
Practice Interview
Study Questions
Error Handling and Resilience
Implementing proper error handling, retry logic, circuit breakers, and graceful degradation to build robust systems.
Practice Interview
Study Questions
End-to-End Feature Ownership
Taking ownership of a complete feature from specification to deployment, including testing, monitoring, and operational readiness.
Practice Interview
Study Questions
Backend API Design and Implementation
Building RESTful or GraphQL APIs, request validation, error handling, business logic implementation, and middleware patterns.
Practice Interview
Study Questions
Frontend Implementation with React and TypeScript
Building component-based UIs, state management, handling API integration, and ensuring responsive, user-friendly interfaces.
Practice Interview
Study Questions
Onsite Technical Round 2 - System Architecture Deep-Dive
What to Expect
Focused session (90 minutes) diving deep into architectural decisions and trade-offs. You may be asked to evaluate or redesign existing systems, propose architectural improvements for a real Spotify problem, or discuss how you'd evolve a system to handle 10x scale. The interviewer probes your thinking on specific components, failure modes, and operational implications. Expect technical follow-ups on why you rejected certain approaches and how you'd measure success of your design.
Tips & Advice
Study Spotify's public engineering blog and documentation about their systems. Be prepared to discuss real architectural challenges: how to scale podcast distribution, handle creator onboarding at scale, manage platform reliability, or coordinate complex workflows. Think about metrics that matter (latency, throughput, cost, availability). Discuss operational concerns: deployment strategy, rollback procedures, monitoring, and on-call support. At Staff level, demonstrate strategic thinking about long-term system evolution, not just immediate requirements. Be comfortable with ambiguity and explain how you'd gather more information or make data-driven decisions.
Focus Topics
Spotify-Specific Context: Creator and Partner Integration
Understanding how external creators and podcast networks integrate with Spotify's platform, API contracts, and scaling considerations for partners.
Practice Interview
Study Questions
Technology Stack Trade-offs
Evaluating technologies (SQL vs. NoSQL, synchronous vs. asynchronous, monolith vs. microservices) and making pragmatic choices based on requirements.
Practice Interview
Study Questions
High Availability and Disaster Recovery
Redundancy strategies, failover mechanisms, multi-region deployment, backup strategies, and ensuring continuous operation despite failures.
Practice Interview
Study Questions
Scalability and Performance Optimization
Designing systems to handle millions of operations, optimizing bottlenecks, caching strategies, database sharding, and load distribution.
Practice Interview
Study Questions
Operational Excellence and Automation
Designing systems that are easy to operate, monitor, and debug. Emphasizing automation over manual processes and self-service capabilities.
Practice Interview
Study Questions
Onsite Behavioral Round - Leadership and Impact
What to Expect
Structured behavioral interview (60 minutes) exploring your career trajectory, leadership philosophy, mentorship experience, and how you drive impact. You'll discuss past projects where you influenced technical direction, mentored engineers, navigated ambiguous situations, and handled failures. Interviewers probe for examples demonstrating ownership, collaboration across teams, resilience, and alignment with Spotify's values. Expect questions about conflict resolution, learning from mistakes, and how you advocate for technical excellence without being inflexible.
Tips & Advice
Prepare 5-7 detailed stories using the STAR format (Situation, Task, Action, Result) showcasing Staff-level impact. Focus on examples where you owned complex projects, mentored multiple engineers, influenced architectural decisions, or improved team practices. Include stories about technical failures and what you learned. Demonstrate humility, growth mindset, and commitment to inclusive collaboration. Reference Spotify's values: transparency, user-focus, creativity, and continuous improvement. Be specific about your impact (metrics, team outcomes, organizational improvements) rather than vague claims. At Staff level, emphasize how you elevated team capability and influenced strategic direction, not just individual contributions.
Focus Topics
Learning from Failure and Resilience
Examples of significant technical failures or challenges, how you handled them, learned from mistakes, and improved processes.
Practice Interview
Study Questions
Cross-Functional Collaboration
Working effectively with backend engineers, SREs, product managers, support teams, and other stakeholders to deliver solutions.
Practice Interview
Study Questions
Ownership and Accountability
Taking end-to-end responsibility for complex projects or systems, making decisions, and seeing them through to production and beyond.
Practice Interview
Study Questions
Technical Leadership and Mentorship
Mentoring junior and mid-level engineers, guiding architectural decisions, conducting code reviews, and developing team members' careers.
Practice Interview
Study Questions
Driving Engineering Excellence Standards
Initiatives to improve code quality, testing practices, observability, incident response, or team processes across teams.
Practice Interview
Study Questions
Onsite Culture and Values Fit Round
What to Expect
Conversational session (45 minutes) with a senior team member or manager exploring cultural alignment, work style, values, and long-term career aspirations. Discuss your philosophy on collaboration, transparency, continuous learning, and how you handle ambiguity. Interviewers assess whether you'll thrive in Spotify's creative, fast-paced environment and align with their commitment to unlocking creator potential and serving users. This round evaluates mutual fit and answers questions about team dynamics, growth opportunities, and what success looks like.
Tips & Advice
Research Spotify's mission deeply: unlocking creative potential for artists and giving fans access to the audio they love. Reference specific Spotify initiatives or values in your responses. Show genuine curiosity about the team's mission and how the role contributes. Discuss your learning philosophy, openness to feedback, and comfort with ambiguity. Be authentic about your working style and ask thoughtful questions about team dynamics, support systems, and how success is measured. At Staff level, discuss how you create psychological safety for your team, foster transparency, and balance guidance with autonomy. Mention your interest in Spotify's focus on AI-powered approaches and automation.
Focus Topics
Work-Life Integration and Team Support
Understanding how you approach remote work flexibility, support for team members' well-being, and sustainable pace.
Practice Interview
Study Questions
Continuous Learning and Growth Mindset
Commitment to learning new technologies, understanding business context, and developing team members' capabilities.
Practice Interview
Study Questions
Inclusive Team Leadership
Creating psychological safety, valuing diverse perspectives, supporting colleagues' growth, and fostering an environment where everyone thrives.
Practice Interview
Study Questions
Collaboration and Transparency Values
Commitment to open communication, sharing knowledge, seeking diverse perspectives, and making decisions transparently.
Practice Interview
Study Questions
Alignment with Spotify's Creator and User Mission
Understanding and genuine commitment to Spotify's goal of supporting millions of creators while serving billions of users.
Practice Interview
Study Questions
Frequently Asked Full-Stack Developer Interview Questions
A suite of UI tests passes locally but fails intermittently on pull requests in CI. What steps would you take to reproduce the issue, identify the root cause, and reduce the flakiness without simply deleting the tests?
Sample Answer
I’d treat this like a reproducibility and isolation problem first, not a test-writing problem.
My steps would be:
- Re-run the exact CI artifact locally if possible: same commit, same build type, same simulator/emulator image, same locale and device size.
- Collect evidence: logs, screenshots/video, test order, network activity, and whether failures correlate with timing or a specific screen.
- Narrow the scope: run the failing test alone, then with nearby tests, then in the full suite to see if there is shared state leakage.
- Check common mobile causes: animations not disabled, missing synchronization, stale app state, async work still running, resource contention, or dependence on previous tests.
- Fix the root cause by making the test deterministic: better selectors, explicit waits on app state, hermetic test data, reset between tests, and stable test fixtures.
I would only use retries as a temporary shield, not a fix. If a test is still flaky after that, I’d quarantine it short-term, keep the behavior covered elsewhere, and assign ownership until the underlying issue is resolved.
An effect sets state that is also in its own dependency list, and the page freezes. Reproduce the loop in a few lines and walk through how you would break it, saying when each fix is appropriate.
Sample Answer
An effect is a function React runs after it has drawn a render, and its dependency list is the set of values that decides whether it runs again. If the effect sets a piece of state that is also in that list, every run causes a new render, the new render changes the dependency, and the effect runs again, forever. To break the loop, first decide what the effect was supposed to do, because the right fix depends on that: delete the effect, move the work into an event handler, compute the value during render, change what the list contains, or make the state update a no-op when nothing changed.
Reproducing the loop in a few lines
function SelfCount() {
const [n, setN] = useState(0);
useEffect(() => {
setN(n + 1); // changes n ...
}, [n]); // ... which is the dependency, so the effect runs again
return <p>n={n}</p>;
}
React compares each dependency with the previous render's value using Object.is (a strict "same value" check: two different objects or arrays are never equal, even if their contents match). n goes from 0 to 1, so the effect runs again, sets 2, and so on. The same loop appears in two less obvious shapes, which the runnable demo below reproduces:
- An object or array created during render in the list.
const options = { q }is a new object on every render, so[options]always "changed", and an effect that sets state therefore re-renders and re-createsoptions. - An effect that writes a freshly built copy of the state it watches.
setItems(items.filter(...))returns a new array even when nothing was removed, so[items]changes on every run.
Breaking the loop: which fix fits which intent
| What the effect was meant to do | Fix | Why it is correct |
|---|---|---|
| Run once to initialise something | Empty list [], and use an updater setN(v => v + 1) | Nothing in the list can change. An updater is the function form of the setter: React calls it with the latest queued state, so the code does not need to read n from the closure (the snapshot of variables that one render's function captured) |
| React to a user action (a click, a submit) | Delete the effect, do the work in the event handler | The cause is the event, not the render. No dependency to get wrong |
| Compute a value from props or state | Delete the effect and the state, compute during render (useMemo if costly) | The value cannot drift out of sync with its inputs, and there is no extra render |
| Re-run when a value changes, where the list holds an object or function | Depend on the primitives inside it ([q]), or stabilise the object with useMemo | Equality is checked on values that only change when they really change |
| Normalise or clean state that must stay in state | Functional update that returns the previous array/object when nothing changed | React bails out (stops early and skips re-rendering the component's children) when the new state is identical to the current one, so the cycle ends |
| Synchronise with something outside React (a fetch, a subscription) | Keep the effect, but keep the state it writes out of its own list | The list should name what the effect reads from the outside world, not what it writes |
The react.dev guide says: "When something can be calculated from the existing props or state, don't put it in state. Instead, calculate it during rendering." On the equal-value rule, the useState reference says: "If the new value you provide is identical to the current state, as determined by an Object.is comparison, React will skip re-rendering the component and its children."
Removing a dependency from the list just to stop the loop is the wrong move when the effect really reads that value: the effect then uses a stale value (a copy captured by an earlier render: an effect that read n as 0 keeps reading 0 after the state has moved on), and the hook lint rules in eslint-plugin-react-hooks will flag it. Use an updater, restructure, or move the work, and keep the list honest.
Worked example: nine components, one counter
The demo renders each broken and fixed version under jsdom (a simulated browser in Node) and counts renders with a plain counter. The broken versions contain a safety valve that stops them at 25 renders so the script finishes instead of freezing. Each broken case asserts that the valve was hit. The four fixed components that still run an effect (InitOnce, ObjDepPrimitive, ObjDepMemo, PruneGuarded) carry the same valve and assert that it was not hit, so a fix that stops working fails an assertion instead of freezing the script. ClickCount and PruneDerived have no effect, so they have no valve; the demo asserts their render counts instead.
The first eleven lines of the listing (up to the Testing Library import) are environment setup, not part of the technique. JSDOM builds a fake browser page; the next three lines expose its window, document and navigator as globals that React and Testing Library look for; IS_REACT_ACT_ENVIRONMENT = true tells React that updates are wrapped in act(), the test helper that makes React finish pending state updates and effects before returning, which Testing Library's render does for you. The unused names pulled out of React and Testing Library are never used and can be ignored.
The nine components pair up as follows:
SelfCountis the loop;InitOncemakes the same effect run once, andClickCountmoves the increment into the click handler.ObjDepputs a fresh object in the list;ObjDepPrimitivelists the stringqinstead, andObjDepMemokeeps the object but only rebuilds it whenqchanges.Prunewrites a new array on every run;PruneGuardedreturns the old array when nothing was removed, andPruneDerivedhas no effect and no extra state.
// effect-loop.mjs
import { JSDOM } from 'jsdom';
import assert from 'node:assert/strict';
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost/' });
globalThis.window = dom.window;
globalThis.document = dom.window.document;
Object.defineProperty(globalThis, 'navigator', { value: dom.window.navigator });
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
const React = (await import('react')).default;
const { useState, useEffect, useMemo, useCallback, useRef, memo, useReducer } = React;
const { render, screen, fireEvent, cleanup, act, waitFor } = await import('@testing-library/react');
const h = React.createElement;
const CAP = 25; // safety valve so the demo ends instead of freezing the tab
function makeCounter() {
return { renders: 0, runaway: false };
}
// Case 1: the effect sets the state that is in its own dependency list.
function SelfCount({ c }) {
const [n, setN] = useState(0);
c.renders++;
useEffect(() => {
if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve
setN(n + 1);
}, [n]);
return h('p', null, 'n=' + n);
}
// Fix 1a: the intent was "initialise once on mount": empty list plus an updater.
function InitOnce({ c }) {
const [n, setN] = useState(0);
c.renders++;
useEffect(() => {
if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve
setN((v) => v + 1);
}, []);
return h('p', null, 'n=' + n);
}
// Fix 1b: the intent was "count clicks": the work belongs in the handler.
function ClickCount({ c }) {
const [n, setN] = useState(0);
c.renders++;
return h('button', { onClick: () => setN(n + 1) }, 'n=' + n);
}
// Case 2: an object literal built during render is in the dependency list.
function runSearch(o) { return ['hit:' + o.q]; }
function ObjDep({ c, q }) {
const [results, setResults] = useState([]);
c.renders++;
const options = { q };
useEffect(() => {
if (c.renders >= CAP) { c.runaway = true; return; }
setResults(runSearch(options));
}, [options]);
return h('p', null, results.join(','));
}
function ObjDepPrimitive({ c, q }) {
const [results, setResults] = useState([]);
c.renders++;
useEffect(() => {
if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve
setResults(runSearch({ q }));
}, [q]);
return h('p', null, results.join(','));
}
function ObjDepMemo({ c, q }) {
const [results, setResults] = useState([]);
c.renders++;
const options = useMemo(() => ({ q }), [q]);
useEffect(() => {
if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve
setResults(runSearch(options));
}, [options]);
return h('p', null, results.join(','));
}
// Case 3: the effect writes a fresh array derived from the state it watches.
function Prune({ c }) {
const [items, setItems] = useState([3, 1, 2]);
c.renders++;
useEffect(() => {
if (c.renders >= CAP) { c.runaway = true; return; }
setItems(items.filter((x) => x > 0)); // new array even when nothing is removed
}, [items]);
return h('p', null, items.join(','));
}
function PruneGuarded({ c }) {
const [items, setItems] = useState([3, 1, 2]);
c.renders++;
useEffect(() => {
if (c.renders >= CAP) { c.runaway = true; return; } // demo-only valve
setItems((prev) => {
const next = prev.filter((x) => x > 0);
return next.length === prev.length ? prev : next; // same reference: React bails out
});
}, [items]);
return h('p', null, items.join(','));
}
function PruneDerived({ c }) {
const [items] = useState([3, 1, 2]);
c.renders++;
const visible = useMemo(() => items.filter((x) => x > 0), [items]);
return h('p', null, visible.join(','));
}
function run(label, Comp, props = {}) {
const c = makeCounter();
const view = render(h(Comp, { c, ...props }));
const out = { label, renders: c.renders, runaway: c.runaway };
console.log(JSON.stringify(out));
return { c, view };
}
let r;
r = run('1 broken self-count', SelfCount);
assert.equal(r.c.runaway, true); assert.ok(r.c.renders >= CAP); cleanup();
r = run('1a init once', InitOnce);
assert.equal(r.c.runaway, false); assert.equal(r.c.renders, 2); cleanup();
r = run('1b handler', ClickCount);
assert.equal(r.c.renders, 1);
fireEvent.click(screen.getByRole('button'));
console.log(JSON.stringify({ label: '1b after click', renders: r.c.renders }));
assert.equal(r.c.renders, 2); cleanup();
r = run('2 broken object dep', ObjDep, { q: 'a' });
assert.equal(r.c.runaway, true); cleanup();
r = run('2a primitive dep', ObjDepPrimitive, { q: 'a' });
assert.equal(r.c.renders, 2); assert.equal(r.c.runaway, false); cleanup();
r = run('2b useMemo dep', ObjDepMemo, { q: 'a' });
assert.equal(r.c.renders, 2); assert.equal(r.c.runaway, false); cleanup();
r = run('3 broken prune', Prune);
assert.equal(r.c.runaway, true); cleanup();
r = run('3a guarded updater', PruneGuarded);
const guardedRenders = r.c.renders;
assert.ok(guardedRenders <= 2, 'bounded'); assert.equal(r.c.runaway, false); cleanup();
r = run('3b derived in render', PruneDerived);
assert.equal(r.c.renders, 1);
assert.equal(screen.getByText('3,1,2') !== null, true);
console.log('all assertions passed');
Run in a node:22 container (Node 22.23.3), it prints:
{"label":"1 broken self-count","renders":25,"runaway":true}
{"label":"1a init once","renders":2,"runaway":false}
{"label":"1b handler","renders":1,"runaway":false}
{"label":"1b after click","renders":2}
{"label":"2 broken object dep","renders":25,"runaway":true}
{"label":"2a primitive dep","renders":2,"runaway":false}
{"label":"2b useMemo dep","renders":2,"runaway":false}
{"label":"3 broken prune","renders":25,"runaway":true}
{"label":"3a guarded updater","renders":1,"runaway":false}
{"label":"3b derived in render","renders":1,"runaway":false}
all assertions passed
Reading the output: the three broken components reach the 25-render valve. The initialise-once version and the primitive-dependency version settle at 2 renders (the first render plus one update from the effect). The click handler version stays at 1 render until the click and then goes to 2. The derived value stays at 1 render, because no effect runs at all. The guarded updater also showed 1 render in this run; the useState docs warn that React may sometimes call the component once more before bailing out, so treat 1 to 2 as the expected range and the loop being gone as the guarantee.
Trade-offs and pitfalls
- Deleting the effect is the best fix more often than not, because the effect only existed to copy one value into state after rendering. The "derived state in an effect" pattern costs an extra render even when it does not loop.
useMemofor an object dependency is a fix for the identity problem only. If the memo's own inputs are new objects every render, it is memoizing nothing.- A guard such as
if (n < 10) setN(n + 1)stops the freeze but leaves a render cascade, and it hides the design problem. Use it only when the cascade is the intended behaviour. - Fetch effects that set state with the response need a different protection (ignore stale responses, cancel on cleanup). The dependency list is still the place to look first when the page spins.
- In the browser, find the culprit with the React DevTools Profiler (a recorded session shows the same component committing again and again; a commit is the step where React writes a finished render into the page, and the Profiler lists one per update).
Running the code
mkdir loop && cd loop && printf '{"type":"module"}' > package.json
npm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16.0.1 @testing-library/dom@10.4.0 jsdom@25.0.1
node effect-loop.mjs # the listing above
Your service stores user-uploaded images. Thumbnails get requested constantly, but the original full-resolution files are almost never read again after the first day. Design a strategy that meaningfully cuts the object storage bill, and walk through the trade-offs of whatever approach you land on.
Sample Answer
Approach
Two very different access patterns share one storage bill: thumbnails are read constantly but are tiny, originals are large but almost never read again after day one. Design around that asymmetry instead of applying one policy to both.
Strategy
- Thumbnails: keep in standard (hot) storage, and put a CDN (content delivery network, a caching layer close to users) in front of them with a long cache TTL (time-to-live). Since they're small and requested constantly, the CDN absorbs most of the read traffic, keeping origin storage cost and request cost low even though the tier itself is the expensive one.
- Originals: transition to a cheaper, infrequent-access class after a short buffer (a couple of days, not day one, since users often edit or delete a fresh upload and an early transition can trigger a minimum-storage-duration charge), then to an archive-class tier after a longer window, since the question states they're "almost never read again" past the first day.
Worked example
At 10 million images/month, average 4 MB originals and 50 KB thumbnails: originals total about 39,060 GB/month, thumbnails about 477 GB/month, so originals are roughly 80x the stored bytes even though thumbnails get nearly all the traffic. At an illustrative $0.023/GB-month, leaving originals in standard storage costs about $898/month per monthly cohort; moving them to an archive class at an illustrative $0.004/GB-month cuts that to about $156/month, a saving near $742/month (about 83%) per cohort, compounding every month new uploads land. Thumbnails, by contrast, cost only about $11/month even fully hot, because they're small; there's no real saving available there, which is exactly why they're not worth tiering down.
Trade-offs
- Archiving originals adds retrieval latency and a retrieval fee for the rare user who wants their full-resolution download; that's an acceptable trade given how rarely it happens, but the product needs a "this may take a moment" state for that path.
- An alternative or complementary lever is re-encoding originals to a smaller lossy format once they're old enough that print-quality is unlikely to matter, trading some quality for less-than-linear byte reduction; worth evaluating if archive-tier savings alone aren't enough, but it's a one-way, quality-losing move, so treat it separately and more cautiously than a reversible storage-class transition.
A piece of work you own needs a technique you have not used before, and there is nobody in house who has used it either. How do you get to the point where you trust your own application of it, and how do you tell the people relying on the result how much weight to put on it?
Sample Answer
Direct answer
Before I trust my own application of a technique nobody in-house has used, I deliberately design a check that would catch me being wrong, usually by running it against a case where I already know the right answer, and I only report a result to people relying on it alongside an honest statement of what that validation did and did not cover. Trust here comes from actively trying to break my own understanding and failing, not from the technique simply producing an answer that looks reasonable.
Structured elaboration
- Before applying the new technique to the real problem, find or construct a case with a known answer, synthetic data with a known effect, a smaller version of the problem you can verify by hand, or a case where an established method already gives a trusted answer, and confirm the new technique recovers it.
- Sanity-check the assumptions the method actually requires, not just whether it runs; many techniques silently produce an output even when their assumptions are violated.
- Design the validation to specifically target where you are least confident, not the part you already understand well; a check that only confirms what you already believed is not doing much work.
- Communicate confidence and limitations in terms the audience can actually evaluate, what was tested, what was not, and what would change your confidence, rather than a bare number.
Worked example
Needed to estimate the causal effect of a new onboarding flow on retention using a technique nobody on the team had used before, synthetic control (a method that builds an artificial comparison group from a weighted blend of untreated units to estimate what would have happened without the change), for a business case going to leadership. Before touching the real question, I built a known-answer test: I took a metric with an already-established, trusted causal estimate from a past well-instrumented randomized test, reconstructed it using the new technique on the same historical data, and confirmed the synthetic-control estimate landed close to the randomized-test answer. That gave a concrete reason to trust the method beyond it having run and produced a chart. Before applying it to the real question, I explicitly checked the assumption the method depends on, that the synthetic control's pre-period trend actually tracked the treated group closely, rather than assuming it did because the model converged. When presenting to leadership, I stated plainly what had been validated, the method recovering a known answer on a comparable case, and the pre-trend assumption holding reasonably well here, and what had not, a small sample size for the treated group that widens the honest uncertainty, rather than presenting one confident number.
Trade-offs and pitfalls
- Treating "the code ran and produced an output" as proof of correctness is the most common way a newly learned technique gets misapplied; a known-answer check is what actually earns trust.
- Skipping the assumption check because the output looks reasonable is dangerous specifically because a technique can produce a plausible-looking wrong answer when its assumptions are violated.
- Presenting a confident single number to an audience that cannot independently evaluate the method, without naming what was and was not validated, sets up a false sense of certainty that is hard to walk back later.
Explain the difference between a stack and a queue and give a concrete example where each is the right choice. Then show how you would implement a queue using only two stacks (or a stack using only queues), and give the amortized cost per operation.
Sample Answer
Direct answer
A stack is last-in-first-out (LIFO): the most recently added item comes out first. A queue is first-in-first-out (FIFO): items come out in the order they arrived. Use a stack when you need to undo or backtrack in reverse arrival order, such as a browser's back button or a function call stack; use a queue when arrival order must be preserved, such as a task scheduler or a print spooler. You can build a queue out of two stacks: push is O(1) worst case, and pop is amortized (averaged over a sequence of operations) O(1) because each element only ever moves between the two stacks once over its lifetime.
Structured elaboration
| Stack (LIFO) | Queue (FIFO) | |
|---|---|---|
| Order returned | Most recent first | Oldest first |
| Concrete example | Undo history, expression parsing, recursive call stack | Print queue, request processing, breadth-first search frontier |
Queue from two stacks. Keep an in_stack that absorbs pushes and an out_stack that serves pops. Pushing always goes to in_stack in O(1). When a pop or peek is requested and out_stack is empty, drain all of in_stack into out_stack; this reverses the order, so the oldest element (which was at the bottom of in_stack) ends up on top of out_stack, ready to be returned first.
Why the amortized argument holds. Use the aggregate method: over any sequence of n operations, each element is pushed onto in_stack exactly once (cost 1), moved from in_stack to out_stack at most once in its lifetime (cost 1), and popped from out_stack exactly once (cost 1). No element is ever moved more than that, so the total work across the whole sequence is bounded by a constant multiple of n, which is what "amortized O(1) per operation" means, even though any single pop that triggers the drain costs O(n) by itself.
Worked example
class QueueFromStacks:
def __init__(self):
self.in_stack: list[int] = []
self.out_stack: list[int] = []
def push(self, x: int) -> None:
self.in_stack.append(x)
def _transfer(self) -> None:
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
def pop(self) -> int:
self._transfer()
return self.out_stack.pop()
def peek(self) -> int:
self._transfer()
return self.out_stack[-1]
if __name__ == "__main__":
q = QueueFromStacks()
q.push(1)
q.push(2)
q.push(3)
seq = [q.pop(), q.peek()]
q.push(4)
seq += [q.pop(), q.pop(), q.pop()]
print(seq)
Running this prints [1, 2, 2, 3, 4]. The first pop() triggers a drain (in_stack [1,2,3] becomes out_stack [3,2,1], top popped is 1); peek() then reads 2 for free from the already-drained out_stack; pushing 4 goes straight to in_stack without disturbing out_stack; the remaining pops (2, 3) come from out_stack, and the last pop (4) triggers a second drain since out_stack had emptied.
Complexity
| Push | Pop / peek | |
|---|---|---|
| Worst case (single call) | O(1) | O(n) |
| Amortized (over n calls) | O(1) | O(1) |
Space: O(n) total across the two internal stacks, since every pushed element lives in exactly one of them at any time (no extra space is used beyond storing the n elements themselves).
Edge cases
- Calling
pop()orpeek()on an empty two-stack queue: in the reference implementation,_transfer()leavesout_stackempty when both stacks are empty, sopop()'sself.out_stack.pop()andpeek()'sself.out_stack[-1]both raise an unhandledIndexErrorinstead of failing cleanly. Guard this explicitly, for exampleif not self.in_stack and not self.out_stack: raise IndexError("pop from empty queue")before touchingout_stack, so the caller gets a clear, intentional signal rather than an incidental one. - A single push followed immediately by a pop: the drain moves that one element from
in_stacktoout_stackand it is returned, leaving both stacks empty again, which is the state the empty-queue guard above must handle correctly on the next call.
Trade-offs & pitfalls
The most common confusion is treating "amortized" as "always fast": a single pop can still cost O(n) when it triggers the drain. Note the asymmetry with building a stack out of a single queue by rotating on every push (dequeue-then-requeue the previous elements so the newest sits at the front): that rotation happens on every single push, not just occasionally, so it is genuinely O(n) per push with no amortization to appeal to, unlike the two-stack construction above where the expensive transfer is rare and each element only ever pays for it once.
Design an idempotent consumer for processing payment events from a message queue. Message format: {payment_id, user_id, amount, currency, timestamp}. Requirements: prevent double-charges on redelivery, support at-least-once delivery semantics from the broker, allow retries, and maintain low latency. Describe the deduplication store, choices between in-memory, Redis, or relational DB, TTL strategy, and cleanup considerations.
Sample Answer
Direct answer
Derive the deduplication (dedup) key from the payment's own business identity, payment_id, not from anything the broker generates, then make claiming that key and processing the payment a single atomic step: check-and-claim, process, mark done. Redelivery of the same message must always produce the same payment_id, so a redelivered message collapses onto the same key and gets skipped instead of charged again.
Structured elaboration
Why payment_id, not the other fields. The message is {payment_id, user_id, amount, currency, timestamp}. user_id alone is wrong (one user can legitimately make two separate payments). (user_id, amount, timestamp) is also wrong: two real, distinct charges can share the same amount, and timestamp is set by the producer, so a retried publish can carry a different timestamp for the same logical payment while a coincidentally identical tuple could describe two different real charges. payment_id is the one field that is supposed to be stable across every redelivery of the same logical event, which is exactly the property a dedup key needs.
The atomicity requirement. "At-least-once delivery from the broker" means the same message will arrive more than once, by design, not as an edge case. If the consumer does exists = store.get(payment_id) followed by a separate store.set(payment_id, ...), two redeliveries handled concurrently (two consumer threads, or two instances in the same consumer group during a rebalance) can both read "not found" before either writes, and both charge. The claim has to be a single atomic operation: "insert this key only if it does not already exist," succeed-or-fail in one round trip.
Store choice: in-memory vs. Redis vs. relational database.
| Store | Atomic claim primitive | Round-trip cost | Durability across restarts | Shared across consumer instances | Best fit here |
|---|---|---|---|---|---|
| In-memory (process-local dict or least-recently-used, LRU, cache) | Check-then-insert under a single process lock | Lowest | None, lost on restart | No | A fast pre-check layer in front of a durable store, never the sole source of truth |
| Redis | SET key value NX PX ttl_ms (atomic in one command) | Low, one round trip | Best-effort unless persistence is explicitly enabled | Yes | Primary dedup store when "maintain low latency" is a hard requirement |
| Relational database | INSERT ... ON CONFLICT DO NOTHING or a unique constraint on payment_id | Higher, a transactional write | Full, same guarantees as the ledger | Yes | When the claim and the actual charge write must commit as one atomic transaction |
For a payment consumer, Redis is usually the right default for the hot path because "maintain low latency" is an explicit requirement and the claim is a single command. The relational option earns its extra latency specifically when you want the dedup row and the ledger write to be atomically consistent with each other, for example inserting the dedup row in the same transaction as the row that records the charge, so a crash between "claim" and "charge" cannot leave the dedup store and the ledger disagreeing.
Probabilistic pre-filter. At high volume, a Bloom or cuckoo filter can sit in front of the authoritative store as a cheap "have I possibly seen this before" check: a negative result is certain (definitely new, skip the store lookup and go straight to processing), a positive result is only "maybe," and must still fall through to the authoritative store, because treating a false positive as certain would silently drop a legitimate first-time charge. A cuckoo filter additionally supports deletion, which matters if you want the filter itself to track a rolling window rather than growing forever. Either filter is an optimization that reduces load on the durable store for the (usually large) fraction of genuinely-new events; it never replaces the store as the source of truth.
TTL strategy. The dedup key's time-to-live (TTL) must be at least as long as the broker's own maximum redelivery window plus a safety margin. If the broker can, in the worst case, redeliver a message up to 12 hours after first delivery (for example, a long consumer outage followed by catch-up), a TTL shorter than that lets the key expire and a legitimate-looking "new" charge slip through on a very late, otherwise-normal redelivery. TTL should not be sized off how long you want to retain history; it should be sized off how long the broker can still legally hand you a duplicate.
Cleanup considerations. Redis expires keys natively via the TTL, no separate job needed. A relational dedup table has no native per-row expiry in most databases, so it needs an explicit periodic sweep (a scheduled DELETE WHERE created_at < now() - retention_window, i.e. a dedup-table-plus-TTL pattern implemented as a cron job rather than a database feature), or the table grows without bound and both storage cost and index lookup latency degrade over time.
flowchart TD
A[Payment event arrives] --> B{Dedup key exists in store?}
B -- Yes --> C[Skip: return prior result, no charge]
B -- No --> D[Atomically claim key: SETNX with TTL]
D --> E[Process payment]
E --> F[Mark key as done, keep TTL]
F --> G[Ack message to broker]
C --> G
Worked example
Assume 500 payment events per second sustained, and a 24 hour TTL matching the broker's stated maximum redelivery window.
live keys=rate×TTL=500×86,400=43,200,000At roughly 150 bytes per key plus value plus Redis's own per-key overhead:
bytes=43,200,000×150B≈6.48GBThat is a meaningful working set for a single Redis instance. It is exactly the kind of number that motivates either sharding the dedup store across a Redis cluster keyed by payment_id, shortening the TTL if the broker's actual redelivery window is smaller than assumed, or moving completed, already-settled payments' dedup records into the cheaper relational table once they age past the point where redelivery is still plausible.
Trade-offs and pitfalls
- Using a coarse or derived key (amount, timestamp, or a hash of the whole payload) instead of
payment_idis the single most common mistake: it either misses real duplicates (payload varies slightly across redeliveries, for example a re-serialized timestamp) or falsely merges two distinct legitimate charges. - A GET-then-SET pattern instead of a single atomic command reintroduces the exact race the dedup layer exists to prevent; this only shows up under real concurrent redelivery, so it can pass casual testing and still double-charge in production.
- Redis becoming unavailable forces an explicit choice: fail closed (stop processing new payments until Redis is back, safe but reduces availability) or fail open (keep processing without dedup protection, risks double-charges). Silently defaulting to one without deciding on purpose is itself the pitfall.
- Sizing the relational table's cleanup job off total historical volume instead of the broker's actual redelivery window wildly over-retains data and slows the unique-constraint index down for no correctness benefit.
During UAT QA finds two high-priority bugs that conflict with each other's fixes: fixing A causes regression in B. How do you triage, prioritize, and resolve both bugs in the run-up to a release?
Sample Answer
Direct answer
When two fixes conflict during User Acceptance Testing (UAT, meaning testing done by real users or stakeholders before release), the goal is not picking which bug wins in isolation. It is finding the smallest change that satisfies both constraints if one exists, or consciously shipping one as a known, mitigated issue based on user impact and release risk, not on which bug was found first.
Structured elaboration
- Reproduce and isolate the actual conflict: confirm both bugs really share the same code path, and pin down exactly which part of fix A causes the regression in B.
- Score each bug independently on user impact (how many users, how severe: a blocked core flow versus a cosmetic issue) and likelihood (how often that path is hit).
- Look for a third option before picking a side: a narrower fix scoped to the specific condition that triggers bug A, rather than a blanket change that also breaks B.
- If no clean third fix exists in the time available, decide using which bug affects more users, which is worse if it ships, and whether either can ship behind a feature flag (a toggle that turns a change on or off without a new deployment) or with a documented interim workaround.
- Timebox the investigation. In the run-up to a release, an open-ended debugging spiral is itself a risk, so set a fixed checkpoint (for example, if it is not resolved by end of day, ship with the interim mitigation and file a fast-follow).
- Get sign-off from whoever owns release risk, typically the QA lead or engineering manager, before shipping either mitigated option, and log the decision.
Worked example
Bug A: an international phone number starting with a plus sign fails client-side validation and blocks checkout entirely for users outside the United States, roughly 15% of traffic. Bug B: the fix for A, loosening the validation, causes the shipping-address autofill to misparse United Kingdom phone formats, silently dropping the last two digits, a smaller data-quality issue within that 15%. Because Bug A is a hard block on purchase and Bug B degrades a stored phone number without blocking checkout, ship the fix for A, add a secondary check that flags the malformed numbers Bug B produces for manual correction, and file a fast-follow ticket to properly separate the two validation paths.
Trade-offs and pitfalls
Reverting to the pre-fix code is not automatically the safe choice, since the pre-fix state has its own known bug. Fixing in isolation without first confirming the two bugs share a root cause wastes the limited timebox re-diagnosing something already understood. Shipping a mitigated option without documenting it as a deliberate, known trade-off makes it look like the team missed something rather than made a considered call under time pressure.
What happens when you take a function that was created with bind and call it with new? Which this and which prototype does the new object get, and which bound arguments survive?
Sample Answer
Direct answer
new on a bound function constructs the original (target) function, as if bind had never happened, with two exceptions. The this value given to bind is ignored, because new creates a fresh object to be this. The arguments given to bind are kept and placed in front of the arguments passed to new. The new object's prototype comes from the target function's prototype property, not from the bound function, which has no prototype property of its own. So new BoundPoint(2, 3) runs Point(1, 2, 3) with a brand-new this whose prototype is Point.prototype.
Step by step
A bound function is an "exotic" function object (the specification's term for an object whose internal behaviour differs from an ordinary one; here, calling and constructing it forwards to another function) that stores three things: the target function, the bound this, and the list of bound arguments. When you call new on it, the engine does this:
- Take the stored target (
Point) and build the argument list: bound arguments first, then the arguments passed tonew(so1, then2,3). - Construct the target, not the bound function. When
newwas applied directly to the bound function, thenew.targetvalue (the functionnewwas applied to, which decides the prototype of the new object) is replaced by the target. This is why insidePoint,new.target === Pointistrue. - The target's
[[Construct]](the internal method the specification uses to define whatnewdoes for a given function; double brackets mark such internal methods, which code cannot call directly) creates a new empty object whose prototype isPoint.prototype, calls the target with that object asthis, and returns it (unless the target returns an object of its own). - The
thisArghanded tobindis never used on this path.
Run
// bound_new.js
"use strict";
function Point(x, y) {
this.x = x;
this.y = y;
this.viaNew = new.target === Point;
}
Point.prototype.sum = function () { return this.x + this.y; };
const thisArg = { x: 100, y: 100 };
const BoundPoint = Point.bind(thisArg, 1);
const p = new BoundPoint(2, 3);
console.log("new BoundPoint(2, 3):", JSON.stringify(p));
console.log("thisArg untouched:", JSON.stringify(thisArg));
console.log("BoundPoint.prototype:", BoundPoint.prototype);
console.log("proto is Point.prototype:", Object.getPrototypeOf(p) === Point.prototype);
console.log("instanceof Point / BoundPoint:", p instanceof Point, p instanceof BoundPoint);
console.log("inherited method:", p.sum());
const again = BoundPoint.bind({ x: -1 }, 9);
console.log("bind of a bind:", JSON.stringify(new again(7)));
console.log("plain call:", BoundPoint(5), "thisArg now", JSON.stringify(thisArg));
function Factory() { this.a = 1; return { replaced: true }; }
console.log("target returns an object:", JSON.stringify(new (Factory.bind({}))()));
console.log("explicit newTarget:",
Object.getPrototypeOf(Reflect.construct(BoundPoint, [], Array)) === Array.prototype);
try { class Child extends BoundPoint {} } catch (e) { console.log("extends bound:", e.name + ": " + e.message); }
const arrow = (a, b) => a + b;
try { new (arrow.bind(null, 1))(2); } catch (e) { console.log("new bound arrow:", e.name + ": " + e.message); }
class Box { constructor(a, b) { this.a = a; this.b = b; } }
const BoundBox = Box.bind(null, "x");
console.log("bound class with new:", JSON.stringify(new BoundBox("y")));
try { BoundBox("y"); } catch (e) { console.log("bound class without new:", e.name + ": " + e.message); }
Run with Node 22, it prints:
new BoundPoint(2, 3): {"x":1,"y":2,"viaNew":true}
thisArg untouched: {"x":100,"y":100}
BoundPoint.prototype: undefined
proto is Point.prototype: true
instanceof Point / BoundPoint: true true
inherited method: 3
bind of a bind: {"x":1,"y":9,"viaNew":true}
plain call: undefined thisArg now {"x":1,"y":5,"viaNew":false}
target returns an object: {"replaced":true}
explicit newTarget: true
extends bound: TypeError: Class extends value does not have valid prototype property undefined
new bound arrow: TypeError: arrow.bind(...) is not a constructor
bound class with new: {"a":"x","b":"y"}
bound class without new: TypeError: Class constructor Box cannot be invoked without 'new'
Reading the results against the three questions
- Which
this? A new object, notthisArg.thisArgstays{x: 100, y: 100}afternew, and the result holdsx: 1, y: 2. - Which prototype?
Point.prototype.BoundPoint.prototypeisundefined, yet the new object inheritssumfromPoint.prototype.instanceofalso works against the bound function itself: it looks through to the target'sprototype, so bothp instanceof Pointandp instanceof BoundPointaretrue. MDN documents the same:new.target,instanceofandthisbehave as if the constructor was never bound, and the only difference is that a bound function cannot be used withextends, which theextends boundline shows. - Which arguments survive? Bound arguments always survive, in front.
Point(1, 2, 3)only readsxandy, so the3is ignored byPoint. Binding a bound function again (again) keeps the earlier bound arguments in order:BoundPointcontributes1,againadds9, andnew again(7)callsPoint(1, 9, 7)givingx: 1, y: 9. The outer{ x: -1 }thisis ignored just as the inner one is.
The same function called without new
The plain call BoundPoint(5) uses the bound this: it ran Point with thisArg as this, so it overwrote thisArg.x and thisArg.y with 1 and 5, set viaNew to false, and returned undefined (the target returns nothing). This is the reason one bound function behaves differently in the two call styles, and the reason constructor code should not depend on this being the bind argument.
Pitfalls
The cases below all come from one rule: construction goes to the target function, and only the arguments (and, via newTarget, the prototype) of the new call carry through.
- Return value of the target. If the target returns an object (as
Factorydoes),newproduces that object instead of the freshthis, with or withoutbind. - Arrow functions have no
[[Construct]], so a bound arrow function cannot be used withnewat all (the error line above). - Classes can be bound and constructed with
new; calling the bound class withoutnewstill throws because the class constructor requires it. Reflect.construct(BoundPoint, [], Array):Reflect.construct(F, args, newTarget)is the function form ofnew, and its third argumentnewTargetis the value thatnew.targetwould take and that picks the prototype of the new object. Here it passes a differentnewTarget. Only whennewTargetis the bound function itself is it swapped for the target; here it staysArray, so the object getsArray.prototype. This is the rule behind the "explicit newTarget" line.- No
extends. Because the bound function lacks aprototypeproperty,class Child extends BoundPointthrows. Extend the original function and bind afterwards.
Running the code
# Node 22
node bound_new.js
Your profile page shows a follower count. A user taps follow, refreshes, and the count is unchanged or briefly wrong. Walk me through why that can happen across the UI, API and database, when you would accept it, and when you would not.
Sample Answer
Direct answer
An edge row is one row in a follows table saying "user A follows user B" (in a social graph the people are nodes and each follow is an edge). That row is the truth. The count is a derived value: a number computed from the edge rows and then stored or cached for speed, so it can disagree with them for a while. The profile page can read the count from several places that each lag the edge rows by a different amount: an HTTP or CDN cache (content delivery network, a cache near the user that serves saved copies of responses), a database read replica (a copy of the database that trails the main one, called the primary), a counter that a batch job updates later, or the client's own cache overwriting the screen with an older response.
Start with step 1 of the checks below. One look at the follow request and the next profile GET shows whether the right number ever left the server, and that splits "a cache or the client is at fault" from "the database is at fault". Then split what must be exact from what may be late. Accept a late count on someone else's popular profile. Never accept a wrong answer to "do I follow this person?", never let a stale response undo the user's own action (the property usually called read-your-own-write: after you write something, your own next read must show it), and never accept a count that does not converge, meaning it must settle back to the true value without anyone repairing it by hand.
Why it happens, layer by layer
| Layer | Mechanism | What the user sees |
|---|---|---|
| UI | A refetch or poll that started before the tap returns afterwards and overwrites the optimistic number | count flickers back to the old value, correct on the next load |
| HTTP / CDN cache | The profile response carries a Cache-Control header (it tells caches whether and how long they may keep the response; a shared cache is one that serves many users, such as a CDN) that lets a shared cache keep it; the refresh is served from that copy | count unchanged after refresh, response has an Age header above zero |
| API | The follow response omits the new count, so the client has nothing newer to show | count briefly wrong until the next fetch |
| Database replica | The read goes to a replica that has not yet applied the write | count (and sometimes the button) wrong for a short time, then right |
| Counter | The stored counter is updated by a later job, or by a code path that is not idempotent | wrong until the job runs, or wrong permanently |
Ordered checks (cheapest and most informative first)
- Network panel, same tap. In Chrome DevTools, Network tab: find the follow request and read its response body (did it return
follower_count?). Then find the profileGETafter the refresh: read the body, and in Headers readCache-ControlandAge.Ageis the number of seconds the response has sat in a shared cache, for exampleAge: 37(illustrative value); a header showingAgeabove zero means a shared cache served it, and noAgeheader suggests the response came from the origin. A body with the right count that the screen does not show means the client discarded it (go to step 5). - Bypass caches. Tick "Disable cache" for the browser cache, and replay the request with a
Cache-Control: no-cacheheader or a unique query string to skip shared ones. If the count is now right, a cache is the cause; fixCache-Controlfor the viewer-specific part of the response. - Ask the primary database. Compare the stored counter with the real edge count for that user. If the edge row is missing, the write never happened; if it exists but the counter is off, go to step 4. The queries below do this and show the repair. Here a follow tap becomes an
INSERTintofollowsin the request; theusers.follower_countcounter is not touched in that request, and a batch job fixes it later, which is the state the first query catches in between. - Check replica lag and the job. On the replica run
SELECT pg_last_xact_replay_timestamp()(the commit time, as it was on the primary, of the last transaction the replica applied; PostgreSQL documents that it returns NULL when the server was started normally without recovery, which is why it is only meaningful on a replica). The result is a timestamp such as2026-10-07 12:00:03+00(illustrative); compare it withnow()on the replica, and a gap of several seconds means that replica is that far behind the primary, assuming the primary is taking writes. If the count is right on the primary and late on the replica, the read path is the cause. If both are late, look at when the batch job last ran. - Client cache. In the app's query-cache devtools (or logging), check whether a refetch that began before the mutation completed wrote its result after the mutation's result.
The database side, run in a postgres:16 container. Query 1 puts the stored counter next to a live count of edge rows. Query 2 asks one exact question about one pair of users. Query 3 is the drift check: LEFT JOIN keeps users who have no followers at all, coalesce(c.n, 0) turns the missing count into 0, and the WHERE keeps only rows where counter and edge count differ. Query 4 recomputes each user's real count with a correlated subquery (a subquery that is re-run for each user row, using that row's id) and overwrites only the counters that are wrong.
CREATE TABLE users (id bigint PRIMARY KEY, follower_count integer NOT NULL DEFAULT 0);
CREATE TABLE follows (
follower_id bigint NOT NULL, followee_id bigint NOT NULL,
PRIMARY KEY (follower_id, followee_id)
);
INSERT INTO users SELECT g FROM generate_series(1, 5) g;
-- three people follow user 1; the counter is maintained later by a batch job, not in the request
INSERT INTO follows VALUES (2, 1), (3, 1), (4, 1);
-- 1. what the profile page's cached counter says, and what the edge table says
SELECT u.follower_count AS counter, (SELECT count(*) FROM follows f WHERE f.followee_id = u.id) AS edges
FROM users u WHERE u.id = 1;
-- 2. "do I follow this account?" is a primary-key lookup on the edge table, so it is exact while the counter lags
SELECT EXISTS (SELECT 1 FROM follows WHERE follower_id = 3 AND followee_id = 1) AS viewer_follows;
-- 3. drift check: rows where the stored counter and the real edge count disagree
SELECT u.id, u.follower_count AS counter, coalesce(c.n, 0) AS edges
FROM users u LEFT JOIN (SELECT followee_id, count(*) AS n FROM follows GROUP BY 1) c ON c.followee_id = u.id
WHERE u.follower_count <> coalesce(c.n, 0);
-- 4. the repair (also the nightly rollup)
UPDATE users u SET follower_count = coalesce(c.n, 0)
FROM (SELECT u2.id, (SELECT count(*) FROM follows f WHERE f.followee_id = u2.id) AS n FROM users u2) c
WHERE c.id = u.id AND u.follower_count <> c.n;
SELECT follower_count AS counter_after_repair FROM users WHERE id = 1;
It prints:
counter | edges -> 0 | 3
viewer_follows -> t
drift check (id, counter, edges) -> 1 | 0 | 3
counter_after_repair -> 3
Reading the output: the first line shows the counter at 0 while three edge rows exist; the second shows user 3 follows user 1; the drift check lists only user 1 (users 2 to 5 have counter 0 and 0 edges, so they match); after the repair the counter reads 3. The counter says 0, the edge table says 3, and the exact question "does user 3 follow user 1?" is still answered correctly by the primary-key lookup. This is the key design point: the button state comes from the edge row, the number may come from a derived value.
The fix on the client: the pending marker plus a viewer-state check
Names in the code: confirmed is the last state the server told us about for the viewer's own follow action, pending is true while that request is on the wire, a snapshot is any profile response (from a refetch, poll, cache or replica) carrying viewer_follows and follower_count, and onSnapshot decides whether to apply it. The button itself shows the new state as soon as pending is true; the log prints confirmed, so following=false right after the tap is expected and does not mean the button is wrong.
// confirmed = last server answer to MY action; pending = a request of mine is on the wire
const initial = { confirmed: { following: false, count: 41 }, pending: false };
function onTap(s) { return { ...s, pending: true }; }
function onResponse(s, r) { return { confirmed: { following: r.following, count: r.follower_count }, pending: false }; }
function onSnapshot(s, snap) {
if (s.pending) return { state: s, action: 'ignored: my request is in flight' };
if (snap.viewer_follows !== s.confirmed.following)
return { state: s, action: 'discarded: snapshot disagrees about MY follow state, refetch in 2s' };
return { state: { ...s, confirmed: { ...s.confirmed, count: snap.follower_count } }, action: 'applied' };
}
let s = initial;
const show = (label, extra = '') => console.log(label.padEnd(44), `following=${s.confirmed.following} count=${s.confirmed.count}`, extra);
show('start');
s = onTap(s); show('tap Follow (request sent)');
let r = onSnapshot(s, { viewer_follows: false, follower_count: 41 }); s = r.state; show('stale snapshot arrives mid-request', r.action);
s = onResponse(s, { following: true, follower_count: 42 }); show('POST answers 200 {following:true, count:42}');
r = onSnapshot(s, { viewer_follows: false, follower_count: 41 }); s = r.state; show('replica or CDN snapshot after refresh', r.action);
r = onSnapshot(s, { viewer_follows: true, follower_count: 40 }); s = r.state; show('snapshot agrees on follow, count is 40', r.action);
Run in a node:22 container, it prints (the state shown is the last server-confirmed one; the button already displays the new state after the tap):
start following=false count=41
tap Follow (request sent) following=false count=41
stale snapshot arrives mid-request following=false count=41 ignored: my request is in flight
POST answers 200 {following:true, count:42} following=true count=42
replica or CDN snapshot after refresh following=true count=42 discarded: snapshot disagrees about MY follow state, refetch in 2s
snapshot agrees on follow, count is 40 following=true count=40 applied
A snapshot is ignored while the user's own request is in flight. After the answer arrives, a snapshot that disagrees about the user's own follow state came from before the write (a replica or a cache) and is discarded with a later retry. A snapshot that agrees is newer truth, including a lower count when other people unfollowed.
The fix on the server
- The follow and unfollow responses return
{following, follower_count}read in the same transaction as the write, so the client always has a post-write number. viewer_followsis computed from the edge table on the primary for the signed-in viewer. Mark that responseCache-Control: privateso a shared cache never serves one person's answer to another.- If profile traffic is large enough that you need a shared cache, split the response: a public, cacheable part (name, avatar, counts) and a small private part (
viewer_follows). That costs a second request and is worth it only when the public part is read far more often than it changes. For ordinary traffic one private response is simpler. - Repair (and detect drift, meaning stored counters that have wandered away from the real edge counts) by running the drift query on a schedule and alerting if the same row mismatches on two consecutive runs, since one mismatch may be a write in flight.
When to accept the lag, and when not
| Case | Verdict | Why |
|---|---|---|
| Another user's follower count on a public profile, seconds to minutes late | Accept | nobody can verify it, and it allows caching and cheap batch updates; show abbreviations like 1.2M for large values |
| The viewer's own button state after tapping | Do not accept | the user just acted and can see the contradiction |
| The count immediately after the viewer's own follow | Do not accept | show their own +1 at once and hold it against stale snapshots |
| A counter that stays wrong after the job has run | Do not accept | lag means the value catches up on its own (converges); a value that never catches up is a bug (a non-idempotent write, one that changes the result when repeated, or a code path that never updates the counter), not lag |
| A number used for a decision, such as a follow limit or eligibility | Do not accept | a stale counter could let someone past a limit they have reached or lock out someone who has not; read the edge table, not the derived counter |
Verify
A Playwright test follows, then routes the next profile GET to a stale body (viewer_follows: false, old count) and asserts the button still reads "Following" and the count shows the new value. A database test inserts an edge without moving the counter and asserts the drift query reports the row and the repair clears it. A latency-injection test delays the replica read and asserts the same screen result. Observe: number of drift rows per run, the share of discarded snapshots (a high share means a systematic cache or replica problem), and replica lag.
Compare OFFSET/LIMIT pagination to keyset (seek) pagination for a large result set. Why does OFFSET-based pagination get progressively slower as the offset grows, and what does keyset pagination need (in the data and in the index) to stay fast and to avoid missing or duplicating rows when the underlying data changes between page loads?
Sample Answer
Direct answer. OFFSET/LIMIT gets slower as the offset grows because the database still has to compute and discard every row before the offset, even though it never returns them; keyset pagination instead remembers the last row's sort-key values and asks for "the next rows after that specific point," which an index can satisfy directly regardless of how deep into the result set you are.
Structured elaboration. OFFSET n LIMIT k conceptually still has to produce and count off the first n+k rows in sorted order before returning the last k of them, so a page near the front costs little but a page a million rows in costs roughly as much as scanning a million rows, even though only k of them are returned. Keyset (or "seek") pagination instead carries forward the sort key values of the last row on the previous page and asks for rows strictly after that point in sort order; if there's an index on the sort key, this is a direct index seek to that position regardless of how many pages came before, so page 2 and page 200,000 cost roughly the same.
For correctness under a changing dataset, keyset pagination also needs a sort key (or combination of keys) that's stable and unique, typically the natural sort column plus a tie-breaking unique column like the primary key, so that rows with identical values on the primary sort column still have a well-defined, non-overlapping order across pages, which is what prevents missed or duplicated rows as new data is inserted between page loads.
Worked example. I verified this with a 20-row orders table ordered by (created_at, id). The first page (ORDER BY created_at, id LIMIT 5) returns ids 1 through 5. Rather than an OFFSET 5 LIMIT 5 for the next page, the keyset form carries the last row's key forward:
-- first page
SELECT id, created_at FROM orders ORDER BY created_at, id LIMIT 5;
-- next page: continue strictly after the last row's key
SELECT id, created_at FROM orders
WHERE (created_at, id) > (:last_created_at, :last_id)
ORDER BY created_at, id
LIMIT 5;
With :last_created_at/:last_id set to the fifth row's values, the second query correctly returns ids 6 through 10, continuing exactly where the first page left off, and would do so at the same cost whether it were the 2nd page or the 20,000th.
Trade-offs and pitfalls. Keyset pagination doesn't support jumping directly to an arbitrary page number the way OFFSET does, only "next" and, with a little more work, "previous"; for a UI that genuinely needs "jump to page 500," you either need a hybrid approach or an accepted trade-off that deep arbitrary jumps stay approximate or unsupported. It also requires the sort key to be genuinely stable and unique, or concurrent inserts near the boundary can cause a row to be skipped or repeated.
Complexity
OFFSET/LIMIT costs O(offset + limit) per page, growing linearly with how deep the page is; keyset pagination costs O(log n + limit) per page via an index seek, independent of how deep the page is.
Edge cases
Ties on the primary sort column (multiple rows with the identical created_at, for instance) must be broken by a unique secondary key in both the ORDER BY and the WHERE comparison, or rows can be skipped or duplicated across page boundaries.
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