Mid-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 full stack developer interview process at FAANG companies typically involves 5-7 rounds spanning 4-8 weeks. Mid-level candidates are evaluated on their ability to design and implement complete features across frontend and backend, handle moderately complex system design problems, demonstrate strong problem-solving skills, collaborate effectively across teams, and show clear growth trajectory. Each round builds on previous assessments to evaluate different dimensions: technical depth, system thinking, coding proficiency, and leadership/culture fit.
Interview Rounds
Recruiter Screening Call
What to Expect
Initial 30-minute call with a technical recruiter to assess communication skills, background fit, motivation, and career goals. They'll verify your full stack experience level, interest in the role, and overall alignment with the company. This is also your opportunity to ask questions about the team, tech stack, and interview process.
Tips & Advice
Be concise but personable. Have 2-3 specific projects ready to discuss that demonstrate full-stack ownership. Ask thoughtful questions about the team structure and technical challenges they're working on. Prepare an elevator pitch about your full-stack journey and why you're interested in this specific role. Confirm you're comfortable with the interview timeline and format (remote vs on-site). Recruiters at FAANG often ask about salary expectations early—research market rates beforehand.
Focus Topics
Career Growth and Motivation
Show genuine interest in what the specific team is building and why this role excites you. Be clear about your career goals and how this position aligns with them. Avoid generic answers about the company brand.
Practice Interview
Study Questions
Communication and Interpersonal Skills
Ability to articulate your technical experience clearly to non-technical and technical audiences. Demonstrate enthusiasm and genuine interest in the role and company. Show collaborative mindset and examples of working cross-functionally.
Practice Interview
Study Questions
Full-Stack Project Experience Overview
Be ready to discuss 2-3 significant projects where you owned features end-to-end. Clearly articulate the frontend technologies, backend services, databases, and your specific contributions. Highlight decisions that improved performance, scalability, or user experience.
Practice Interview
Study Questions
Technical Phone Screen - Frontend Focus
What to Expect
First technical assessment focusing on frontend capabilities. A 45-60 minute video call with a frontend-focused engineer where you solve a coding problem involving DOM manipulation, component logic, or state management using JavaScript/TypeScript and a modern framework (React, Angular, Vue, etc.). Expect questions about your approach, trade-offs, and optimization. The problem is typically LeetCode-Medium difficulty with a frontend twist.
Tips & Advice
Start by clarifying requirements and edge cases before diving into code. Think out loud about your approach. Write clean, readable code even in timed settings. Discuss performance implications of your solution. Be ready to handle follow-up questions about state management, re-rendering optimization, or handling async operations. For React specifically, understand hooks, useEffect cleanup, and performance optimization. For other frameworks, know their lifecycle and reactivity patterns. If you get stuck, communicate clearly about what you're thinking and ask clarifying questions. It's better to work through the problem methodically than to rush to a wrong solution.
Focus Topics
Frontend Performance Optimization
Code splitting and lazy loading components, image optimization, bundle size analysis, memoization strategies, avoiding memory leaks, optimizing render performance, understanding Core Web Vitals (LCP, FID, CLS). Tools like DevTools, Lighthouse, and profilers.
Practice Interview
Study Questions
Asynchronous Programming and Data Fetching
Proficiency with promises, async/await, and observables (RxJS). Handling loading states, error states, and caching. Understanding fetch API vs axios. Knowledge of race conditions and how to prevent them. Handling concurrent requests and request cancellation.
Practice Interview
Study Questions
DOM Manipulation and Browser APIs
Proficiency with DOM selection, event handling, and browser APIs. Understanding of event delegation, event bubbling, and capturing. Knowledge of common patterns like lazy loading, intersection observers, and performance-conscious DOM updates.
Practice Interview
Study Questions
React/Angular State Management and Component Patterns
If React: hooks (useState, useContext, useReducer, useCallback, useMemo), component composition patterns, lifting state up, controlled vs uncontrolled components, preventing unnecessary re-renders. If Angular: components, services, dependency injection, RxJS basics, change detection strategies. Understanding when to use context vs external state management (Redux, Zustand, NgRx).
Practice Interview
Study Questions
Modern JavaScript/TypeScript Fundamentals
ES6+ features (arrow functions, destructuring, spread operator, async/await, promises), closures, prototypes, and this binding. TypeScript basics including interfaces, generics, and type narrowing. Understanding of functional vs object-oriented paradigms.
Practice Interview
Study Questions
Technical Phone Screen - Backend Focus
What to Expect
Second technical assessment focusing on backend capabilities. A 45-60 minute call with a backend-focused engineer where you solve a backend-oriented problem involving API design, database queries, or server-side logic. Expect questions about RESTful API design, database queries (SQL or NoSQL), handling concurrency, or building middleware. The problem typically has LeetCode-Medium difficulty but emphasizes backend concepts like scalability and data modeling.
Tips & Advice
Think systematically about scalability from the start. Consider how your solution would perform with millions of requests. Discuss trade-offs between different approaches (relational vs document databases, caching strategies, sync vs async). Write clean code but also articulate your architecture decisions. Be prepared to optimize queries, discuss indexing, and explain why certain patterns help at scale. If working with Node.js/Express, show understanding of middleware order, error handling, and asynchronous flow. For Java/Python backends, discuss async patterns in those languages. Ask clarifying questions about requirements (scale, latency requirements, consistency needs). If you don't know a specific technology, explain how you'd approach learning it.
Focus Topics
Error Handling and Logging
Structured logging practices. Error categorization (client errors vs server errors vs dependency errors). Graceful degradation and fallback strategies. Retry logic and exponential backoff. Circuit breakers for external dependency failures. Monitoring and alerting concepts.
Practice Interview
Study Questions
Authentication, Authorization, and Security
JWT vs session-based authentication. OAuth 2.0 basics. Password hashing and salting. SQL injection and XSS prevention. HTTPS and SSL/TLS basics. Rate limiting and DDoS protection concepts. CORS (Cross-Origin Resource Sharing) configuration. Secure headers. Input validation and sanitization.
Practice Interview
Study Questions
Caching Strategies and Performance
Understanding cache layers (client-side, server-side, CDN, database query caching). Redis/Memcached usage patterns. Cache invalidation strategies (TTL, LRU, cache-aside, write-through, write-behind). When to cache and when not to. Understanding the performance/consistency trade-off. Database connection pooling.
Practice Interview
Study Questions
Database Design and Query Optimization
Normalization vs denormalization trade-offs. Indexing strategies and query optimization. Understanding joins, subqueries, and aggregations in SQL. NoSQL patterns and when to use them. Transaction handling and ACID properties. Sharding and replication concepts. N+1 query problems. Working with ORM tools.
Practice Interview
Study Questions
RESTful API Design and HTTP Fundamentals
Understanding of REST principles: statelessness, resource-based design, proper use of HTTP methods (GET, POST, PUT, DELETE, PATCH). Knowledge of HTTP status codes (200, 201, 204, 400, 401, 403, 404, 500, etc.). API versioning strategies, pagination, filtering, and sorting. Difference between REST and GraphQL. Understanding of content negotiation and response formats.
Practice Interview
Study Questions
Server-Side Asynchronous Programming
For Node.js: event loop, callbacks, promises, async/await, handling blocking operations, streaming. For Java: threading, futures, reactive programming (Project Reactor, RxJava). For Python: asyncio, multiprocessing vs multithreading. Understanding callback hell and how to avoid it. Proficiency with concurrency patterns.
Practice Interview
Study Questions
Technical On-Site/Virtual - Full Stack Integration
What to Expect
A comprehensive 60-90 minute assessment where you design and implement a feature that requires both frontend and backend work. You might design a real-time notification system, a product search interface, or a data visualization feature. The interviewer focuses on how you think holistically about the problem, make technology choices, and understand trade-offs across the stack. You'll implement key parts (not necessarily complete) and be ready to discuss how the full system would work. This round often involves pair programming or live coding with an interviewer.
Tips & Advice
Take time upfront (5-10 minutes) to understand the problem fully. Ask about scale, performance requirements, user base, and timeline. Sketch your architecture before coding. Discuss which technology choices you'd make and why. Show your full-stack thinking: consider the frontend UX implications of your backend design and vice versa. Code one part well rather than sketching everything poorly. Communicate constantly about your decisions. Be prepared to discuss what you'd do differently with more time. If you get stuck on one part, move to another rather than getting blocked. At mid-level, interviewers expect thoughtful decisions, not perfection.
Focus Topics
Testing Strategy and Quality Assurance
Unit testing both frontend and backend components. Integration testing across layers. Mocking external dependencies. Test coverage thinking. End-to-end testing concepts. Manual testing approach. Thinking about edge cases and error scenarios. Debugging strategies.
Practice Interview
Study Questions
Data Flow and State Management Across Layers
Understanding data flow from database through API to frontend. Managing state consistency across frontend and backend. Handling real-time updates and synchronization. Designing schemas that support frontend requirements. API response structures that minimize client-side complexity. Pagination and lazy loading strategies.
Practice Interview
Study Questions
Problem-Solving Under Constraints
Breaking down complex problems into manageable parts. Identifying critical path vs nice-to-haves. Making time-aware decisions about implementation depth. Communicating about constraints clearly. Ability to pivot and discuss alternatives when hitting obstacles. Testing strategy and quality assurance thinking.
Practice Interview
Study Questions
Full-Stack Architecture and Feature Design
Ability to design complete features considering frontend UX, backend API design, database schema, and data flow. Understanding of separation of concerns and communication between layers. API-first design thinking. Discussing trade-offs (e.g., complex queries on backend vs post-processing on frontend). Designing for extensibility and maintainability.
Practice Interview
Study Questions
System Design Round
What to Expect
A 45-60 minute session focused on architectural thinking at scale. You'll be asked to design a medium-scale system (e.g., URL shortening service, real-time messaging system, or an analytics dashboard). At mid-level, you're expected to discuss basic scalability concepts, choose appropriate technologies, and justify your choices. The focus is on your thought process, not getting every detail perfect. You should discuss database choices, caching layers, API design, and how the system scales.
Tips & Advice
Start by clarifying requirements and constraints (scale, latency, consistency needs). Discuss your approach out loud before drawing. Keep the design practical and based on common patterns, not over-engineering. Use a whiteboard or digital drawing tool to sketch architecture. Discuss trade-offs explicitly (SQL vs NoSQL, sync vs async, centralized vs distributed). Be comfortable saying 'I don't know but here's how I'd approach it' rather than making things up. At mid-level, focus on correctness and understanding trade-offs, not handling billions of requests. Be ready to drill down into one component (e.g., database schema, API design, caching strategy) when asked. Practice with system design primers and real-world systems you've built or studied.
Focus Topics
Asynchronous Processing and Job Queues
Message queues and task processing (RabbitMQ, Kafka, SQS). Producer-consumer patterns. When to use async processing vs synchronous APIs. Exactly-once delivery semantics. Handling failures and retries in async systems. Monitoring queue health.
Practice Interview
Study Questions
API Design for Scale
Stateless API design. Rate limiting and quota management. Pagination for large datasets. Filtering and search optimization. API versioning strategies. Backward compatibility. Error handling and retry semantics.
Practice Interview
Study Questions
Caching and Content Delivery
Multi-layer caching (CDN, Redis, query caching, browser caching). Cache invalidation strategies and consistency challenges. When to use each caching layer. Understanding cache hit rates and performance impact. Global vs regional content delivery.
Practice Interview
Study Questions
Database Architecture and Data Modeling
Choosing between relational and NoSQL databases based on requirements. Sharding and replication strategies. Read replicas vs write replicas. Consistency models (strong consistency, eventual consistency). Backup and disaster recovery concepts. Partition tolerance and network failure handling.
Practice Interview
Study Questions
Scalability and Load Distribution
Horizontal vs vertical scaling. Load balancing strategies and algorithms. Understanding bottlenecks in a system. Identifying what needs to scale and why. Stateless vs stateful service design. Connection pooling and resource management.
Practice Interview
Study Questions
Behavioral and Communication Round
What to Expect
A 45-60 minute conversation with a senior engineer or hiring manager focused on your work experience, collaboration style, and problem-solving approach. You'll discuss specific projects, challenges you've overcome, conflicts you've resolved, and how you work with teammates. FAANG companies assess values like customer obsession, ownership, and bias for action alongside technical competence. Expect open-ended questions about your biggest technical achievement, a time you failed, and how you collaborate with frontend/backend teammates when perspectives differ.
Tips & Advice
Use the STAR method (Situation, Task, Action, Result) for behavioral questions. Focus on specific examples with numbers when possible (improved performance by 30%, reduced bug count from 50 to 10, etc.). Show ownership: use 'I' instead of 'we' when discussing your contributions. Discuss impact on users or business, not just technical details. Be honest about failures and what you learned. Show growth mindset: discuss how you've improved and what you'd do differently. When discussing team collaboration, emphasize communication and finding win-win solutions. Prepare 4-5 stories covering different competencies: dealing with ambiguity, owning a project, collaborating across teams, learning something new, and handling failure. Practice telling them concisely (2-3 minutes each).
Focus Topics
Dealing with Ambiguity and Technical Decisions
How you approach problems without clear solutions. Making decisions with incomplete information. Choosing between multiple valid approaches and justifying your choice. Adapting when requirements change. Learning new technologies or domains quickly.
Practice Interview
Study Questions
Learning and Growth Mindset
Examples of technologies or concepts you've learned. How you approach unfamiliar problems. Seeking feedback and acting on it. Reading technical blogs, books, or papers. Continuously improving code quality and skills. Teaching others what you've learned.
Practice Interview
Study Questions
Ownership and Impact
Ability to take ownership of end-to-end features. Taking initiative to solve problems without being asked. Driving projects to completion despite obstacles. Understanding user impact and business metrics. Proactively finding and fixing bugs. Going beyond the basic requirement to deliver excellence.
Practice Interview
Study Questions
Cross-Functional Collaboration
Working effectively with frontend and backend teams despite differing perspectives. Communicating technical decisions to non-technical stakeholders. Receiving and acting on feedback. Supporting and mentoring junior developers. Collaborating with product, design, and QA teams.
Practice Interview
Study Questions
Hiring Manager Round
What to Expect
A 30-45 minute final conversation with the hiring manager for the team where you'd be working. This focuses on role clarity, team dynamics, growth opportunities, and mutual fit. The hiring manager discusses what success looks like in the role, how they support growth, and what projects you'd work on. This is your last chance to ask questions about team culture, tech stack specifics, and work environment. Expect discussion of your long-term career goals and how this role supports them.
Tips & Advice
Ask thoughtful questions about the team's current challenges, tech stack, and how the team is structured. Inquire about what success looks like in the first 3-6 months. Ask about opportunities for growth and mentorship. Discuss your interest in specific technologies or domains the team works with. Be authentic about your strengths and areas for growth. Show genuine interest in the work. This is not a test; it's a conversation to ensure mutual fit. Have 4-5 meaningful questions prepared that show you've done research on the team.
Focus Topics
Growth and Development Opportunities
Understanding how the team supports engineer growth. Opportunities for leadership (leading projects, mentoring), learning new technologies, or expanding skills. How performance is evaluated. Available mentorship and guidance.
Practice Interview
Study Questions
Team Dynamics and Culture Fit
Understanding how the team works together, collaboration patterns, and decision-making processes. Communication style of the team and manager. Work-life balance and flexibility. Diversity and inclusion in the team.
Practice Interview
Study Questions
Role Clarity and Expectations
Understanding the specific responsibilities of the full-stack role on this team. Clarifying whether the role is frontend-heavy, backend-heavy, or truly balanced. Understanding the team's biggest technical challenges. Learning about current projects and roadmap.
Practice Interview
Study Questions
Frequently Asked Full-Stack Developer Interview Questions
Describe the role of assertions and invariants in maintaining code correctness. When should assertions be used versus throwing exceptions? Provide an example where an assertion detects a developer error early and avoids a costly runtime check in production, and describe how this maps to design-by-contract thinking (preconditions, postconditions, invariants).
Sample Answer
Direct answer
An assertion checks a condition that your own code's logic guarantees should always be true if nothing upstream has a bug; an exception handles a condition that the outside world (a user, a file system, a network) can legitimately produce regardless of whether your code is correct. Assertions catch developer errors early and cheaply; exceptions handle the world being unpredictable.
Structured elaboration
What an assertion is for. An assertion encodes an invariant: a statement that, given correct code, must hold at this point in the program no matter what valid input arrives. If it fails, the bug is in the code that led to this point, not in the input or the environment. Because of this, assertions are cheap to reason about (you never need a recovery path for them, the correct response to a failed assertion is to fix the bug) and, in several languages, can be compiled out entirely in optimized production builds, which is precisely why they must never be relied on for something the outside world can trigger.
What an exception is for. An exception handles a condition that is a normal, expected possibility given a correct program: a file that does not exist, a network call that times out, a user who submits invalid input. These require an actual recovery path (retry, a default, informing the user) because they will happen in production no matter how correct the code is.
Preconditions, postconditions, and invariants (design by contract). A precondition is what a function requires to be true of its inputs to behave correctly; a postcondition is what it guarantees to be true of its output if the precondition held; an invariant is a condition that must hold at every observable point in an object's lifetime. Assertions are the natural implementation mechanism for all three inside a single codebase's own internal logic: asserting a precondition at function entry catches a caller who violated the contract due to a bug in their own code, which is different from validating an input that arrived from outside the trust boundary and might be malformed for entirely legitimate reasons.
The line between the two. The test is not "is this input bad", it's "could this input be bad even if every line of my own code is correct". A negative array length passed internally between two functions you wrote and control, where nothing external can produce that value if your code is right, is an assertion case. A negative quantity field parsed from a JSON request body is an exception (or validation-error) case, because a malicious or buggy client can produce it no matter how correct your server code is.
Worked example
A function withdraw(account, amount) internal to a ledger system might assert assert account.balance >= 0, "invariant violated: account balance went negative" right after debiting, because if the debit logic is correct, the balance should never go negative; if this assertion fires, there's a bug in the debit logic itself, and the fix is to find that bug, not to add a check that reacts gracefully to a negative balance in production. Contrast this with the same function's very first line, which must instead RAISE an exception (not assert) if the caller passes a negative amount: a negative withdrawal amount is exactly the kind of thing an upstream caller (a request handler parsing user input) can produce, whether or not the ledger's own internal logic has any bugs at all, so it needs a real, always-active check, and the right response is to reject the request, not to crash a debug build's assertion and silently no-op in production.
Trade-offs and pitfalls
The most costly mistake is using an assertion to validate something a real caller can trigger: because assertions can be disabled in optimized builds in several languages (C's NDEBUG, Python's -O flag), a check that only exists as an assertion can silently vanish in production, meaning the exact case it was meant to guard against reaches production code entirely unchecked. The opposite mistake, wrapping every internal invariant in a full exception with a try/catch elsewhere in the codebase, adds real performance and readability cost for something that, if your own code is correct, should genuinely never happen and does not need a recovery path at all, only a way to fail loudly and immediately during development and testing.
You must size an in-memory cache cluster for a dataset: total data size 200GB, expected working set 20GB, replication factor 2 for high availability, and 20% extra headroom for fragmentation and metadata. Explain how you would calculate node count and per-node memory, consider shard overhead, and account for future growth.
Sample Answer
Direct answer
Size a cache cluster from the actual working set, not the total dataset, then add replication and fragmentation headroom on top; node count and per-node memory come out of that total, not the other way around.
Structured elaboration
- Working set versus total data size: the total dataset (200 GB, gigabytes, in a typical example) is not what needs to fit in cache; the working set (20 GB, the subset actually read repeatedly within a relevant time window) is the real sizing driver, since the whole point of caching is serving the repeatedly-accessed subset, not the entire dataset.
- Replication factor: for high availability, each byte of the working set is stored on more than one node (replication factor 2 doubles the effective memory requirement, since every item exists on a primary and at least one replica).
- Fragmentation and metadata headroom: real-world memory usage is always somewhat higher than the raw data size, due to per-key overhead (metadata, pointers) and memory fragmentation from the allocator; a 20 percent headroom is a reasonable starting estimate, refined with actual measurement once running.
- Calculating node count and per-node memory: total required memory equals working set size times replication factor times (1 plus headroom fraction); node count times per-node memory must exceed that total, with per-node memory chosen based on available instance types and a preference for more, smaller nodes (better fault isolation, smaller blast radius per node loss) versus fewer, larger nodes (simpler operations, less network overhead).
- Accounting for future growth: size with headroom for expected growth over a planning horizon (e.g., 6 to 12 months), not just current working-set size, since scaling a cache cluster up later involves the same resharding/migration considerations covered elsewhere in this topic.
Worked example
Working set 20 GB, replication factor 2, 20 percent headroom: required memory is 20 GB×2×1.2=48 GB. Choosing nodes with 8 GB of usable cache memory each (leaving room for the node's own operational overhead), that requires ⌈48/8⌉=6 nodes. If 6-month growth projections suggest the working set could grow to 30 GB, planning for 30×2×1.2=72 GB, or 9 nodes at the same per-node size, avoids a resharding event shortly after initial rollout.
Trade-offs and pitfalls
Sizing off total dataset size instead of working set drastically overestimates the memory needed for most read-heavy workloads with meaningful access skew (a small fraction of data accounting for most reads); always validate the working-set assumption with real access-pattern data where available, not just an estimate. Under-provisioning headroom for fragmentation and metadata is a common source of "sized correctly on paper, still evicting more than expected in production" surprises; treat the headroom percentage as a starting estimate to refine with real measurement, not a fixed constant to trust blindly.
Explain two frameworks you might use to approach ill-defined engineering problems (for example, OODA loop, hypothesis-driven development, or DMAIC). For each framework, describe when it's most appropriate and one concrete step you would take under that framework when faced with limited data.
Sample Answer
Two frameworks that pull in genuinely different directions, useful precisely because they suit different kinds of ill-defined problems.
Framework 1: the OODA loop. OODA stands for Observe, Orient, Decide, Act, a rapid decision cycle originally developed for fighter pilot combat decisions and since adapted broadly to any fast-moving, uncertain situation. When it's most appropriate: time-critical, fast-changing situations where the cost of waiting for complete information exceeds the cost of acting on an imperfect but quickly-updated picture, such as live incident response or a fast-moving competitive situation. One concrete step under limited data: in the Observe phase, explicitly timebox data gathering to whatever's already available in minutes, not days, and in the Orient phase, write down specifically what's still missing so the next loop iteration targets that exact gap instead of re-observing everything from scratch. Worked example: an SRE, a site reliability engineer, facing a degraded service with no clear root cause observes the 3 dashboards already available (latency, error rate, deploy log) in about 5 minutes, orients on noticing a deploy 10 minutes before the onset, decides the hypothesis is a bad deploy, and acts by rolling it back; if that doesn't resolve it, the next loop starts within 5 minutes, now with that cause ruled out.
Framework 2: DMAIC. DMAIC stands for Define, Measure, Analyze, Improve, Control, a structured five-phase process from Six Sigma, a quality-improvement methodology. When it's most appropriate: longer-horizon, less time-critical problems where a repeatable, documented process matters, particularly recurring quality or consistency issues that other people will need to follow later; it's a poor fit for a genuine emergency, since its ceremony costs real minutes an incident can't spare. One concrete step under limited data: in the Measure phase, explicitly define a proxy metric you can measure right now, flagged clearly as a stand-in for the metric you actually want but don't yet have data for, with a stated plan to validate that proxy once real measurement becomes available, rather than blocking the entire process on getting perfect measurement first. Worked example: a support team wants more consistent ticket resolution across agents but has no existing quality-scoring data. Define: reduce the reopened-ticket rate. Measure: use the reopened-ticket count as an available proxy for resolution quality, even though a full rubric-based quality score would ideally be preferred, baseline 9%. Analyze: bucket reopens by agent tenure and ticket category to find where the problem concentrates. Improve: pilot a checklist for the worst-offending category. Control: track the reopen rate weekly after the pilot to confirm the gain holds.
The trap. Naming a framework without the 'when appropriate' half is the common shortfall: running DMAIC's full five-phase process during a live production incident burns minutes that matter far more than process rigor does in that moment, while running OODA's instinct-driven rapid loop on a multi-month systemic quality problem tends to produce thrashing, a string of quick fixes that don't add up to an actual, durable improvement.
After an endpoint was moved to async Python, the service freezes under load: CPU stays low, yet one slow request seems to stall all the others. How do you find which call is blocking the event loop, and how do you fix it?
Sample Answer
What the symptom means
In asyncio, all coroutines (functions declared with async def, which can pause and resume) share one thread, the event loop, and a coroutine only gives control back at an await (the point where it pauses so others can run). If one coroutine calls something that blocks the thread (a synchronous HTTP or database client, time.sleep, a blocking file or DNS call), nothing else on that loop runs until it returns. Low CPU together with a freeze points at blocking I/O or a lock, not a computation: the thread is parked in the operating system waiting, not working. (A CPU-bound loop would show one core at 100%; that is the other case and the checks below tell the two apart.)
Ordered checks
In a live outage start with checks 1 and 3: the loop-lag probe confirms the diagnosis in seconds and the stack dump names the call; debug mode and the audit are for finding the cause in code and preventing a repeat.
- Measure loop lag. Run a probe task that sleeps 10 ms in a loop and records how late it wakes. On a healthy loop the lag is a few milliseconds; a blocking call shows up as a spike about as long as the call. Export the max and p99 (the value that 99 percent of samples are at or under) as a metric.
- Turn on asyncio debug mode (in staging, or briefly in production; it adds overhead). Per the Python docs, enable it with
PYTHONASYNCIODEBUG=1,python -X dev,asyncio.run(..., debug=True)orloop.set_debug(True). In debug mode asyncio logs any callback or task step that runs longer thanloop.slow_callback_duration(100 ms by default) and names the coroutine. That names the handler, though not always the exact line. - Take a stack dump of the live process with
py-spy dump --pid <pid>(py-spy is an external sampling profiler that reads another process's stack without modifying it; on Linux in a container it needs the ptrace capability, the permission to inspect another process's memory, for example--cap-add=SYS_PTRACE). If the main thread's top frame is in a driver,requests,socketortime.sleepcall beneath anasync def, that is the blocking call.py-spy recordover a window gives a flame graph (a chart in which each bar is a function and its width is the share of samples spent in it, stacked by caller) if the freeze is intermittent. - Separate it from the other suspects. CPU-bound work in a handler: a core at 100% and the stack shows your own function. A slow downstream awaited properly: the loop lag stays low, because the loop is free. A connection pool or lock wait: lag stays low but latency rises; look at pool-wait metrics. An executor or thread pool starved: lag low, but
to_threadcalls queue. - Audit for the usual offenders: synchronous database drivers or ORM (object-relational mapper) calls,
requestsand other sync HTTP clients, synchronous Redis/Mongo clients, blocking DNS lookups,open()on slow disks, largejson.loadsor regex on big inputs,time.sleep,subprocess.run, calling.result()on a future from the loop thread, and third-party libraries that block internally.
A runnable reproduction
import asyncio, logging, os, sys, time
logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")
async def lag_probe(samples, interval=0.01):
"""Ask the loop to wake us every 10 ms; record how late it actually does."""
while True:
t = time.perf_counter()
await asyncio.sleep(interval)
samples.append((time.perf_counter() - t - interval) * 1000)
def blocking_query():
time.sleep(0.3) # stands in for a driver call that blocks the thread
async def handler_bad():
blocking_query() # blocks the loop thread: nothing else runs for 300 ms
async def handler_good():
await asyncio.to_thread(blocking_query) # runs in the default thread pool instead
async def main(handler):
samples = []
probe = asyncio.create_task(lag_probe(samples))
await asyncio.sleep(0.05)
await asyncio.gather(*(handler() for _ in range(3)))
await asyncio.sleep(0.05)
probe.cancel()
samples.sort()
print("%-12s worst loop lag %6.1f ms, median %.1f ms" % (handler.__name__, samples[-1], samples[len(samples)//2]))
if __name__ == "__main__":
which = sys.argv[1]
debug = len(sys.argv) > 2 and sys.argv[2] == "debug"
asyncio.run(main(handler_bad if which == "bad" else handler_good), debug=debug)
Run python blocked_loop.py bad, python blocked_loop.py good and python blocked_loop.py bad debug. Sample run, docker run --rm --cpus=4 on python:3.12-slim (Python 3.12.15), one run on a noisy host:
handler_bad worst loop lag 907.9 ms, median 2.4 ms
handler_good worst loop lag 4.7 ms, median 1.1 ms
WARNING asyncio: Executing <Task finished name='Task-3' coro=<handler_bad() done, defined at /w/blocked_loop.py:15> result=None created at /usr/local/lib/python3.12/asyncio/tasks.py:695> took 0.307 seconds
WARNING asyncio: Executing <Task finished name='Task-4' coro=<handler_bad() done, defined at /w/blocked_loop.py:15> result=None created at /usr/local/lib/python3.12/asyncio/tasks.py:695> took 0.300 seconds
WARNING asyncio: Executing <Task finished name='Task-5' coro=<handler_bad() done, defined at /w/blocked_loop.py:15> result=None created at /usr/local/lib/python3.12/asyncio/tasks.py:695> took 0.301 seconds
handler_bad worst loop lag 900.1 ms, median 0.6 ms
Reading a warning: Executing <Task ... coro=<handler_bad() done, defined at /w/blocked_loop.py:15> ...> took 0.307 seconds names the coroutine (handler_bad), the file and line where it is defined, and how long that one step of it ran without yielding to the loop; each of the three handler tasks produced one, about 300 ms each.
The shape: the median lag is tiny (the loop is idle most of the time), the worst lag is about 900 ms because three 300 ms blocking calls ran back to back on the one thread, and the debug-mode warnings name handler_bad with its duration. With to_thread the loop lag stays in single-digit milliseconds. --cpus=1 gave the same result (worst lag about 895 ms for the blocked version, about 7 ms for the fixed one), because the blocked version is waiting, not computing.
To see the stack of a process stuck this way, this script blocks the loop in a function called blocking_query:
import asyncio, time
def blocking_query():
time.sleep(0.5)
async def handler():
while True:
blocking_query()
await asyncio.sleep(0)
asyncio.run(handler())
Run in the same image with pip install py-spy and --cap-add=SYS_PTRACE, py-spy dump --pid <pid> printed:
Process 12: python serve_blocked.py
Python v3.12.15 (/usr/local/bin/python3.12)
Thread 12 (idle): "MainThread"
blocking_query (serve_blocked.py:4)
handler (serve_blocked.py:8)
_run (asyncio/events.py:88)
_run_once (asyncio/base_events.py:1999)
run_forever (asyncio/base_events.py:645)
run_until_complete (asyncio/base_events.py:678)
run (asyncio/runners.py:118)
run (asyncio/runners.py:195)
<module> (serve_blocked.py:11)
The thread is marked idle (not using CPU), the top frame is the blocking function, and the frames beneath it are the event loop's own machinery: that confirms a blocking call on the loop thread. How to read the frames: each line is function (file:line), newest call first. blocking_query is where the thread is stuck; handler is the coroutine that called it; _run executes one scheduled step of a task; _run_once is a single pass of the event loop, which picks up the ready callbacks and runs them; run_forever, run_until_complete and the two run frames are the start-up path that asyncio.run created. Seeing your own function directly above _run with a blocking call on top is the signature: the loop is inside one callback and cannot start its next pass.
The fixes
- Offload the blocking call:
await asyncio.to_thread(fn, ...)(orrun_in_executorwith a dedicated, bounded executor so slow calls cannot starve the default pool). The default executor holdsmin(32, os.cpu_count() + 4)threads, so concurrency of offloaded waits is capped; and cancelling the awaiting task does not stop the thread. - Use an async client for the hot paths (an async HTTP client, an async database driver). The loop then waits on the socket instead of a thread, and thousands of calls can be in flight.
- Bound concurrency toward the database. Whichever way you go, the connection pool is the ceiling: converting to async raises how many requests try to reach the database at once, so the pool size and a semaphore (a counter that lets at most N coroutines proceed while the rest wait) in front of it decide how many succeed, and the rest should wait cheaply or fail fast.
- Memory and CPU impact of the migration. Coroutines are much cheaper than threads, so memory per in-flight request falls; but all coroutine code still runs on one core, so CPU-heavy steps (large JSON, serialization, templating) now compete with every other request. Run one process per core, and move heavy computation to a process pool or worker.
- Keep it from coming back. Alert on loop lag, run debug mode in tests and staging so a blocking call in a new
async defis logged, and in code review treat any synchronous library call insideasync defas suspect.
Verify
Reproduce with the probe and a load test: before the fix loop lag spikes to the blocking duration under load; after it, lag p99 stays in milliseconds, throughput rises and the p99 request latency stops tracking the slowest call. Check that the offload pool or database pool did not become the new bottleneck (queue time and pool-wait metrics).
You are designing an API for a social feed consumed by both mobile and web clients, and the mobile team keeps complaining the responses are heavy and hard to work with. Walk through how you would shape the API to minimize client complexity, and justify your protocol choice given the mobile bandwidth constraints.
Sample Answer
Direct answer
The mobile team's complaint ("responses are heavy and hard to work with") is really two separate problems: the payload carries fields nobody on that screen needs, and the client has to reshape what it gets before it can render. The fix is to stop shipping one fixed shape to every consumer and let the server compute exactly the fields each client asks for, while keeping the underlying feed data model the same. Given that mobile and web genuinely want different shapes from the same feed and mobile is bandwidth-constrained, GraphQL's field-selection model is the better protocol fit here, as long as it is constrained (persisted, allow-listed queries; depth and cost limits) so no client can accidentally request an expensive, unbounded query.
Structured elaboration
Requirements to design against: less client-side reshaping work, smaller mobile payloads, predictable caching behavior, and one schema that serves both clients without diverging codepaths.
Protocol comparison for this consumer mix:
| Concern | REST (fixed resource shape) | GraphQL (client-selected fields) | gRPC |
|---|---|---|---|
| Matches "mobile wants less, web wants more" | Poor without ad hoc ?fields= params | Native fit, one query per client shape | Poor, schema is fixed per RPC method |
HTTP-level caching (CDN, Cache-Control) | Strong, stable URLs | Weak by default, needs persisted-query IDs to get cacheable URLs back | Not HTTP-cacheable in the browser sense |
| Browser/mobile-web client support | Native | Native (plain HTTP POST/GET) | Needs gRPC-Web plus a proxy translating HTTP/2 trailers, extra moving part for a browser client |
| Risk of one client hurting others | Low, server controls the shape | Real, a deep nested query can be expensive; needs depth/cost limits | Low |
| Payload compactness for text-heavy feed data | Medium (JSON) | Medium (JSON, but only requested fields) | Best (binary), but the win is smaller for a feed that's already mostly short strings and IDs |
Response-shaping principles regardless of protocol:
- Cursor-based pagination (opaque
next_cursortoken) instead of offsets, so the feed stays stable while new posts are inserted. - Embed hot-path fields the card renders unconditionally (author name, avatar URL, like count); reference cold-path data the card doesn't render by default (full bio, high-resolution media, comment thread) via a separate call or a nested field the client only selects when it needs it.
- Serve media as pre-generated size variants (thumbnail/medium/full URLs) rather than one large image URL the client has to resize client-side; this is a bigger bandwidth win for mobile than almost any protocol choice.
Making GraphQL safe for a bandwidth-constrained mobile client:
- Ship the mobile app with a fixed set of persisted queries (each identified by a hash the client sends instead of the query text). The server only executes registered query hashes and rejects anything else with a 400 response; this closes off arbitrary expensive queries and lets a CDN cache responses by persisted-query hash the same way it would cache a REST URL.
- Enforce query depth and complexity limits server-side so a client cannot nest
author.posts.author.posts...into an expensive fan-out. - Keep the REST fallback in mind: a much lower-effort alternative that gets most of the same benefit is REST with a sparse-fieldset query parameter (
?fields=id,text,author.name,author.avatar_url); it is worth naming as the pragmatic choice for a smaller team that isn't ready to run a GraphQL server.
Worked example
Same feed item, shaped two different ways from one underlying schema.
REST, default embedding (what the mobile team is complaining about):
{
"id": "post_9182",
"text": "Shipped the new onboarding flow today",
"created_at": "2026-07-18T14:02:00Z",
"author": {
"id": "u_4471",
"name": "Priya Shah",
"avatar_url": "https://cdn.example.com/avatars/u_4471_full.jpg",
"bio": "Product engineer, ex-Stripe, likes climbing",
"follower_count": 3821,
"following_count": 512
},
"media": [
{ "url": "https://cdn.example.com/media/m_1.jpg", "width": 4032, "height": 3024 }
],
"like_count": 214,
"comment_count": 18,
"geo": { "lat": 37.7749, "lng": -122.4194 }
}
Everything the card actually renders on mobile is five fields; the rest (bio, follower/following counts, full-resolution image, precise geo) is dead weight on that screen.
GraphQL query the mobile client sends for a feed row (persisted, hash-identified in production; shown here as text for clarity):
query MobileFeed($cursor: String) {
feed(cursor: $cursor, limit: 20) {
edges {
node {
id
text
createdAt
likeCount
author { id name avatarThumbUrl }
media { thumbnailUrl }
}
}
pageInfo { endCursor hasNextPage }
}
}
Response for one edge:
{
"id": "post_9182",
"text": "Shipped the new onboarding flow today",
"createdAt": "2026-07-18T14:02:00Z",
"likeCount": 214,
"author": { "id": "u_4471", "name": "Priya Shah", "avatarThumbUrl": "https://cdn.example.com/avatars/u_4471_thumb.jpg" },
"media": [{ "thumbnailUrl": "https://cdn.example.com/media/m_1_thumb.jpg" }]
}
The web client, on the same schema, asks a different query for the same node and legitimately gets bio, counts, and full-resolution media because its screen renders them; no server-side branching by client type, no separate mobile endpoint to maintain.
Trade-offs and pitfalls
- GraphQL's caching story is genuinely worse than REST's out of the box (an arbitrary query has no stable URL); persisted queries recover most of it by giving each allowed shape a stable, cacheable identifier, but that is an extra piece of infrastructure to build and operate, not a free win.
- The classic GraphQL trap is the N+1 resolver problem: naively resolving
authorper feed item issues one database call per post instead of one batched call for all authors in the page. This needs a batching layer (a per-request data loader that collects author IDs across the whole response and issues one query) or the fix does not show up until load testing. - Over-embedding (putting the full author profile in every feed item) reproduces the original complaint under a new protocol; under-embedding forces one extra round trip per screen, which is worse than a slightly larger response on a high-latency mobile network. The embed-vs-reference line should be drawn by "does this screen render it unconditionally," not by what's convenient to fetch.
- A REST sparse-fieldset compromise is a legitimate answer for a team not ready to operate a GraphQL server; naming it as the deliberately-rejected alternative (and why the full field-selection model wins here specifically because mobile and web diverge so much) is what separates a considered answer from a technology-preference answer.
Explain the common cache-invalidation strategies: TTL, explicit invalidation, versioning with ETags, and write-through invalidation. For a product-pricing service where a price change must be visible to users within 5 seconds, which strategies would you choose, and how would you combine them?
Sample Answer
Direct answer
Time-to-live (TTL) expiry, explicit invalidation, versioning with entity tags (ETags), and write-through invalidation each guarantee freshness differently: TTL is a passive timer, explicit invalidation is an active push the moment data changes, ETag versioning lets clients cheaply confirm whether their copy is still valid, and write-through invalidation updates the cache synchronously as part of the write itself. For a product-pricing service that must show a price change within 5 seconds, the answer is to combine write-through updates for immediacy with a short TTL as a safety net, since relying on either alone leaves a gap: write-through alone has no fallback if an update is missed, and TTL alone cannot guarantee anything faster than the TTL window itself.
Structured elaboration
The four base strategies
- TTL: each cache entry is set to expire automatically after a fixed duration. Simple and requires no coordination, but guarantees only "stale for at most the TTL," never immediate freshness.
- Explicit invalidation: the service that changed the data actively removes or refreshes the specific cache key, typically by publishing an event over a message bus (a publish/subscribe, or pub/sub, mechanism) that every cache node or API server subscribes to, so all of them invalidate or refresh in step rather than each polling independently.
- Versioning with ETags: each response carries a version identifier; clients make conditional requests (
If-None-Match) and the server replies with a cheap "not modified" if the version is unchanged, or the full payload if it changed. This mainly saves bandwidth and lets the client self-verify freshness; it does not by itself push updates to anyone. - Write-through invalidation: on a write, the write path updates both the durable store and the cache atomically (or updates the store then immediately overwrites the cache entry) as part of the same operation, so the very next read already sees the new value with no propagation delay.
Coordination mechanics that make these strategies work at scale
- Pub/sub invalidation and race conditions: broadcasting an invalidation event over pub/sub is what lets many cache nodes and services stay in sync without polling each other, but it introduces a race condition risk: if the event is published before the underlying write is fully durable, or delivered out of order relative to a second write on the same key or a deployment that changes read logic, a subscriber can refresh into a value that is itself about to be overturned. Guard against this by publishing the invalidation only after the write is confirmed durable, and by making invalidation handlers idempotent so a duplicate or out-of-order event cannot leave the cache worse off than doing nothing.
- Soft-expiry (stale-while-revalidate) and cache tagging: rather than a hard TTL that forces every expiring request to wait on a fresh fetch, soft expiry serves the stale value immediately while triggering a background refresh, keeping latency low during the refresh window. Cache tagging (grouping many cache entries under a shared tag) lets one invalidation event clear every entry derived from a changed piece of data, without the writer needing to know every individual cache key that resulted from it.
- Key-prefix versioning across services sharing a distributed cache: when multiple services share one distributed cache, a global key-prefix version (bump a shared prefix like
v42:to instantly make every key under the old prefix unreachable) gives a cheap way to invalidate an entire class of entries at once, without deleting them individually and without every service needing to agree on invalidation timing key-by-key. The cost is that it invalidates in bulk, which is a blunt instrument if only a subset of that prefix actually changed. - Soft-delete-plus-revalidation: instead of removing a cache entry outright on a write, mark it stale and let the next read trigger revalidation against the source of truth. This suits high-read workloads well, since it avoids a thundering-herd of readers all missing the cache at once after a hard delete; it suits high-write workloads less well, since a key being marked stale repeatedly under heavy writes gains little over a plain short TTL and adds bookkeeping for no benefit.
Choosing for the 5-second product-pricing requirement
- Primary mechanism: write-through update. When a price changes, the write path updates the database and updates (or invalidates) the cache entry as part of the same operation, so the instance that handled the write serves the new price immediately, with zero propagation delay for that instance.
- Fan-out: explicit pub/sub invalidation. The price-change write also publishes an invalidation event so every other cache node and API server, not just the one that handled the write, drops or refreshes its copy without waiting for a TTL to expire.
- Safety net: a short TTL, strictly shorter than the 5-second requirement, so that if an invalidation event is ever missed (a subscriber was briefly disconnected, a message was dropped), the entry expires and is refetched well within the service-level agreement (SLA) regardless. A TTL near 3 seconds gives roughly 2 seconds of margin against the 5-second requirement while still keeping the cache hit rate high between price changes, which are relatively infrequent events.
- Client efficiency: ETags on top. Returning a version or ETag lets clients avoid re-downloading a price that has not changed, cutting bandwidth without weakening the freshness guarantee established by steps 1-3.
This mirrors the same trade-off shape as a high-write inventory system needing near-real-time correctness: write-through plus pub/sub invalidation carries the freshness guarantee, and TTL is there purely as the fallback for the failure case, not as the primary mechanism, because TTL alone cannot promise "within 5 seconds" without being set so short it defeats the purpose of caching in the first place.
HTTP-level mechanics for a semi-dynamic JSON API
The same ideas map onto standard HTTP headers when the pricing data is exposed through a semi-dynamic JSON API: Cache-Control and Surrogate-Control set the client-facing and edge-facing TTLs respectively (the edge can be allowed to cache slightly differently than the browser), Vary ensures responses that differ by request header are not cross-served, ETag enables the conditional-request savings described above, and stale-while-revalidate plus stale-if-error let the edge serve a slightly-stale price during a background refresh or during a brief origin outage rather than failing the request outright. These headers implement the same combination described above (short TTL as the backstop, revalidation as the mechanism that keeps it cheap) at the HTTP caching layer specifically.
Worked example
A price update for one SKU (stock-keeping unit, a unique product identifier) fires at time zero. The write-through update makes the originating instance's cache correct instantly. The pub/sub invalidation event reaches the other 9 API instances within roughly 200 ms under normal message-bus latency, well inside the 5-second budget. If one instance's subscriber connection had silently dropped an hour earlier (the failure case the safety net exists for), that instance would still be serving the old price from cache, until its 3-second TTL on that entry expires and the next read refetches the current price, landing at worst 3 seconds after the change, still inside the 5-second requirement.
Trade-offs & pitfalls
- Relying on TTL alone for a tight freshness requirement forces the TTL down to where it defeats caching's purpose (a 1-second TTL on a hot key approaches the request rate itself); combining it with an active-invalidation mechanism is what lets the TTL stay a safety net instead of the primary lever.
- Pub/sub invalidation requires reliable, idempotent delivery; treating it as guaranteed-delivery without a fallback (the TTL backstop above) is the single most common way "instant" cache invalidation quietly breaks under a dropped connection or a deploy.
- Key-prefix versioning is a fast, coarse bulk-invalidation tool, not a substitute for targeted invalidation; using it for every single-key change wastes cache warmth across unrelated keys under the same prefix.
- Soft-delete-plus-revalidation and hard TTL expiry solve similar problems differently depending on read/write ratio; picking soft-delete for a write-heavy key just adds bookkeeping overhead without the thundering-herd benefit it was designed for, since a write-heavy key rarely stays warm long enough for that benefit to matter.
You are reviewing a pull request that replaces every var in a legacy module with let or const. Explain what changes in how those variables are scoped and what bugs this could fix or introduce, and how you decide between let and const.
Sample Answer
Direct answer
var is scoped to the whole enclosing function, while let and const are scoped to the nearest pair of braces (a block: an if, a loop body, a try, a bare {}). Swapping them therefore shrinks the region where each name exists, which fixes accidental leaks and shared-variable bugs, and can break code that quietly relied on the old reach. For the choice between the two new keywords: default to const and use let only for a name that is reassigned.
What changes in scoping
| Behaviour | var | let / const |
|---|---|---|
| Scope | Function (or the whole file at top level) | Block |
| Read before the declaration line | undefined (the name is created and set to undefined when the function starts, called hoisting) | ReferenceError (the name exists but is in the temporal dead zone, "TDZ", until the declaration runs) |
| Declare the same name twice in one scope | Allowed | SyntaxError, reported when the file is parsed |
| Fresh copy per loop iteration | No, one variable for the whole loop | Yes, when declared in a for (let ...) header |
| Top-level of a classic browser script | Becomes a property of globalThis (the global object: window in a browser) | Does not (MDN, let) |
Run in node:22, this module shows the differences that matter most in a review:
function demoVar() {
if (true) {
var leaked = "visible after the block";
let contained = "block only";
}
console.log(leaked);
console.log(typeof contained);
}
demoVar();
var callbacks = [];
for (var i = 0; i < 3; i++) callbacks.push(() => i);
console.log(callbacks.map((f) => f()));
const fns = [];
for (let j = 0; j < 3; j++) fns.push(() => j);
console.log(fns.map((f) => f()));
const cfg = { retries: 1 };
cfg.retries = 2;
console.log(cfg);
try {
// eval compiles and runs a string as code at run time; it is used here only so a parse-time error
// can be caught and printed instead of stopping the whole file.
eval("const n = 1; n = 2;");
} catch (e) {
console.log(e.name + ": " + e.message);
}
try {
eval("let dup = 1; let dup = 2;");
} catch (e) {
console.log(e.name + ": " + e.message);
}
function before() {
total = 5; // assignment before the declaration line
var total;
return total;
}
console.log(before());
function viaLet() {
try {
total = 5;
let total;
return total;
} catch (e) {
return e.name + ": " + e.message;
}
}
console.log(viaLet());
It prints:
visible after the block
undefined
[ 3, 3, 3 ]
[ 0, 1, 2 ]
{ retries: 2 }
TypeError: Assignment to constant variable.
SyntaxError: Identifier 'dup' has already been declared
5
ReferenceError: Cannot access 'total' before initialization
Reading the output top to bottom: the var inside the if is still readable after the block, while typeof contained is "undefined" because the let never existed outside its braces. The three callbacks created in the var loop all see the one shared i, which is 3 once the loop ends, while the let loop gives each callback its own i. Assigning to a const throws TypeError, a duplicate let is a SyntaxError (caught here only because eval parses the string at run time; in a real file it stops the whole module from loading). The last two lines contrast var, which yields 5 when assigned before its declaration line, with let, which throws.
Bugs the change can fix
- Leaks out of blocks. In a Node service a
vardeclared inside anifortrystays visible to the rest of the function, so a later line can read a stale or half-set value without any error. Withletthe stray read fails loudly at the line that is wrong. - Shared loop variable in callbacks. Timers, event handlers and promise callbacks created in a
varloop all see the final index (the[3, 3, 3]line). - Accidental redeclaration. Two
var totallines in a long legacy function silently merge into one variable. After the change the parser rejects the second. - Reads before initialisation become errors rather than
undefinedflowing into later arithmetic.
Bugs the change can introduce
- Code that relied on the leak. A pattern such as
try { var parsed = JSON.parse(text) } catch (e) {}followed byuse(parsed)breaks, becauseparsednow lives only inside thetrybraces. Fix by declaringlet parsedabove thetry. - Code that relied on hoisting to
undefined. A function that reads a variable before the line that sets it (for example a helper called at the top of the file that uses a variable defined lower down) now throws at that moment. conston something that is later reassigned. The error appears only when the reassigning line runs, so an untested branch can ship broken.- Parse failures. One duplicate declaration makes the whole file fail to load rather than one function misbehave.
- Closures that depended on sharing. A rare loop that intentionally shared one variable across iterations behaves differently once every iteration gets its own copy.
A mechanical find-and-replace is therefore not a safe review strategy. Turn on the lint rules no-var, prefer-const and no-use-before-define, run the test suite, and read each diff hunk that moves a declaration or sits inside a loop, a try or an if.
Choosing between let and const
const means the name cannot be rebound (assigned a different value). It does not make the value immutable, so a const object or array can still be changed in place, as cfg.retries = 2 above shows. Use Object.freeze when you also want a shallow guard against mutation (it blocks changes to the object's own properties, but not to objects nested inside it).
- Default to
constfor every binding, including functions, configuration objects and arrays you only push into. - Switch to
letonly when the name must point to a different value later (a counter, an accumulator, a value set in atry/catch). - In
forloops usefor (const x of items)when you only read each element. A classicfor (let i = 0; ...; i++)needsletbecausei++rebinds. - If you reach for
letjust to build a value in steps, consider extracting a small function that returns the final value so it can beconst.
The benefit is readability: when a reviewer sees const, they know the name never changes, and let becomes a signal that a reassignment is somewhere below.
Running the code
docker run --rm -v "$PWD":/w -w /w node:22 node scope_review.mjs
Save the listing above as scope_review.mjs (Node 22, ES module, no install step).
A gaming leaderboard requires frequent writes (position updates) and low-latency reads. If you naively cache leaderboard snapshots, writes can be lost or stale. Propose a caching and architecture strategy that preserves accuracy and performance. Consider batch updates, write-through vs write-behind, sorted-set data structures, and eventual consistency tolerance for user-facing pages.
Sample Answer
Framing
A gaming leaderboard has a write pattern that fights a naive cache: position updates happen constantly (every match, every score event), but a plain "cache the computed top-N snapshot, refresh on a timer" design either serves a stale snapshot between refreshes or, if you try to invalidate and recompute on every single write, ends up recomputing a full sort on every score update, which doesn't scale.
The core fix: use a data structure the cache is naturally correct for, not a cached derived snapshot
Instead of caching "the answer" (a pre-sorted top-N list) and trying to keep that derived answer fresh under constant writes, store the leaderboard itself in a data structure that's already efficiently sorted and directly queryable, so there's no separate "cache" to go stale relative to a "source of truth" at all for the hot read path. Redis's sorted set (ZSET) is built for exactly this: it maintains members ordered by score with O(log n) insert/update and O(log n + m) range queries (getting the top N, or a user's rank), backed by a skip list internally. A score update is ZADD or ZINCRBY, an O(log n) operation, not a full re-sort. Reading the top 100 is ZREVRANGE 0 99, also O(log n + m). This sidesteps the write-loses-to-stale-cache problem structurally: there's no separate cached copy to reconcile, the sorted set is always current.
Batching writes
Even at O(log n) per update, a wildly popular game can generate more score-update events per second than you want to apply as individual round trips to the leaderboard store. Batch:
- Buffer score deltas in the application tier for a short window (tens to low hundreds of milliseconds) or a small count threshold, then apply them as a single pipelined batch of
ZINCRBYcalls (Redis pipelining avoids the per-command round-trip cost while still applying each update correctly and atomically at the data-structure level). - For a single player who scores multiple times in the buffering window, coalesce into one net delta before applying, cutting the number of writes further without losing correctness (the sorted set doesn't need to see every intermediate value, only the final one, since nothing reads intermediate states).
Write-through vs write-behind for the source of truth
The sorted set is fast but typically not the durable system of record; a Redis restart or eviction shouldn't be able to silently lose a player's score.
- Write-through: apply the update to the durable store (a database) and the sorted set together, before acknowledging the write. Safer (no window where the sorted set has data the database doesn't), but every score event pays the database's latency.
- Write-behind: apply to the sorted set immediately (fast, what players see right away), and asynchronously flush to the durable store in the background (batched, same coalescing idea as above). Faster for the hot path, but introduces a small window where a crash could lose the not-yet-flushed writes.
For a leaderboard specifically, write-behind is usually the right call: losing a few seconds of granular score events in a crash (recoverable from the game's own authoritative match-result log, which is the actual system of record for "what happened," not the leaderboard) is a much smaller problem than adding database latency to every score update, and the leaderboard's job is to be a fast, eventually-durable read-optimized VIEW of the score history, not the durable record itself.
Eventual consistency tolerance
Decide, explicitly, how stale the user-facing leaderboard is allowed to be:
- The player's OWN score/rank after their own action should update immediately (or feel like it) in their client, this is what they just did and they're watching for it; apply their own update synchronously to the sorted set even under a write-behind design for everyone else's aggregate view.
- The GLOBAL top-100 view shown to all players can tolerate a bounded staleness window (seconds), especially if it's additionally cached at the API/CDN layer for read scaling, since a global top-100 list changing by one position a few seconds late is not something most players will notice or care about, unlike their own score being wrong.
Worked example
A game generates 50,000 score events per second at peak. Buffered and coalesced in 100ms windows, that's roughly 5,000 net ZINCRBY operations per 100ms window applied via a pipeline, well within a single Redis instance's throughput, versus 50,000 individual round trips per second if unbatched. The durable database receives the same coalesced batches asynchronously. The API layer caches the top-100 response for 2 seconds (safe, since the global view already tolerates seconds of staleness), while a player's own score endpoint bypasses that cache and reads their entry directly from the sorted set for an immediate, accurate view of their own result.
Trade-offs
Sorted sets solve the "stale cached snapshot" problem structurally, but they're an in-memory structure sized to the number of tracked entries (a full-season leaderboard with millions of players needs the sorted set's memory footprint budgeted for, or the leaderboard scoped to a rolling window, like weekly, rather than all-time, to bound its size). Write-behind trades a small durability window for much lower write latency, which is the right trade specifically because the leaderboard is a read-optimized view, not the authoritative record of what happened in the game.
You need a global leaderboard for an online game with tens of millions of players: near-real-time top-100 per region and a global top-100. Walk through your first-pass architecture and justify each major piece, including how you'd stop a handful of top players updating constantly from overwhelming the system.
Sample Answer
Direct answer
A global leaderboard for tens of millions of players needs three layers: a rate-limited ingest path that bounds how fast any single player's updates can enter the system, a per-region top-N structure that absorbs most of the update volume locally, and a periodic global merge that combines regional top-N lists into the global top-100. The handful of top players updating constantly is contained by capping their update rate at ingest, not by trying to process every update they generate.
Structured elaboration
Each piece exists to solve a specific problem:
Rate limiting at ingest. A per-player token-bucket cap (for example, a fixed number of accepted score updates per second per player) exists because a small number of hyperactive top players can otherwise generate a disproportionate share of total write volume; bounding it there protects everything downstream regardless of how aggressively any one player updates.
Regional top-N structures. Each region maintains its own bounded top-N set (slightly larger than 100, to keep merges accurate) in a fast in-memory structure, updated only when an incoming score would actually change that region's top-N; this keeps per-region write volume bounded by the number of players who could plausibly be in the top-N, not by total player count or total update volume.
Global merge. A periodic (sub-few-second) job reads each region's top-N snapshot and merges them into the global top-100, published to a cache the serving layer reads from. This decouples the strict local consistency of a region's own leaderboard from the necessarily looser consistency of the global view, which only needs to be accurate to within the merge interval.
flowchart LR
A[Game clients] --> B[Ingest API]
B --> C[Rate limiter: per-player token bucket]
C --> D[Stream log]
D --> E[Regional aggregator: top-N sorted set]
E --> F[Global merge service]
F --> G[Read cache]
G --> H[Regional and global top-100 API]
E --> I[(Cold store)]
Worked example
Assume, as illustrative pinned inputs, 50 million total players with 5% concurrently active and submitting a score update on average once every 10 seconds:
concurrent=50,000,000×0.05=2,500,000 players
avg update rate=10s2,500,000=250,000 updates/s
That 250,000 updates/s average is the volume the regional aggregation tier as a whole absorbs, but the reason a handful of top players don't overwhelm any single shard is the per-player cap applied at ingest. If the top 100 players were all capped at 10 updates/s each:
bounded hot-shard worst case=100 top players×10 updates/s (token-bucket cap)=1,000 updates/s
Even in the worst case where every top player updates at the maximum allowed rate simultaneously, that's only 1,000 updates/s concentrated on the shard (one partition of the data spread across multiple servers, each holding a slice of the total) holding the current top-N, roughly 0.4% of total system update volume, which is exactly the point of capping at ingest rather than trying to absorb an unbounded rate from a handful of accounts.
Trade-offs & pitfalls
- Without the per-player rate cap, a handful of hyperactive top players can dominate write volume on the specific shard holding the top-N, since by definition they're the ones near the top; the cap is what keeps that from becoming a hot-key problem (one specific record, here the top-N list, getting a disproportionate share of traffic and overloading the single shard that holds it, even though the system overall has plenty of spare capacity elsewhere).
- The global merge is only as fresh as its merge interval; a design that promises true real-time global ranking is overpromising unless it accepts a correspondingly higher merge frequency and cost.
- Keeping each region's top-N slightly larger than the 100 actually served (for example, 200) protects merge accuracy against players near the boundary between regions' top lists, at a small extra memory cost.
- A common shallow answer proposes exact global ranking with no rate limiting and no batching, which looks correct on a diagram but doesn't survive a handful of players updating every fraction of a second; naming the rate-limiting mechanism explicitly is the senior signal here.
Tell me about a time you worked with a cross-functional team. What was your role, and what made the collaboration succeed or struggle?
Sample Answer
Direct answer
Pick a project that genuinely needed more than one function, and be specific about two things: what YOU owned (not what 'the team' did), and the one concrete mechanism that determined whether the collaboration worked, such as a shared definition of done, a clear handoff point, or clarity on who decided what when opinions differed. Vague answers ('we communicated well') sound rehearsed; specific answers sound lived-in.
What the story needs to show
Your specific contribution. Interviewers are listening for what you personally decided or built, distinct from what your collaborators did. If every sentence is 'we', the interviewer cannot tell what you'd do differently on the next team.
A mechanism-level explanation. Organize the story around one of three lenses:
- Shared goal: did every function agree on what 'done' looked like and how success would be measured, or was each function quietly optimizing for its own definition?
- Interface or handoff: was there a clear point where work crossed from one function to another, and was that point actually defined, or did people guess?
- Decision rights: when functions disagreed, was it clear whose call it was, or did disagreement just stall until someone got tired of arguing?
Honesty if it's a struggle story. The question explicitly allows 'succeed or struggle'. A good struggle story ends on what you changed about the collaboration, not on who was at fault.
Worked example
Situation: [your team] needed to deliver [a feature or initiative] that required real work from [Team A, for example a design or research function] and [Team B, for example a data or infra function], against a fixed external date.
Task: your role was the one connecting the three groups, for example owning the shape of the interface between design and engineering, or owning how data requirements got translated into a schema.
Action: early on, each function had a different idea of what 'done' meant for their piece, which caused rework when the pieces met. You wrote a short one-page agreement naming the shared definition of done and who would sign off on each handoff, and used it to resolve the next two disagreements without a meeting.
Result: the project shipped on the revised date, and the agreement itself became something the group reused on the next cross-functional piece of work, which is the real marker of a story about redesigning the collaboration rather than just pushing through it.
To make that skeleton concrete rather than a fill-in-the-blank: picture a checkout redesign that needed real work from the design function and the payments engineering function, against a fixed external date tied to a promotional campaign launch. The specific disagreement was about what 'done' meant for the new payment-method selector: design considered the screen done once every state (loading, error, empty) matched the approved mockups pixel-for-pixel, while payments engineering considered it done once the integration correctly handled every payment-provider response code, even ones with no mockup drawn yet. That mismatch caused two rounds of rework when a payment-provider error state shipped without a design pass. The one-page agreement that resolved it included this line: 'A screen is done when it matches an approved mockup for every state the payments API can return, and any new state discovered after mockups are drawn triggers a joint 15-minute review before either side builds it.' That single sentence is what let the two functions stop re-litigating 'done' every time a new edge case appeared, and both sides signed off on it before the next round of work began.
Trade-offs and pitfalls
- A generic 'we all communicated well' answer with no mechanism is the single most common weak version of this story, avoid it.
- Over-crediting the team at the expense of your own specific contribution leaves the interviewer unable to evaluate you.
- If you pick a struggle story, resist framing it as the other function's fault. The senior version of this answer explains what you changed about how the groups worked together, not who dropped the ball.
- The strongest answers show you redesigning a structure (a handoff, a shared definition, a decision rule), not just working harder inside a broken one.
Recommended Additional Resources
- LeetCode (focus on Medium problems, particularly in Arrays, Strings, Trees, Graphs, Dynamic Programming categories)
- System Design Primer (GitHub: https://github.com/donnemartin/system-design-primer) - Study scalability concepts, load balancing, caching
- Cracking the Coding Interview by Gayle Laakmann McDowell - Excellent for understanding coding interview patterns
- Designing Data-Intensive Applications by Martin Kleppmann - Deep dive into distributed systems concepts
- React/Angular/Vue official documentation - Depending on your primary framework
- Node.js/Backend framework documentation (Express, Spring, Django depending on language)
- Frontend Masters courses on system design and performance optimization
- FAANG company engineering blogs (Google Engineering Blog, Netflix Tech Blog, Meta Engineering) for architectural insights
- Leetcode System Design section - Study medium-level system design problems
- Mock interview platforms like Pramp or Interviewing.io for practice with real engineers
- GitHub: Awesome Full Stack - Curated list of full-stack resources and libraries
- CSS-Tricks and JavaScript.info - Deep dives into frontend fundamentals
- InterviewCake - Well-explained coding problems with similar patterns
- High Scalability blog - Real-world system architecture case studies
Search Results
Top 24 Full Stack Developer Interview Questions & Answers
In this article, we will cover a complete list of Full Stack Developer interview questions and provide detailed answers to help you ace your interviews.
Full Stack Developer Interview Questions and Answers
Ace your Full Stack Developer interview! Get essential questions and answers covering frontend, backend, and DevOps. Prep and succeed!
Top 70 Coding Interview Questions and Answers for 2026
Prepare for your next coding interview with these top 70 coding interview questions and expert answers. Covering data structures, algorithms, and more.
170 UI Developer Interview Questions for Experienced Candidates
UI developer coding interview questions include topics like algorithms, data structures, and large-scale distributed systems.
30+ Software Engineer Interview Questions: What to Expect & How ...
Common Software Engineer Interview Questions ; Experiential · Explain to me your toughest project and the working architecture. What have you built? ; Hypothetical.
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