Experienced

Software Engineer | 443 questions | 2026

Software Engineer interview questions for experienced

Questions for candidates with 2 to 5 years of experience, by topic. Tap a question to see the model answer.

Python

ExperiencedMost asked
Answer

What is the GIL and how does it affect multithreading in Python?

The Global Interpreter Lock is a lock in CPython. It lets only one thread run Python bytecode at a time. It protects CPython's internal state, such as reference counts, from race conditions.

Effects:

  • CPU-bound Python code gains no speed from threads, since they take turns on one core.
  • I/O-bound code still benefits, because a thread releases the GIL while waiting on sockets, files or time.sleep.
  • Many C extensions (NumPy, hashing, compression) release the GIL during heavy work.
  • Race conditions on your own data are still possible. You still need locks for steps like counter += 1.

Ways around it: multiprocessing or concurrent.futures.ProcessPoolExecutor for CPU-bound work, asyncio or threads for I/O, native extensions. Python 3.13 added an experimental free-threaded build (PEP 703) where the GIL can be turned off. The default build still has it.

What they are checking: Accurate detail: I/O threads work, CPU threads do not, and the GIL is not a substitute for locks

ExperiencedMost asked
Answer

Explain threading vs multiprocessing vs asyncio. When would you use each?

All three give concurrency but with different models.

threadingmultiprocessingasyncio
UnitOS threads, one processSeparate processesCoroutines on one thread
GIL limitYesNo, each process has its ownSingle thread anyway
MemorySharedSeparate (needs pickling or shared memory)Shared
OverheadMediumHighVery low
Best forBlocking I/O with libraries that are not asyncCPU-bound workThousands of concurrent network connections
  • Threading: preemptive switching, so races are possible and locks are needed.
  • Multiprocessing: real parallelism across cores, but data moves through IPC and startup costs more.
  • Asyncio: cooperative; tasks switch only at await, so a blocking call (like requests.get) freezes everything. Use async libraries or asyncio.to_thread.

Rule of thumb: For CPU-bound work use processes. For many network calls use asyncio. For a few blocking calls in old code use a thread pool.

What they are checking: Ability to map a workload to the right concurrency model and know the failure modes

ExperiencedMost askedFree with sign-in
Answer

Explain async and await in Python. What is an event loop?

async def defines a coroutine. await pauses it until another awaitable finishes. Meanwhile the event loop runs other tasks. The event loop is the scheduler: it runs on a single thread and switches between coroutines at await points.

ExperiencedMost askedScenarioFree with sign-in
Answer

A Python function is too slow in production. How do you find and fix the bottleneck?

Measure first, then optimise the part that matters.

ExperiencedMost askedScenarioFree with sign-in
Answer

You need to call 100 external APIs and combine the results. How would you do it efficiently?

This is I/O-bound. Run the calls at the same time with asyncio (or a thread pool if the client library is blocking). Also limit how many run at once.

ExperiencedMost askedFree with sign-in
Answer

How does a Python dictionary work internally?

A dict is a hash table. For each key, Python computes hash(key) and uses it to pick a slot in an index array. It handles collisions by probing for another free slot. Then it stores the key and value.

ExperiencedMost askedFree with sign-in
Answer

How does memory management and garbage collection work in Python?

CPython manages memory automatically with reference counting plus a cyclic garbage collector.

ExperiencedMost askedFree with sign-in
Answer

What is a context manager and how does the `with` statement work?

A context manager defines setup and cleanup around a block. with calls __enter__ on entry and always calls __exit__ on exit, even after an exception. So resources are released reliably.

ExperiencedMost askedFree with sign-in
Answer

What are type hints in Python? Are they enforced at runtime?

Type hints are annotations that declare the expected types of variables, parameters and return values. They are not enforced by the interpreter at runtime. They exist for static checkers (mypy, pyright), IDEs and documentation.

ExperiencedMost askedFree with sign-in
Answer

What is a dataclass in Python and why use it?

@dataclass (module dataclasses, since 3.7) writes repeated methods for you in classes that mainly hold data: __init__, __repr__, __eq__, and optionally ordering and hashing.

ExperiencedMost askedFree with sign-in
Answer

What does this print? `funcs = [lambda: i for i in range(3)]; print([f() for f in funcs])`

It prints [2, 2, 2], not [0, 1, 2]. Closures capture the variable i, not its value at creation time (late binding). By the time the lambdas are called, the loop has finished and i is 2.

ExperiencedMost askedFree with sign-in
Answer

Explain Method Resolution Order (MRO) and multiple inheritance in Python.

MRO is the order in which Python searches base classes for an attribute or method. It uses the C3 algorithm. Each class comes before its parents, and the order of the bases you list is kept.

ExperiencedMost askedFree with sign-in
Answer

How do you write a decorator that takes arguments?

You need three nested layers: an outer function that takes the decorator's arguments, and a decorator that takes the function. The third layer is a wrapper that runs on each call.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you process a 20 GB log file in Python without running out of memory?

Stream it instead of loading it. File objects are lazy iterators over lines, so memory stays flat.

ExperiencedMost askedScenarioFree with sign-in
Answer

A long-running Python service keeps growing in memory. How do you investigate a memory leak?

Confirm it is a leak (memory rising steadily and never plateauing), then find what holds references.

  • Take snapshots with tracemalloc and compare them to see which lines allocate the growing objects:
ExperiencedMost askedScenarioFree with sign-in
Answer

You must process 10 million records that need heavy CPU computation. How do you speed it up in Python?

CPU-bound work is limited by the GIL, so use processes or vectorisation, not threads.

  • First check if the work can be vectorised with NumPy or pandas. This moves loops into C and is often 10 to 100 times faster.
  • Otherwise split the data into chunks and use ProcessPoolExecutor:
ExperiencedMost askedScenarioFree with sign-in
Answer

Two projects on the same machine need different versions of the same library. How do you manage dependencies so they do not conflict?

Give each project its own virtual environment and pin its dependencies.

ExperiencedMost askedFree with sign-in
Answer

What is memoization and how does `functools.lru_cache` work?

Memoization saves the result of a function for given arguments. Repeated calls return the saved value instead of recomputing. functools.lru_cache does this with a bounded Least Recently Used cache.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you write a retry decorator with exponential backoff for unreliable network calls?

Wrap the call in a loop. Catch only errors worth retrying, wait longer each time, add jitter (a small random delay), and give up after a limit.

ExperiencedMost askedFree with sign-in
Answer

How do you test Python code? Compare unittest and pytest, and explain mocking.

Both run automated tests. unittest ships in the standard library with class-based TestCase and self.assertEqual style. pytest is the de facto standard: plain functions, plain assert statements with rich failure output, fixtures, parametrisation and a large plugin ecosystem.

ExperiencedMost askedScenarioFree with sign-in
Answer

Several threads update a shared counter and the final total is wrong. Why does this happen and how do you fix it?

A process has its own memory space, a thread shares memory with others in the same process. Threads are lighter, but shared data needs synchronisation.

Safe ways to share:

  • queue.Queue: thread-safe producer-consumer channel, the preferred approach.
  • threading.Lock around read-modify-write sequences.
ExperiencedMost askedFree with sign-in
Answer

What is the difference between `__init__` and `__new__`?

__new__ creates the instance (it is a static method that receives the class and returns a new object). __init__ then sets up that new instance. Python calls __new__ first. It calls __init__ only if __new__ returns an instance of the class.

ExperiencedMost askedFree with sign-in
Answer

What does this print? `a = 256; b = 256; print(a is b); x = 1000; y = 1000; print(x is y)`

In a normal CPython session, typed separately, the first line prints True and the second usually prints False. CPython creates and caches the integers from -5 to 256, so both names point to the same object. Larger integers are created as new objects.

ExperiencedMost askedFree with sign-in
Answer

What are the walrus operator and structural pattern matching, and when are they useful?

The walrus operator := (3.8) assigns a value inside an expression. match/case (3.10) does structural pattern matching.

ExperiencedMost askedFree with sign-in
Answer

What are abstract base classes and duck typing in Python?

Duck typing means the methods an object has decide if it fits, not its declared class. The idea: "if it walks like a duck and quacks like a duck". Abstract base classes (ABCs) set a clear contract. They force subclasses to implement certain methods.

ExperiencedMost askedFree with sign-in
Answer

How do you create custom exceptions, and what is exception chaining?

Subclass Exception (not BaseException) and give it a meaningful name, optionally with extra data. Chaining keeps the original cause visible.

ExperiencedMost askedFree with sign-in
Answer

What does this function return, and why? def f(): try: return 1 finally: return 2

It returns 2. The finally block always runs, even when the try block has already hit a return. A return inside finally replaces the earlier return value.

ExperiencedFree with sign-in
Answer

What is `__slots__` and when would you use it?

__slots__ declares a fixed set of attributes for a class. Instances then store them in a compact array instead of a per-instance __dict__. This saves memory and makes attribute access a little faster.

JavaScript

ExperiencedMost asked
Answer

Explain the JavaScript event loop.

JavaScript runs your code on one thread. The event loop is what lets it handle async work without blocking.

  1. Synchronous code runs on the call stack until it is empty.
  2. The host (browser or Node) handles async APIs (timers, network, DOM events). Later it queues a callback.
  3. Promise reactions and queueMicrotask callbacks go to the microtask queue. Timers and I/O callbacks go to the macrotask (task) queue.
  4. When the stack is empty, the loop runs all microtasks. Then it takes one macrotask and runs it. Then it runs microtasks again, and repeats. In browsers rendering happens between tasks.

What this means: a long synchronous loop freezes the page and delays timers. setTimeout(fn, 0) means "after the current code and microtasks". A microtask that keeps adding microtasks can block rendering.

What they are checking: Whether you can describe stack, queues and ordering, not only say single threaded

ExperiencedMost asked
Answer

What is the output of this code, and why? console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4');

Output: 1 4 3 2.

  • 1 and 4 are synchronous, so they run first in order.
  • The promise callback is a microtask, so it runs as soon as the stack is empty: 3.
  • setTimeout is a macrotask, so it runs after the microtasks: 2, even with a delay of 0.

A harder variant adds async function f() { console.log('a'); await null; console.log('b'); }. Code before the first await runs synchronously; the code after it is a microtask. Explain by naming the stack, microtask queue and task queue.

What they are checking: Whether you can trace event loop ordering

ExperiencedMost askedFree with sign-in
Answer

What is the difference between promises and async/await?

async/await is syntax built on top of promises. An async function always returns a promise. await pauses that function until a promise settles, without blocking the thread.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between microtasks and macrotasks?

Both are queues the event loop uses, but microtasks have higher priority.

  • Microtasks: promise .then/.catch/.finally callbacks, await continuations, queueMicrotask, MutationObserver.
  • Macrotasks: setTimeout, setInterval, DOM events, network and I/O callbacks, MessageChannel.
ExperiencedMost askedFree with sign-in
Answer

What is the difference between debounce and throttle? Implement debounce.

Both limit how often a function runs during rapid events.

  • Debounce waits until events stop for N ms, then runs once. Good for search-as-you-type and window resize end.
  • Throttle runs at most once per N ms while events keep coming. Good for scroll, mousemove and drag.
ExperiencedMost askedFree with sign-in
Answer

What is the difference between shallow copy and deep copy? How do you deep copy an object?

A shallow copy duplicates only the top level; nested objects are still shared references. A deep copy duplicates everything.

ExperiencedMost askedFree with sign-in
Answer

How do arrow functions differ from regular functions?

Arrow functions are shorter, but the real differences are behavioural:

ExperiencedMost askedFree with sign-in
Answer

What is event delegation and why is it useful?

Event delegation puts one listener on a parent element. It uses event bubbling to handle events from the children, and finds the source with event.target.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between Promise.all, allSettled, race and any?

All take an iterable of promises and return one promise.

ExperiencedMost askedScenarioFree with sign-in
Answer

In a search box, users type fast and old responses sometimes overwrite newer results. How do you fix this race condition?

The problem: requests can return out of order. A slow response for an old query arrives last and wins.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you handle errors in async code, and what happens with unhandled promise rejections?

Use try/catch around await, or .catch() on promise chains. A thrown error in an async function becomes a rejected promise.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between CommonJS and ES modules?

Both split code into files, but they differ in syntax and loading.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between event bubbling and capturing?

An event travels in three phases: capturing (window down to the target), target, then bubbling (target back up to window).

ExperiencedMost askedFree with sign-in
Answer

What does this code print? const obj = { name: 'A', regular() { return this.name; }, arrow: () => this.name }; const fn = obj.regular; console.log(obj.regular(), obj.arrow(), fn());

  • obj.regular() gives "A": called as a method, so this is obj.
  • obj.arrow() gives undefined: an arrow function takes this from the place where the object literal sits (module or global scope), not from obj.
  • fn() loses the receiver. In strict mode or ES modules this is undefined, so reading .name throws a TypeError. In sloppy mode this is the global object. So it returns undefined (or "" in a browser, where window.name exists).
ExperiencedMost askedFree with sign-in
Answer

What is currying? Write a curry function.

Currying turns a function of several arguments into a chain of functions. Each one takes one (or some) arguments. It enables reuse through partial application.

ExperiencedMost askedFree with sign-in
Answer

How would you implement memoization?

Memoization caches results of a pure function keyed by its arguments, so repeated calls are instant.

ExperiencedMost askedFree with sign-in
Answer

Implement Promise.all yourself.

Return a new promise. Track results by index so the order is kept. Resolve when the count reaches the length. Reject on the first failure.

ExperiencedMost askedFree with sign-in
Answer

What are callbacks and callback hell? How do you avoid it?

A callback is a function passed to another function to be called later, often after async work. Callback hell is deeply nested callbacks that are hard to read, handle errors in and refactor.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between Object.freeze, Object.seal and const?

  • const prevents reassigning the variable. The object it points to can still change.
  • Object.freeze(obj) makes the object immutable at the top level: no add, delete or change of properties.
  • Object.seal(obj) blocks adding and deleting properties, but existing ones can still be changed.
  • Object.preventExtensions(obj) blocks only adding.
ExperiencedMost askedFree with sign-in
Answer

How does JavaScript garbage collection work, and what causes memory leaks?

Engines use mark-and-sweep: starting from roots (global object, stack), they mark everything reachable and free the rest. Reference counting alone fails on cycles, so it is not used.

ExperiencedMost askedScenarioFree with sign-in
Answer

Our single page app slows down and memory grows the longer a user keeps it open. How do you find and fix the leak?

Approach: reproduce, measure, compare, fix.

ExperiencedMost askedScenarioFree with sign-in
Answer

A page freezes for seconds when a user clicks a button that processes a large array. How would you fix it?

The work runs on the main thread, so it blocks rendering and input. Confirm with the DevTools Performance tab (a long task).

ExperiencedMost askedScenarioFree with sign-in
Answer

You must call an API for 1,000 ids, but the server allows only 5 concurrent requests. How do you implement that?

Fire all 1,000 at once and you will hit rate limits or exhaust the browser. Use a pool: start up to 5 workers that each pull the next id until none are left.

ExperiencedMost askedScenarioFree with sign-in
Answer

An API call fails randomly. How would you implement retry with exponential backoff?

Retry only temporary failures (network errors, 5xx, 429). Wait longer each time. Add jitter (a small random delay) so many clients do not retry together. Limit the number of attempts. Do not retry 4xx client errors. Retry non-idempotent requests (like POST) only if the server supports idempotency keys.

ExperiencedMost askedScenarioFree with sign-in
Answer

Given an array of objects, how do you remove duplicates by id and group items by a field?

Use a Map or object for O(n) work instead of nested loops.

ExperiencedMost askedFree with sign-in
Answer

What does the new keyword do, and how do classes work in JavaScript?

new Fn(...) does four things: creates an empty object and links its prototype to Fn.prototype. It calls Fn with this set to that object. It returns the object (unless the function returns another object).

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: users sometimes double click a Submit button and create two orders. How do you prevent it?

Fix it on both sides, because client checks alone can be bypassed.

Client:

  • Disable the button and show a spinner as soon as the submit starts. Enable it again in finally.
  • Guard with a flag so a second handler call returns early.

SQL

ExperiencedMost asked
Answer

What is a window function? Explain ROW_NUMBER, RANK and DENSE_RANK.

A window function computes a value across a set of rows related to the current row. Unlike GROUP BY, it does not collapse them. You define the set with OVER (PARTITION BY ... ORDER BY ...).

For salaries 90, 80, 80, 70 ordered descending:

SalaryROW_NUMBERRANKDENSE_RANK
90111
80222
80322
70443
  • ROW_NUMBER: unique sequence, ties broken arbitrarily.
  • RANK: ties share a rank, then a gap.
  • DENSE_RANK: ties share a rank, no gap.
SELECT name, dept_id, salary,
       RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS dept_rank
FROM employees;

Other common ones: LAG, LEAD, SUM() OVER, NTILE, FIRST_VALUE.

What they are checking: Whether you know analytics SQL beyond GROUP BY

ExperiencedMost askedFree with sign-in
Answer

What are the transaction isolation levels and what problems does each prevent?

Isolation levels trade consistency for concurrency. The problems they prevent:

  • Dirty read: reading uncommitted data of another transaction.
  • Non-repeatable read: the same row read twice returns different values.
  • Phantom read: the same query returns new rows the second time.
ExperiencedMost askedScenarioFree with sign-in
Answer

How would you get the top 3 highest-paid employees in every department?

Rank within each department using a window function, then filter.

ExperiencedMost askedScenarioFree with sign-in
Answer

A query on a table with millions of rows suddenly became slow. How do you investigate and fix it?

Measure before changing anything.

ExperiencedMost askedScenarioFree with sign-in
Answer

Two users book the last seat at the same time. How do you prevent double booking in SQL?

Make the check and the update atomic using row locking or a constrained update.

Option 1, pessimistic lock:

ExperiencedMost askedScenarioFree with sign-in
Answer

Your report query joins five tables and takes minutes. What optimizations would you consider?

Start from the execution plan, then work through the options in order of effort.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a clustered and a non-clustered index?

A clustered index sets the physical order of the table rows, so the table data is the index. A non-clustered index is a separate structure with pointers back to the rows.

ExperiencedMost askedFree with sign-in
Answer

What is a CTE and when would you use it instead of a subquery?

A Common Table Expression (WITH) is a named temporary result you can reference in the following query. It improves readability and supports recursion.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you write a query to show total revenue per month for the last 6 months?

Truncate the date to the month, filter the range, group and sort.

ExperiencedMost askedFree with sign-in
Answer

What is a deadlock in a database and how do you prevent it?

A deadlock happens when two transactions each hold a lock the other needs, so neither can proceed. The database detects it and aborts one transaction as the victim.

Example: T1 updates row A then wants row B, while T2 updated row B and wants row A.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you paginate results efficiently? What is wrong with large OFFSET values?

Simple pagination uses LIMIT and OFFSET. But the database must read and throw away all skipped rows, so page 10,000 is slow.

ExperiencedMost askedScenarioFree with sign-in
Answer

You added an index but the database still does a full table scan. Why might that happen?

Common reasons the planner ignores an index:

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you add a column to a table with 100 million rows in production without downtime?

Avoid anything that locks or rewrites the whole table during peak traffic.

ExperiencedMost askedScenarioFree with sign-in
Answer

You need to delete 50 million old rows from a large table. How do you do it safely?

One giant DELETE holds locks for a long time, bloats the transaction log and can stall replication. Delete in small batches instead.

ExperiencedMost askedScenarioFree with sign-in
Answer

Write a query that returns employees earning more than the average salary of their own department.

Compare each salary to a per-department average, using a join or a window function.

ExperiencedMost askedFree with sign-in
Answer

When would you denormalize a database?

Denormalize when read performance matters more than write simplicity and joins have become the bottleneck, after measuring.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between IN and EXISTS?

Both test membership in a subquery result. IN compares a value against a list. EXISTS checks whether the correlated subquery returns at least one row.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a correlated and a non-correlated subquery?

A non-correlated subquery runs once and does not reference the outer query. A correlated subquery references outer columns, so conceptually it runs once per outer row.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you calculate a running total in SQL?

Use SUM() OVER with an ordered window.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you pivot rows into columns in SQL?

For simple conditional logic, CASE inside a query is enough and keeps everything portable. To pivot rows into columns, combine CASE with an aggregate.

ExperiencedMost askedFree with sign-in
Answer

What are lost updates and how do you avoid them?

A lost update happens when two transactions read the same value, both change it, and the second write overwrites the first.

Example: both read stock = 10, one sets 9 and the other sets 8, so one sale vanishes.

ExperiencedMost askedFree with sign-in
Answer

Explain the difference between OLTP and OLAP databases.

OLTP handles many small, concurrent transactions for running the business. OLAP handles few, heavy analytical queries over large history.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you find the second-highest value without using LIMIT, TOP or window functions?

Use a subquery that takes the maximum of everything below the overall maximum.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between SQL and NoSQL databases from a query perspective, and when would you still choose a relational database?

Relational databases use a fixed schema, SQL, joins and ACID transactions. NoSQL stores (document, key-value, wide-column, graph) trade some of that for flexible schemas and horizontal scale.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a database index on a foreign key and not having one? Should you always index foreign keys?

A foreign key constraint does not create an index on the child column in PostgreSQL. (MySQL InnoDB does create one.) Without it:

  • Joins from parent to child scan the whole child table.
  • Deleting or updating a parent row forces a scan of the child table to check references. This can be slow and cause lock contention.

Java

ExperiencedMost askedFree with sign-in
Answer

How do you use Spring Data JPA? Explain entities, repositories and the N+1 problem.

Annotate a class with @Entity, extend JpaRepository, and Spring generates the implementation.

ExperiencedMost askedFree with sign-in
Answer

How does @Transactional work in Spring, and what are its common pitfalls?

Spring wraps the bean in a proxy. The proxy opens a transaction before the method. It commits on normal return. It rolls back on a RuntimeException or Error (not on checked exceptions by default).

ExperiencedMost askedFree with sign-in
Answer

How does ConcurrentHashMap work and how is it different from HashMap and Hashtable?

ConcurrentHashMap is a thread-safe hash map. It allows concurrent reads and fine-grained writes without locking the whole map.

ExperiencedMost askedFree with sign-in
Answer

Explain the Executor framework and thread pools. How do you choose a pool size?

The Executor framework separates task submission from execution. You submit tasks, and a pool of reusable threads runs them.

ExperiencedMost askedFree with sign-in
Answer

What is a deadlock? How can you detect and prevent it?

A deadlock is when two or more threads each hold a lock the other needs, so none can move on.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your production Java service's memory keeps growing until it crashes with OutOfMemoryError. How do you investigate?

Capture evidence, find what is retaining memory, fix it, and add a guard.

ExperiencedMost askedScenarioFree with sign-in
Answer

A Java API became slow in production under load. How do you find the bottleneck?

Measure before changing anything, and narrow down from the outside in.

ExperiencedMost askedScenarioFree with sign-in
Answer

Multiple threads increment a shared counter and the final value is wrong. How do you fix it?

count++ is not atomic (read, add, write), so threads overwrite each other's updates. This is a race condition.

ExperiencedMost askedFree with sign-in
Answer

What does @SpringBootApplication do and how does auto-configuration work?

@SpringBootApplication combines @Configuration, @ComponentScan and @EnableAutoConfiguration.

ExperiencedMost askedFree with sign-in
Answer

Explain Spring bean scopes and the bean lifecycle.

The default scope is singleton: one instance per container. Others are prototype (new instance per injection or lookup), and for web apps request, session and application.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between @Component, @Service, @Repository and @Controller? And @Bean vs @Component?

All four are stereotype annotations that register a class as a bean through component scanning. The last three are specialisations of @Component that add meaning.

ExperiencedMost askedFree with sign-in
Answer

What is try-with-resources and how does it differ from try-finally?

Try-with-resources closes any resource that implements AutoCloseable for you. It closes in reverse order of declaration, even if an exception occurs.

ExperiencedMost askedFree with sign-in
Answer

What is CompletableFuture and how do you combine async tasks?

CompletableFuture is a Future you can compose without blocking: chain steps, combine results and handle errors.

ExperiencedMost askedFree with sign-in
Answer

What are virtual threads in Java 21 and when should you use them?

Virtual threads are lightweight threads scheduled by the JVM, not the OS (Project Loom, final in Java 21). Millions can exist. A blocking call such as I/O parks the virtual thread and frees its carrier platform thread.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between synchronized and ReentrantLock?

Both are reentrant mutual-exclusion locks. ReentrantLock adds control that synchronized lacks.

ExperiencedMost askedFree with sign-in
Answer

How do you handle exceptions globally in a Spring Boot REST API?

Use @RestControllerAdvice with @ExceptionHandler methods to turn exceptions into consistent error responses, ideally RFC 7807 ProblemDetail (Spring 6).

ExperiencedMost askedFree with sign-in
Answer

What is the difference between lazy and eager loading in JPA and what is a LazyInitializationException?

Lazy loading fetches an association only when it is first accessed. Eager loading fetches it immediately with the parent.

ExperiencedMost askedFree with sign-in
Answer

How do you implement a thread-safe singleton in Java?

The simplest safe options are an enum singleton or the initialization-on-demand holder idiom.

ExperiencedMost askedScenarioFree with sign-in
Answer

A HashMap lookup suddenly returns null for a key you definitely inserted. What could be wrong?

The most likely cause is a key whose hashCode or equals changed after it was added, or a broken hashCode/equals pair.

ExperiencedMost askedFree with sign-in
Answer

Explain the difference between map and flatMap in streams, and how groupingBy works.

map transforms each element into one element. flatMap transforms each element into a stream and flattens them into one stream.

ExperiencedMost askedFree with sign-in
Answer

How do you read configuration in Spring Boot? Explain profiles and @ConfigurationProperties.

Boot loads application.properties or application.yml, then profile files such as application-prod.yml, environment variables and command-line arguments. Later sources override earlier ones, so env vars win over files.

ExperiencedMost askedFree with sign-in
Answer

How do you write unit tests for a Spring Boot service? What is the difference between @SpringBootTest, @WebMvcTest and Mockito mocks?

Test the smallest slice that proves the behaviour.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between G1, ZGC and Parallel GC, and how would you tune GC for a latency sensitive service?

Parallel gives the most throughput but has stop-the-world pauses. G1 balances pause times and throughput. ZGC aims for very short pauses whatever the heap size.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you cache data in a Spring Boot application, and what problems should you watch for?

Enable caching with @EnableCaching and annotate methods. Back it with Caffeine for in-process or Redis for shared caches.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design pagination and sorting for a REST endpoint that returns a large list using Spring Data?

Never return unbounded lists. Accept page, size and sort parameters, validate them, and return a page with metadata.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your Spring Boot app fails to start with 'No qualifying bean of type found' or 'circular dependency'. How do you resolve it?

Read the failure analysis: it names the missing bean and the injection point.

React

ExperiencedMost asked
Answer

What is the difference between useMemo and useCallback?

Both memoise a value between renders and only recompute when dependencies change.

  • useMemo(() => compute(a, b), [a, b]) caches a computed value.
  • useCallback(fn, [deps]) caches a function; it equals useMemo(() => fn, [deps]).
const sorted = useMemo(() => items.slice().sort(cmp), [items]);
const onSelect = useCallback((id) => setSelected(id), []);

Use them when:

  • A calculation is genuinely expensive.
  • You pass a function or object to a React.memo child, or use it as a hook dependency, and need a stable reference.

Do not wrap everything: memoisation costs memory and comparison time. Measure with the Profiler first. The React Compiler can add much of this automatically.

What they are checking: Whether you know they are for referential stability and cost, not default habits

ExperiencedMost asked
Answer

What causes a React component to re-render, and how do you reduce unnecessary renders?

A component re-renders when its state changes. It also re-renders when its parent re-renders (even with the same props), or when a context it uses changes.

Ways to reduce it, roughly in order of preference:

  1. Move state down, closer to where it is used, so fewer components sit under the changing state.
  2. Pass expensive parts as children or props (composition), so they keep the same element identity.
  3. Split contexts, or use a store with selectors.
  4. Use React.memo on heavy children, with stable props through useMemo and useCallback.
  5. Virtualise long lists, and use useDeferredValue or transitions for expensive updates.

Measure first with React DevTools Profiler ("why did this render") rather than guessing. A re-render alone is cheap; the problem is slow work during it.

What they are checking: Whether you diagnose before optimising

ExperiencedMost askedScenario
Answer

Scenario: a page renders a list of 10,000 rows and scrolling and typing feel slow. How do you fix it?

Find the problem first with the React Profiler and the browser Performance tab. Then reduce what is rendered and re-rendered.

  1. Virtualise (windowing): render only visible rows using react-window, @tanstack/react-virtual or similar. This is usually the biggest win.
  2. Paginate or filter on the server if users never need all rows at once.
  3. Stop needless re-renders: stable keys, React.memo on the row, useCallback for handlers, and keep per-row state inside the row.
  4. Move fast-changing state (like a search input) so it does not re-render the list; use useDeferredValue for filtering.
  5. Avoid expensive work in render: precompute or memoise sorting and formatting.
  6. Keep row DOM small and avoid layout thrash.

Confirm with before-and-after measurements.

What they are checking: Whether you measure and reach for virtualisation

ExperiencedMost askedScenario
Answer

Scenario: your component enters an infinite render loop or you get 'Too many re-renders'. How do you find and fix it?

Causes are usually one of these:

  • Calling a setter during render: <button onClick={setOpen(true)}> runs immediately; it must be onClick={() => setOpen(true)}.
  • An effect that sets state it also depends on, with no guard:
useEffect(() => { setItems([...items, 1]); }, [items]); // loops forever
  • A dependency that is a new object, array or function on every render (useEffect(fn, [{ a: 1 }])). The effect then re-runs each time and sets state.

Fix:

  • Move calculations into render (derived state) instead of effect plus setState.
  • Use functional updates (setItems(prev => ...)) so you do not need the value as a dependency.
  • Memoise object dependencies with useMemo or depend on primitives.
  • Check the call stack and use the lint rule react-hooks/exhaustive-deps. Add a console log to see which dependency changes.

What they are checking: Whether you can find the loop cause quickly

ExperiencedMost askedFree with sign-in
Answer

When would you use Context versus Redux (or another state library)?

Context is a delivery mechanism for a value, not a state manager. Redux (and Zustand, Jotai) provide a store, update patterns and selective subscriptions.

Use Context for low-frequency, app-wide values: theme, locale, auth user, feature flags.

ExperiencedMost askedFree with sign-in
Answer

What are React Server Components, and how do they differ from client components?

Server Components render only on the server (at build time or per request). They send serialised output to the browser, with no component JavaScript shipped for them.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between CSR, SSR, SSG and ISR in Next.js?

  • CSR (client-side rendering): the browser downloads JavaScript and builds the page. Slow first paint, weak for SEO without extras.
  • SSR (server-side rendering): HTML is generated on each request. Fresh data, good SEO, but needs a server and costs time per request.
  • SSG (static site generation): HTML is built once...
ExperiencedMost askedFree with sign-in
Answer

What is new in React 19?

Main additions:

  • Actions: functions (often async) passed to <form action={fn}> or transitions, with built-in pending, error and optimistic handling.
  • useActionState for form state from an action, useFormStatus for pending state inside a form, and useOptimistic for instant optimistic UI.
  • use() to read a...
ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: a setInterval counter inside useEffect always shows the same old value. Why, and how do you fix it?

This is a stale closure (the callback holds an old value). The effect ran once with []. So the callback captured count from the first render and keeps using it.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: a data-fetching effect shows the wrong user's data when the id changes quickly. How do you fix the race condition?

Responses can arrive out of order, so an older request overwrites the newer one. Cancel or ignore old requests in the effect cleanup.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: design state management for a large React app with auth, a shopping cart, API data and forms.

Split state by type and use the simplest tool for each.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: a content-heavy marketing and blog site must load fast and rank on Google. Which React rendering approach do you choose?

Use a framework with server rendering, most pages as static or incrementally regenerated: Next.js (App Router) or similar.

ExperiencedMost askedScenarioFree with sign-in
Answer

Refactor a component that calls fetch inside useEffect into a reusable hook that handles loading, error and cancellation.

Move the data logic into a custom hook that returns { data, error, loading }. Use an AbortController so a slow earlier request cannot overwrite a newer one.

ExperiencedMost askedFree with sign-in
Answer

What are error boundaries and how do you use them?

An error boundary is a component that catches errors thrown while rendering its children, in lifecycle methods and in constructors. It shows a fallback UI instead of crashing the whole app.

ExperiencedMost askedFree with sign-in
Answer

When would you use useReducer instead of useState?

Use useReducer when state has several related fields, when the next state depends on complex rules, or when many different actions update it. It centralises updates in a pure reducer, which is easy to test.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between useEffect and useLayoutEffect?

Both run after React updates the DOM, but at different times.

ExperiencedMost askedFree with sign-in
Answer

How do Suspense and lazy loading work?

React.lazy loads a component's code only when it is first rendered. Suspense shows a fallback while the component (or data) is not ready.

ExperiencedMost askedFree with sign-in
Answer

What is useTransition and useDeferredValue?

Both mark updates as non-urgent so React keeps the UI responsive.

  • useTransition returns [isPending, startTransition]. Wrap a state update in startTransition so React can interrupt it for urgent input.
  • useDeferredValue(value) returns a lagging copy of a value that updates after urgent work finishes.
ExperiencedMost askedFree with sign-in
Answer

What is hydration, and what causes hydration mismatch errors?

Hydration is when React attaches event handlers and state to HTML that the server already rendered. It reuses the existing DOM instead of rebuilding it.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: typing in a big form feels laggy because every keystroke re-renders the whole form. What do you do?

Each keystroke updates state at the top, which re-renders everything beneath.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: a child component's state resets unexpectedly (or its input loses focus) on every parent update. What are the likely causes?

React preserves state only while the component keeps the same type at the same position (and key). Resets usually come from:

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: how would you handle loading, error and empty states for data fetched on the client?

Treat every request as having four states: loading, error, empty and success, and design each one.

ExperiencedMost askedFree with sign-in
Answer

How does React batch state updates?

React groups multiple state updates that happen in the same event or tick into a single re-render. Since React 18 this automatic batching also works inside promises, timeouts and native event handlers, not only React events.

ExperiencedMost askedFree with sign-in
Answer

What are Server Actions in React and Next.js?

Server Actions are async functions marked with "use server". They run on the server but can be called from client code, usually as a form action or from an event handler. The framework creates the network endpoint for you.

ExperiencedMost askedFree with sign-in
Answer

How do you build and maintain a shared component library for several React applications?

Treat it as a product: a versioned package with a clear API, documentation and tests, built on shared design tokens.

ExperiencedFree with sign-in
Answer

How do you test React components?

Test how a user sees the behaviour, not implementation details.

ExperiencedFree with sign-in
Answer

What is the React Compiler, and does it replace useMemo and useCallback?

The React Compiler is a build-time tool (Babel/SWC plugin). It analyses components and memoises values and functions for you, so you rarely write useMemo, useCallback or React.memo by hand.

ExperiencedFree with sign-in
Answer

What are micro frontends, and when would you use them?

Micro frontends split a large web application into smaller frontends. Separate teams build, test and deploy them independently. They are then combined into one page for the user. It is the frontend version of the microservices idea.

TypeScript

ExperiencedMost askedScenario
Answer

TypeScript types are erased at runtime. How do you validate data coming from an API or form safely?

Types do not exist at runtime, so a fetch().json() result typed as User is just a guess. Check the data where it enters your app, using a runtime schema library (Zod, Valibot, ArkType). Get the static type from the schema, so the two never get out of sync.

import { z } from "zod";

const UserSchema = z.object({
  id: z.number(),
  name: z.string().min(1),
  email: z.string().email().optional(),
});
type User = z.infer<typeof UserSchema>;

async function getUser(id: number): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const json: unknown = await res.json();
  return UserSchema.parse(json);       // throws a clear error if the shape is wrong
}

Practical points:

  • Treat all external input (network, localStorage, query string, env vars) as unknown until parsed.
  • Use safeParse where you want to handle errors without exceptions.
  • Share the schema between client and server so both validate the same contract.
  • Hand-written type guards work for tiny shapes but get long fast.

What they are checking: Whether you understand the limit of static types and validate untrusted data at the edge

ExperiencedMost askedScenario
Answer

An API returns JSON and the team wants the response typed. How would you handle it?

I would never trust the type for data from outside the program. The flow:

  1. Define the expected shape once as a runtime schema (Zod or similar) and infer the TypeScript type from it.
  2. Keep the raw result as unknown and parse it in one wrapper function so nobody reads unvalidated data.
  3. Handle failure on purpose (bad status, bad shape). Return a result type or throw a typed error.
import { z } from "zod";

const Todo = z.object({ id: z.number(), title: z.string(), done: z.boolean() });
type Todo = z.infer<typeof Todo>;

async function fetchJson<T>(url: string, schema: z.ZodType<T>): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  const body: unknown = await res.json();
  return schema.parse(body);
}

const todos = await fetchJson("/api/todos", z.array(Todo));

If the backend is also TypeScript, share the schema package or generate types from an OpenAPI/GraphQL spec. Then a contract change breaks the build instead of production. A bare as Todo[] cast is acceptable only for trusted internal data and should be a conscious exception.

What they are checking: Whether you validate at the boundary and keep a single source of truth for the contract

ExperiencedMost askedFree with sign-in
Answer

How do generic constraints and default type parameters work?

A constraint with extends limits what a type parameter may be, so you can safely use its members. A default gives the parameter a fallback when it cannot be inferred or is not supplied.

ExperiencedMost askedFree with sign-in
Answer

What do ReturnType, Parameters and Awaited do, and when would you use them?

They extract types from existing functions or promises, so you do not repeat or drift from the source.

ExperiencedMost askedFree with sign-in
Answer

What is a discriminated union, and why is it useful?

A discriminated union is a union of object types that share a literal-typed property (the discriminant). Checking that property lets TypeScript narrow to exactly one member.

ExperiencedMost askedFree with sign-in
Answer

What are mapped types? Write one.

A mapped type builds a new type by looping over the keys of another type with [K in keyof T]. It can also change modifiers or value types. Most utility types are mapped types.

ExperiencedMost askedFree with sign-in
Answer

How do you type useState, event handlers and refs in React with TypeScript?

Let inference work where it can, and add a generic where the initial value does not tell the full type.

ExperiencedMost askedFree with sign-in
Answer

How do you do exhaustive checking with never, and why does it matter?

Assign the leftover value to never in the default branch. If every union member is handled, the leftover type is never and it compiles. If someone adds a new member later, the assignment fails and the compiler points to the switch that needs updating.

ExperiencedMost askedScenarioFree with sign-in
Answer

You have a large JavaScript codebase. How would you migrate it to TypeScript incrementally?

Migrate gradually so the app keeps shipping.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you build a type-safe API client where each endpoint has its own request and response types?

Describe all endpoints in one map type, then make a generic function that looks up the types by path. The compiler then knows the body and the result for each call.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you model loading, success and error states for a data fetch in a React component?

Use a discriminated union instead of separate boolean flags, so impossible combinations (loading and error at once) cannot exist.

ExperiencedMost askedFree with sign-in
Answer

What are conditional types and the infer keyword?

A conditional type picks one of two types based on a check: T extends U ? X : Y. With infer you can capture a part of the matched type into a new type variable.

ExperiencedMost askedFree with sign-in
Answer

What do 'as const' and the 'satisfies' operator do?

as const makes a value deeply readonly and keeps literal types instead of widening them. satisfies checks that a value matches a type without changing the inferred type of the value.

ExperiencedMost askedFree with sign-in
Answer

What are function overloads in TypeScript? When are generics a better option?

Overloads declare several call signatures for one function, followed by a single implementation that handles all of them. Callers see only the overload signatures.

ExperiencedMost askedFree with sign-in
Answer

Is TypeScript structurally or nominally typed? What are branded types?

TypeScript is structurally typed: two types are compatible if their shapes match, regardless of names. That means a UserId and an OrderId that are both number are interchangeable, which can hide bugs.

ExperiencedMost askedFree with sign-in
Answer

What are index signatures, how do they differ from Record, and what does noUncheckedIndexedAccess do?

An index signature says an object can have any number of keys of a given type: { [key: string]: number }. Record<K, V> is a mapped type that expresses the same idea and also works with a union of known keys.

ExperiencedMost askedScenarioFree with sign-in
Answer

A function should accept either a single item or an array of items and return the same shape. How would you type it?

Use a generic with a conditional return type, or overloads, so the output depends on the input.

ExperiencedMost askedScenarioFree with sign-in
Answer

The TypeScript build (tsc) has become very slow in a large monorepo. What would you do?

First measure, then reduce the work.

ExperiencedMost askedScenarioFree with sign-in
Answer

A third-party library returns any in several places. How do you keep your codebase type-safe?

Contain the unsafety at the boundary so any never leaks into the rest of the code.

ExperiencedMost askedFree with sign-in
Answer

Interface extends versus intersection types: how do they differ when properties conflict?

Both combine shapes, but they report conflicts differently.

ExperiencedMost askedFree with sign-in
Answer

How do you write a generic React component, such as a reusable list or select that works with any item type?

Make the function component generic. The props use the type parameter, and TypeScript infers it from what the caller passes.

ExperiencedMost askedFree with sign-in
Answer

What is declaration merging and module augmentation? Show how to add a property to an existing type such as Express Request.

Declaration merging means TypeScript joins several declarations with the same name into one. Interfaces merge, and namespaces merge with classes and functions. Module augmentation applies that to a third-party module: you reopen its declarations and add to them.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you configure tsconfig.json for a Next.js or other modern bundled app, and what do the key options mean?

The bundler does the emitting, so TypeScript is used only for checking.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your team resists turning on strict mode because the codebase has thousands of errors. How do you roll it out?

Enable it gradually and stop the debt from growing.

ExperiencedFree with sign-in
Answer

What are template literal types? Give a practical example.

Template literal types build string literal types using the same backtick syntax as JavaScript templates, and they distribute over unions.

ExperiencedFree with sign-in
Answer

What do covariance and contravariance mean for function parameters, and what does strictFunctionTypes change?

Covariance means a more specific type can be used where a general one is expected (return types). Contravariance is the reverse: a function that accepts a general type can stand in for one that accepts a specific type (parameters).

Next.js

ExperiencedMost asked
Answer

How does caching work in Next.js 15 and 16? What changed from Next 14?

Next 14 cached fetch results and GET route handlers by default, which surprised many teams. Since Next 15, fetch requests and GET route handlers are not cached by default, and you opt in.

The caching layers worth knowing:

  • Request memoization: identical fetch calls during one render are de-duplicated.
  • Data cache: persisted fetch results (opt in with next: { revalidate: n }, cache: "force-cache" or tags).
  • Full route cache: the rendered HTML and RSC payload of static routes.
  • Router cache (client): visited segments kept in the browser. In Next 15, page segments are no longer reused by default, so navigations are fresher.

Next 16 adds an opt-in model called Cache Components. You mark code with the "use cache" directive and control how long it lives with cache life profiles, instead of route-level flags. Dynamic data inside static shells is streamed with Suspense.

export default async function Page() {
  const res = await fetch("https://example.com/api/rates", {
    next: { revalidate: 3600, tags: ["rates"] },
  });
  const rates: Record<string, number> = await res.json();
  return <pre>{JSON.stringify(rates)}</pre>;
}

Tags let you clear the cache later with revalidateTag (in Next 16 it also takes a cache life profile as a second argument). Always check the docs for your exact version, since this area changes quickly.

What they are checking: Whether you know caching is opt-in now and understand the layers

ExperiencedMost asked
Answer

Where should you store a JWT in a web app: localStorage or an HttpOnly cookie?

Prefer an HttpOnly, Secure, SameSite cookie. Any JavaScript on the page can read localStorage. So one XSS bug (or a bad npm package) lets an attacker steal the token.

localStorageHttpOnly cookie
Readable by JSYes (XSS can steal it)No
Sent automaticallyNo, you add the headerYes, with every request to the domain
CSRF riskNoneYes, so use SameSite and CSRF protection
Works with server componentsNo, the server never sees itYes, readable via cookies()
// app/api/login/route.ts
import { NextResponse } from "next/server";

export async function POST() {
  const token = "signed.jwt.value"; // issued after verifying credentials
  const res = NextResponse.json({ ok: true });
  res.cookies.set("session", token, {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });
  return res;
}

Also keep access tokens short-lived and use a refresh token. Check the signature on the server for every request. Set a strict Content Security Policy. For SSR apps, cookies are the natural choice since the server can read them during rendering.

What they are checking: Whether you understand the XSS versus CSRF choice, and pick cookies for SSR

ExperiencedMost askedScenario
Answer

A Next.js page has a very high Time To First Byte. How do you investigate and fix it?

Find where the time goes before changing anything.

  1. Check whether the route is rendered dynamically on every request when it could be static or cached. Look for cookies(), headers(), searchParams or cache: "no-store" forcing dynamic rendering.
  2. Measure the server: log timing around each fetch and database call, or use OpenTelemetry. Look for slow queries, missing indexes and N+1 patterns.
  3. Remove request waterfalls: start independent fetches together with Promise.all.
  4. Cache what can be cached: revalidate, tags, or "use cache" in Next 16; a CDN in front for public pages.
  5. Stream: wrap slow, non-critical sections in Suspense so the shell is sent immediately.
  6. Reduce work in middleware and avoid heavy computation on the request path.
  7. Check geography: server and database should be in the same region, and users far away should hit a CDN.
  8. Check cold starts and memory limits on serverless platforms.
const [user, posts] = await Promise.all([getUser(), getPosts()]); // parallel, not sequential

Verify with real field data (Core Web Vitals, server timing headers), not only local runs.

What they are checking: Whether you follow a measurement-driven approach and know Next-specific causes

ExperiencedMost askedScenario
Answer

You updated content in the database, but the Next.js site still shows the old version. What could be wrong?

This is a caching question. Walk the layers from server to browser.

  1. Static or ISR page: the page was generated earlier and revalidate has not passed. Fix with on-demand revalidation (revalidatePath or revalidateTag) after writes, or lower the interval.
  2. Data cache: a fetch with force-cache or a long revalidate. Use tags and invalidate them, or cache: "no-store" for truly live data.
  3. Full route cache and generateStaticParams: new slugs need dynamicParams true or a rebuild.
  4. Router cache in the browser: soft navigation may show a previous payload. Call router.refresh() after a mutation, or use Server Actions which refresh automatically.
  5. CDN or reverse proxy cache (Cloudflare, nginx): check Cache-Control and purge. Verify with curl -I and the x-nextjs-cache header (HIT, MISS, STALE).
  6. Multiple instances with separate in-memory caches: a revalidation reached only one server. Use a shared cache handler.
  7. Read-replica lag or a wrong environment variable pointing at old data.
curl -sI https://example.com/blog/post | grep -i -E "cache|age|x-nextjs"

Fix by deciding the freshness requirement per page, then invalidating explicitly on write.

What they are checking: Whether you can systematically debug stale data across caches

ExperiencedMost askedScenario
Answer

You see 'Hydration failed because the server-rendered HTML didn't match the client'. What causes it and how do you fix it?

Hydration attaches React to server HTML. If the first client render produces different markup than the server did, React reports a mismatch.

Common causes:

  • Values that differ between server and client: Date.now(), Math.random(), new Date().toLocaleString() (time zone and locale differ).
  • Reading window, localStorage or navigator during render.
  • Invalid HTML nesting, such as a <div> inside a <p>, which the browser repairs.
  • Browser extensions injecting attributes, or inconsistent conditional rendering based on the user agent.

Fixes:

"use client";
import { useEffect, useState } from "react";

export function Clock() {
  const [now, setNow] = useState<string | null>(null);   // same on server and first client render
  useEffect(() => setNow(new Date().toLocaleTimeString()), []);
  return <span>{now ?? ""}</span>;
}
  • Compute browser-only values in useEffect, so the first render matches.
  • Use useId for ids, and pass stable data (like a server-generated timestamp) as props.
  • Fix invalid nesting.
  • Use suppressHydrationWarning only for unavoidable one-off text such as a timestamp.
  • next/dynamic with ssr: false for components that cannot render on the server.

What they are checking: Whether you can reason about server versus client render output

ExperiencedMost asked
Answer

How do you revalidate cached data: time-based versus on-demand?

Time-based: the data is considered fresh for N seconds, then refreshed on a later request (stale-while-revalidate).

// route-level
export const revalidate = 60;
// or per fetch
// fetch(url, { next: { revalidate: 60 } })

On-demand: you invalidate immediately when something changes, for example from a Server Action or a webhook route.

// app/actions.ts
"use server";
import { revalidatePath, revalidateTag } from "next/cache";

export async function publishPost() {
  // ... write to the database
  revalidateTag("posts", "max");  // tag-based; Next 16 takes a cache life profile as 2nd argument
  revalidatePath("/blog");       // or a specific route
}

Choose time-based when a delay is fine (price lists, blogs). Choose on-demand when users expect to see their own change at once (admin edits, CMS publish webhooks). Combine both: a long revalidate as a safety net plus on-demand invalidation for freshness. Tags are better than paths when many pages depend on the same data.

What they are checking: Whether you can keep data fresh without turning off caching

ExperiencedMost askedFree with sign-in
Answer

What are Server Actions, and what should you watch out for when using them?

Server Actions are async functions that run on the server and can be called from forms or client code. They are marked with "use server". Next creates a POST endpoint for each one automatically.

ExperiencedMost askedFree with sign-in
Answer

What is middleware in Next.js and what is it good for? What changed in Next 16?

Middleware runs before a request reaches a route. It can redirect, rewrite, set headers and cookies, or short-circuit with a response. It runs for the paths you match.

ExperiencedMost askedFree with sign-in
Answer

What is generateStaticParams and how does it relate to dynamic routes?

generateStaticParams tells Next which dynamic route values to pre-render at build time. It replaces getStaticPaths from the Pages Router.

ExperiencedMost askedFree with sign-in
Answer

What is streaming in Next.js, and how do Suspense boundaries help?

Streaming sends the page's HTML in chunks as each part becomes ready, instead of waiting for the slowest query. The user sees the shell immediately and slow sections fill in later.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you protect pages and data behind login in a Next.js App Router app?

Use layers, and put the real check next to the data.

ExperiencedMost askedScenarioFree with sign-in
Answer

Pages of your Next.js site are not appearing in Google. How do you diagnose it?

Work from what Google sees to how the page is built.

ExperiencedMost askedScenarioFree with sign-in
Answer

The Largest Contentful Paint on a Next.js page is poor. What would you do?

First find the LCP element in Lighthouse or Chrome DevTools (usually a hero image or a big heading). Then remove what delays it.

ExperiencedMost askedFree with sign-in
Answer

When would you fetch data on the client (SWR or TanStack Query) instead of in a Server Component?

Use the server by default. Fetch on the client when the data depends on the browser or changes while the user is on the page.

ExperiencedMost askedScenarioFree with sign-in
Answer

You inherit a Pages Router app and the team wants the App Router. How do you migrate safely?

Migrate incrementally, because both routers work in the same project. If a path exists in both, app/ wins, so move one route at a time.

ExperiencedMost askedScenarioFree with sign-in
Answer

You must self-host a Next.js app on a small VM. How would you set up the build, runtime and deploys?

Build in CI, not on the small server, and ship only the output.

ExperiencedMost askedFree with sign-in
Answer

What are route groups, parallel routes and intercepting routes in the App Router?

They are folder conventions that shape routing without changing URLs in unusual ways.

ExperiencedMost askedFree with sign-in
Answer

Server Components cannot use hooks or context. How do you provide shared client state such as a theme or a query client?

Create a small Client Component that wraps the provider and shows children. Then use it in the (server) root layout. Server components passed as children stay server components.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between the Edge runtime and the Node.js runtime in Next.js?

You can choose the runtime per route or middleware.

ExperiencedMost askedFree with sign-in
Answer

How do you think about CSRF, XSS and security headers in a Next.js app?

  • XSS: React escapes values by default. The risks are dangerouslySetInnerHTML, unsanitised markdown or HTML from users, and unsafe URLs (javascript:). Sanitise with a library such as DOMPurify and set a Content Security Policy.
  • CSRF: cookie-based auth is exposed to cross-site requests. Use SameSite=Lax or...
ExperiencedMost askedScenarioFree with sign-in
Answer

You have a list with 100,000 items to show. How would you design pagination and rendering in Next.js?

Never render them all. Paginate or stream, and let the database do the work.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you build a multilingual (i18n) or multi-tenant site in the App Router?

Put the variable part in a dynamic top-level segment and resolve it early.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your public Next.js site is being scraped heavily and your server cost is rising. What would you do?

Reduce the cost per request first, then restrict abusers, without blocking real users or search engines.

ExperiencedMost askedFree with sign-in
Answer

What new React 19 features matter for Next.js apps (use, useActionState, useFormStatus, useOptimistic)?

The App Router uses React 19, so these are available:

ExperiencedMost askedScenarioFree with sign-in
Answer

A Next.js build runs out of memory or is very slow on your small server. How do you fix the deployment?

Stop building on the production machine, and shrink the build.

ExperiencedMost askedFree with sign-in
Answer

How do you use TanStack Query with the Next.js App Router, so the server loads the data first and the client reuses it?

Prefetch the query in a Server Component, dehydrate the cache, and pass it to a client-side provider with HydrationBoundary. The client component then reads the same query key and gets the data instantly, without a second request.

Angular

ExperiencedMost asked
Answer

Explain Default vs OnPush change detection. When would you use OnPush?

Default change detection checks every component in the tree after any event, timer or HTTP response that Zone.js sees. OnPush checks a component only when something specific changes, which cuts work a lot in large trees.

An OnPush component is re-checked when:

  • an @Input reference changes (not a mutation of the same object),
  • an event handler in its own template fires,
  • an async pipe emits or a signal read in the template changes,
  • you call markForCheck() explicitly.
@Component({
  selector: 'app-row',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `{{ user().name }}`,
})
export class RowComponent { user = input.required<User>(); }

Use OnPush by default for presentational components, combined with immutable updates and signals or observables.

What they are checking: Whether you understand what triggers checks and how to keep data flow predictable

ExperiencedMost asked
Answer

What are Angular signals and why were they introduced?

A signal is a value that tells its users when it changes. So Angular knows exactly which views depend on which data. They were introduced to enable precise updates, simpler state code, and a path away from Zone.js.

const count = signal(0);
const double = computed(() => count() * 2);
count.set(2);          // double() is 4
count.update(n => n + 1);

Key points:

  • Read by calling the function: count().
  • computed is lazy, memoised and read-only.
  • effect runs side effects when dependencies change.
  • Signal inputs (input()), model(), and signal queries (viewChild()) are available in Angular 17.1 to 18+.
  • Signals work well with OnPush because the template registers the dependency.

What they are checking: Whether you grasp the reactivity model, not only the syntax

ExperiencedMost askedFree with sign-in
Answer

Explain switchMap, mergeMap, concatMap and exhaustMap and when to use each.

All four map each source value to an inner observable and flatten the results; they differ in how they handle overlapping inner observables.

ExperiencedMost askedFree with sign-in
Answer

What are HttpClient interceptors and what are they used for?

An interceptor sits between the app and the network. It can read or change every HTTP request and response. Typical uses are attaching auth tokens, global error handling, logging, loading indicators and retry.

ExperiencedMost askedFree with sign-in
Answer

How do you avoid memory leaks from RxJS subscriptions in Angular?

Make sure every long-lived subscription ends when the component is destroyed. The cleanest options are the async pipe, takeUntilDestroyed, or toSignal.

ExperiencedMost askedScenarioFree with sign-in
Answer

A page with a table of 10,000 rows is slow and janky. How do you fix it?

First measure with the Angular DevTools profiler and the Chrome Performance tab. Then reduce what is drawn and what is checked.

ExperiencedMost askedScenarioFree with sign-in
Answer

The app slows down and memory grows the longer a user stays on a dashboard. How do you investigate?

This pattern usually means leaked subscriptions, listeners or detached DOM. Confirm it with a heap comparison, then fix the code that owns them.

ExperiencedMost askedScenarioFree with sign-in
Answer

Build a search box that calls an API as the user types. How do you design it?

Use a form control stream with debounce, removal of repeated values and switchMap. Handle loading and errors without breaking the stream.

ExperiencedMost askedScenarioFree with sign-in
Answer

The initial load of your Angular app is slow. How do you reduce the bundle size and load time?

Measure first (Lighthouse, ng build --stats-json with a bundle analyser), then cut what ships and defer the rest.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between computed and effect in signals?

computed makes a new value from other signals and has no side effects. But effect runs code with side effects whenever the signals it reads change.

ExperiencedMost askedFree with sign-in
Answer

What are route guards and resolvers? How do functional guards look?

Guards decide whether navigation is allowed, and resolvers fetch data before the route activates. Since Angular 15 guards are plain functions that use inject().

ExperiencedMost askedFree with sign-in
Answer

How do you write a custom validator and an async validator for a reactive form?

A sync validator is a function that takes an AbstractControl and returns null when valid, or an error object when invalid. An async validator returns an observable or promise of the same.

ExperiencedMost askedFree with sign-in
Answer

What is the inject() function and how do injector hierarchies work?

inject() gets a dependency from the current injection context, such as a constructor, a field start value, a factory or a functional guard. You do not need constructor parameters. Angular resolves it by walking up a hierarchy of injectors.

ExperiencedMost askedFree with sign-in
Answer

What is Zone.js and what does zoneless Angular mean?

Zone.js patches async APIs (timers, events, promises, XHR) so Angular knows when to run change detection. Zoneless means Angular learns about changes from signals, markForCheck, events and the async pipe instead. So Zone.js can be removed.

ExperiencedMost askedFree with sign-in
Answer

How would you manage state in a large Angular application: services with signals or NgRx?

Start with signal-based services for local and feature state. Add NgRx (or NgRx SignalStore) when many features share complex state and you need a strict flow, devtools and managed side effects.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you implement automatic token refresh in an HTTP interceptor?

Catch 401 responses and refresh the token once. Hold the other failed requests until the refresh finishes. Then retry them with the new token.

ExperiencedMost askedScenarioFree with sign-in
Answer

You get ExpressionChangedAfterItHasBeenCheckedError. What causes it and how do you fix it?

It happens in development mode. A binding's value changes after Angular has already checked it in the same cycle. Usually a child or a lifecycle hook changes parent state during the check.

ExperiencedMost askedScenarioFree with sign-in
Answer

A form has dependent dropdowns (country, state, city) and fields that appear based on earlier answers. How do you build it?

Use a reactive form and drive the dependent controls from the parent control's valueChanges. Reset the children when the parent changes.

ExperiencedMost askedScenarioFree with sign-in
Answer

An OnPush component does not update after data arrives from a service. What do you check?

Check that the template is told something changed. OnPush only refreshes when an input reference changes, on template events, on async pipe or signal updates, or on markForCheck.

ExperiencedMost askedFree with sign-in
Answer

How do you unit test an Angular component that uses a service?

Set up TestBed with the standalone component and a fake provider for the service. Then check the drawn output and the calls.

ExperiencedMost askedScenarioFree with sign-in
Answer

You must migrate a large NgModule-based app to standalone components. How do you plan it?

Migrate step by step, because NgModules and standalone components work together. Use the schematic to do most of the routine work.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between ViewChild, ContentChild, and ng-content?

ng-content projects markup from a parent into a component's template. ViewChild queries elements in the component's own template. ContentChild queries elements that were projected into it.

ExperiencedMost askedFree with sign-in
Answer

What are deferrable views (@defer) in Angular?

@defer loads part of a template and its dependencies later, when a trigger fires. Angular puts that code into a separate chunk automatically.

ExperiencedMost askedFree with sign-in
Answer

What is Angular SSR and hydration, and what problems does it solve?

Server-side rendering (SSR) renders the page HTML on the server, so users and search crawlers get content immediately. Hydration then reuses that server DOM in the browser instead of rebuilding it.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between markForCheck and detectChanges?

markForCheck() marks a component and its parents to be checked in the next change detection cycle. You need this with OnPush. detectChanges() runs change detection on that component's view right now, synchronously.

ExperiencedMost askedScenarioFree with sign-in
Answer

Two sibling components need to react to the same data change. How do you design this?

Put the shared state in a service that both components inject. Expose it as a read-only signal or observable. Neither component should know about the other.

ExperiencedMost askedFree with sign-in
Answer

How do you create a custom form control that works with ngModel and reactive forms (ControlValueAccessor)?

Implement ControlValueAccessor and register it with the NG_VALUE_ACCESSOR token. Then the forms API can read and write the component's value.

Node.js

ExperiencedMost asked
Answer

Explain the phases of the Node.js event loop.

The event loop is run by libuv and cycles through phases, each with a queue of callbacks:

  1. timers: setTimeout and setInterval callbacks that are due.
  2. pending callbacks: some deferred system I/O callbacks.
  3. idle, prepare: internal.
  4. poll: retrieves new I/O events and runs their callbacks; it may wait here if nothing else is scheduled.
  5. check: setImmediate callbacks.
  6. close callbacks: for example socket.on('close').

Between each callback (and after each phase transition) Node drains process.nextTick first, then promise microtasks.

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("tick"));
Promise.resolve().then(() => console.log("promise"));
// tick, promise, then timeout/immediate (order of the last two varies in the main module)

Inside an I/O callback, setImmediate always fires before setTimeout.

What they are checking: Whether you can name the phases and ordering

ExperiencedMost asked
Answer

What is the difference between process.nextTick(), setImmediate() and setTimeout(fn, 0)?

  • process.nextTick(fn) runs right after the current operation, before the event loop continues and before promise microtasks. Overusing it can starve I/O.
  • setImmediate(fn) runs in the check phase, after the poll phase.
  • setTimeout(fn, 0) runs in the timers phase after at least 1 ms.

Order of priority: nextTick, then promise microtasks, then timers/immediates.

  • Use nextTick to run something after the current function but before any I/O. One example is emitting an event after you return the emitter.
  • Use setImmediate to yield to the event loop between chunks of work.
  • From the main module the order of setTimeout 0 and setImmediate is not guaranteed; inside an I/O callback setImmediate is always first.

What they are checking: Whether you know the queue order

ExperiencedMost askedScenario
Answer

Scenario: your Node.js service's memory keeps growing until it is killed (out of memory). How do you find and fix the leak?

Confirm it is a leak: memory climbs and does not drop after garbage collection. Then check process.memoryUsage() or metrics for heapUsed and RSS over time.

Find it:

  1. Run with node --inspect, connect Chrome DevTools, and take heap snapshots under load a few minutes apart. Use the Comparison view to see which object types grow. Then read what keeps them alive (their retainers).
  2. Or use --heapsnapshot-signal=SIGUSR2 in production-like environments, or tools such as clinic.js.

Typical causes:

  • Unbounded in-memory caches or maps keyed by user id.
  • Event listeners added per request and never removed (the "MaxListeners" warning is a hint).
  • Closures holding large request objects, global arrays that accumulate, timers never cleared.
  • Un-ended streams or unclosed connections.

Fix: bound caches (LRU with a max size and TTL) or move them to Redis, remove listeners, clear timers, close resources. Verify memory plateaus under load. Setting --max-old-space-size only delays the crash.

What they are checking: Whether you debug with heap snapshots, not guesses

ExperiencedMost askedScenario
Answer

Scenario: CPU usage is at 100% on one core and the API becomes slow. How do you diagnose and fix it?

Node runs your code on one thread, so a hot function blocks all requests.

Diagnose:

  • Capture a CPU profile: node --prof and node --prof-process, clinic flame, or Chrome DevTools via --inspect. Read the flame graph for the widest functions.
  • Check event loop lag (perf_hooks.monitorEventLoopDelay) and which endpoint correlates with the spike.

Common culprits and fixes:

  • Large JSON.parse/stringify, sorting or looping over big arrays: paginate, stream, or process in chunks with setImmediate.
  • Synchronous crypto or hashing: use async versions or worker threads.
  • Catastrophic regex backtracking: fix the pattern or limit input size.
  • Complex per-request computation: cache results, precompute, or move to a worker pool or separate service.

Then run one process per core (cluster or containers). That way one busy process does not take down all capacity. Add load tests to confirm the fix.

What they are checking: Whether you profile and know the single-thread consequence

ExperiencedMost asked
Answer

What are streams in Node.js? Why and when would you use them?

A stream processes data in chunks instead of loading it all into memory. There are four types: Readable, Writable, Duplex (both) and Transform (modify data while passing through).

const { pipeline } = require("stream/promises");
const fs = require("fs");
const zlib = require("zlib");

await pipeline(
  fs.createReadStream("input.log"),
  zlib.createGzip(),
  fs.createWriteStream("input.log.gz")
);

Use them for large files, uploads and downloads, HTTP request/response bodies, CSV processing and compression. Benefits: constant memory use and faster time to first byte. Use pipeline (not bare .pipe) so errors propagate and resources are cleaned up. Streams support backpressure: when the consumer is slow, write() returns false and the source pauses until drain.

What they are checking: Whether you can handle big data without exhausting memory

ExperiencedMost asked
Answer

What is the difference between the cluster module, worker threads and child processes?

All three use more CPU cores, but in different ways.

clusterworker_threadschild_process
UnitMultiple Node processes sharing a server portThreads in one processSeparate OS process (any program)
MemorySeparateCan share via SharedArrayBufferSeparate
Best forScaling an HTTP server across coresCPU-bound JavaScript workRunning shell commands or other programs
CommunicationIPC messagespostMessage, shared memoryIPC, stdio
const { Worker, isMainThread, parentPort, workerData } = require("worker_threads");
if (isMainThread) {
  new Worker(__filename, { workerData: 40 }).on("message", console.log);
} else {
  const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
  parentPort.postMessage(fib(workerData));
}

In production, cluster is often replaced by PM2 or containers with one process each behind a load balancer.

What they are checking: Whether you pick the right tool for I/O versus CPU work

ExperiencedMost asked
Answer

How do you handle errors in Express, including async errors?

Use a central error-handling middleware with four arguments, registered last. Synchronous throws inside route handlers reach it automatically. In Express 4, rejected promises from async handlers do not, so wrap them or call next(err). Express 5 forwards rejected promises automatically.

const wrap = (fn) => (req, res, next) => fn(req, res, next).catch(next);

app.get("/users/:id", wrap(async (req, res) => {
  const user = await db.find(req.params.id);
  if (!user) { const e = new Error("Not found"); e.status = 404; throw e; }
  res.json(user);
}));

app.use((err, req, res, next) => {
  const status = err.status || 500;
  res.status(status).json({ error: status === 500 ? "Internal error" : err.message });
});

Also: create custom error classes, log with context, and never leak stack traces to clients. Handle unhandledRejection and uncaughtException at process level, to log the error and exit cleanly.

What they are checking: Whether you handle async errors and avoid leaking details

ExperiencedMost askedFree with sign-in
Answer

How does JWT authentication work in a Node.js API?

A JSON Web Token is a signed token with a header, payload (claims such as sub, exp) and signature. The server signs it after login; the client sends it on each request; the server verifies the signature and expiry without a session lookup.

ExperiencedMost askedFree with sign-in
Answer

How do you secure a Node.js / Express application?

Layered measures:

ExperiencedMost askedFree with sign-in
Answer

How would you scale a Node.js application?

Scale vertically first, then horizontally, and remove bottlenecks before adding servers.

ExperiencedMost askedFree with sign-in
Answer

How do you handle unhandled rejections and uncaught exceptions, and implement graceful shutdown?

After an uncaughtException the process state may be inconsistent, so log it and exit; let a supervisor (PM2, Docker, Kubernetes) restart it. Since Node 15, unhandled promise rejections also crash the process by default.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: an endpoint is fast in testing but slow under load, with high p99 latency. How do you investigate?

Work from measurement to cause.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: users upload a 2 GB CSV that must be parsed and loaded into the database. How do you design it in Node.js?

Never buffer the whole file in memory. Stream it end to end and batch the writes.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: how would you implement rate limiting per user for your Node.js API, running on several instances behind a proxy?

Counters must be shared across instances, so use a central store (Redis), not in-memory counters per process.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: deploying a new version drops in-flight requests and users see errors. How do you get zero-downtime deployments?

Combine graceful shutdown with a rolling or blue-green deploy.

ExperiencedMost askedFree with sign-in
Answer

How does libuv and its thread pool fit into Node.js?

libuv is the C library that provides Node's event loop and asynchronous I/O across operating systems. Network I/O uses OS facilities (epoll, kqueue, IOCP) directly. Operations with no async OS API are run on libuv's thread pool, which has 4 threads by default.

ExperiencedMost askedFree with sign-in
Answer

How would you add caching with Redis to a Node.js API?

Use the cache-aside pattern: check Redis, on a miss read the database and store the result with a TTL.

ExperiencedMost askedFree with sign-in
Answer

What is connection pooling and why does it matter for database access?

Opening a database connection is slow and databases limit concurrent connections. A pool keeps a set of open connections and lends them out, reusing them across requests.

ExperiencedMost askedFree with sign-in
Answer

How do you test a Node.js API?

Use layers of tests.

ExperiencedMost askedFree with sign-in
Answer

How do you do logging and monitoring in a Node.js service?

Use structured (JSON) logs and send them to a central system.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: traffic suddenly spikes 10x because of a campaign. How do you keep the Node.js service up?

Act in layers, fastest wins first.

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: the server stops responding intermittently, yet CPU and memory look normal. What could be wrong?

Likely suspects:

ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: a JWT was leaked or a user must be logged out immediately. How do you handle token revocation?

Stateless JWTs are valid until they expire, so revocation needs extra design.

ExperiencedMost askedFree with sign-in
Answer

What is backpressure in Node.js streams, and how do you handle it?

Backpressure happens when a producer writes data faster than a consumer can handle. Without control, buffered data piles up in memory.

A writable stream signals this: write() returns false when its internal buffer passes highWaterMark. The producer should pause until the drain event, then resume.

ExperiencedFree with sign-in
Answer

What is the difference between spawn, exec, execFile and fork in child_process?

All start another process, but with different output handling.

ExperiencedFree with sign-in
Answer

What useful features have been added to recent Node.js versions?

Recent LTS releases reduced the need for extra packages:

C# and .NET

ExperiencedMost asked
Answer

What happens when you call .Result or .Wait() on a Task? What is the sync-over-async deadlock?

They block the calling thread until the task completes. In an environment with a synchronization context (classic ASP.NET, WinForms, WPF), this can deadlock.

The deadlock: the UI or request thread calls GetAsync().Result and blocks. Inside, the code after await tries to resume on that same saved context. But the thread is blocked waiting, so neither can move on.

// Risky in UI / legacy ASP.NET
var data = LoadAsync().Result;

// Fix: async all the way
var data2 = await LoadAsync();

// In library code: do not capture the context
await SomeCallAsync().ConfigureAwait(false);

ASP.NET Core has no synchronization context, so this exact deadlock does not happen there. But blocking still wastes pool threads and can leave no free threads under load. Rule: go async all the way, avoid .Result, .Wait() and GetAwaiter().GetResult(), and use ConfigureAwait(false) in general-purpose libraries.

What they are checking: A favourite senior question: whether you know the cause, not just the slogan

ExperiencedMost askedFree with sign-in
Answer

What is the N+1 query problem in EF Core and how do you fix it?

N+1 means one query loads N parents, then one extra query per parent loads related data, giving N+1 round trips.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between clustered and non-clustered indexes in SQL Server, and how do you find out why a query is slow?

A clustered index sets the physical order of the table rows. So a table has only one (the primary key by default). A non-clustered index is a separate structure. It holds the key columns plus a pointer (the clustering key) to the row. A table can have many.

ExperiencedMost askedFree with sign-in
Answer

How do you use AI coding assistants (Copilot, Cursor, Claude Code) in daily .NET work? How do you make sure the output is reliable?

Use them as a fast pair programmer, and keep ownership of design and verification.

ExperiencedMost askedScenarioFree with sign-in
Answer

An ASP.NET Core API is slow under load. How do you diagnose and fix it?

Measure first, find the bottleneck layer, then fix and verify.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between Task and Thread? What is the difference between Task.Run and async/await?

A Thread is an OS thread you manage yourself. A Task is a higher-level unit of work scheduled on the thread pool. It may not even use a thread while it waits for I/O.

ExperiencedMost askedFree with sign-in
Answer

Why should you avoid async void? And how do you run several async operations in parallel?

async void cannot be awaited, and exceptions thrown in it cannot be caught by the caller. They are raised on the synchronization context and can crash the process. Use it only for event handlers.

ExperiencedMost askedScenarioFree with sign-in
Answer

A singleton service depends on a scoped service, such as a DbContext. What goes wrong and how do you fix it?

This is the captive dependency problem. The singleton holds the first scoped instance forever, so a DbContext is shared across requests and threads. It is not thread safe, it caches tracked entities (stale data) and grows without bound.

ExperiencedMost askedFree with sign-in
Answer

How do you handle errors globally in an ASP.NET Core Web API?

Use the exception handling middleware, and in .NET 8 an IExceptionHandler that returns RFC 7807 ProblemDetails.

ExperiencedMost askedFree with sign-in
Answer

How does authentication with JWT work in ASP.NET Core?

The client logs in, the server issues a signed JWT, and the client sends it as Authorization: Bearer <token> on later requests. The JWT bearer middleware validates the signature, issuer, audience and expiry, and builds the ClaimsPrincipal.

ExperiencedMost askedFree with sign-in
Answer

How do you use IHttpClientFactory and why not create a new HttpClient each time?

Creating a new HttpClient() per request can exhaust sockets (ports stay in TIME_WAIT), while a single static client never refreshes DNS. IHttpClientFactory pools and recycles the underlying handlers and gives you named or typed clients with policies.

ExperiencedMost askedFree with sign-in
Answer

Explain agentic workflows, sub-agents, spec-driven development and MCP in the context of AI-assisted coding.

These are patterns for letting AI tools do larger, more reliable pieces of work.

ExperiencedMost askedScenarioFree with sign-in
Answer

What is wrong with this code? for (int i = 0; i < 3; i++) tasks.Add(Task.Run(() => Console.WriteLine(i)));

Many closures read the loop variable after the loop has advanced, so you may see repeated or unexpected values.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your .NET service's memory grows until the container is killed. How do you find the leak?

Find what is kept in memory, using dumps and counters. Then fix the root cause.

ExperiencedMost askedScenarioFree with sign-in
Answer

After a release, an endpoint returns HTTP 500 intermittently for a few users only. How do you troubleshoot it?

Treat it as an evidence hunt: narrow what the failing requests have in common.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you stop duplicate order submissions when a user double-clicks or a client retries a POST request?

Make the operation idempotent on the server, and do not rely only on disabling the button.

ExperiencedMost askedFree with sign-in
Answer

How do you handle concurrency and transactions in EF Core?

SaveChanges runs inside one transaction by default. For multi-step work, use a transaction that you start yourself. For concurrent edits use optimistic concurrency.

ExperiencedMost askedFree with sign-in
Answer

How would you implement pagination in SQL Server and in EF Core?

Use OFFSET ... FETCH with a deterministic ORDER BY. For deep pages or feeds use keyset pagination.

ExperiencedMost askedFree with sign-in
Answer

What are records, init-only properties and primary constructors in modern C#?

Modern C# adds concise ways to model data.

ExperiencedMost askedFree with sign-in
Answer

Write a thread-safe producer-consumer example in C#.

Use System.Threading.Channels, the modern async-friendly bounded queue, instead of manual locks.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you run background jobs in ASP.NET Core?

Use a hosted service for in-process work, and a durable job system when jobs must survive restarts.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you migrate a legacy .NET Framework application to .NET 8?

Migrate incrementally and keep the system running, rather than a risky big-bang rewrite.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between Minimal APIs and controllers in ASP.NET Core?

Both build HTTP endpoints on the same pipeline. Minimal APIs are lightweight and function based, while controllers are class based with more built-in conventions.

OOP

ExperiencedMost askedFree with sign-in
Answer

Composition vs inheritance: which do you prefer and why?

Prefer composition ("has-a") over inheritance ("is-a") unless there is a genuine subtype relationship.

ExperiencedMost askedFree with sign-in
Answer

What is the Observer pattern? Give a real-world use.

Observer defines a one-to-many dependency: when a subject changes state, all its registered observers are notified automatically, with no tight coupling between them.

ExperiencedMost askedFree with sign-in
Answer

What is the Liskov Substitution Principle? Give an example of breaking it.

If S is a subtype of T, you can use objects of S in place of objects of T without breaking the program. A subclass must honour the parent's contract: same preconditions or weaker, same postconditions or stronger, no new exceptions.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between Dependency Inversion and Dependency Injection?

Dependency Inversion (the D in SOLID) is a design principle: high-level modules should depend on abstractions, not on concrete low-level classes. Dependency Injection (DI) means giving a class the objects it needs from outside (constructor, setter or framework). The class does not create them inside with new.

ExperiencedMost askedFree with sign-in
Answer

How do you create an immutable class in Java, and why would you?

Immutable objects cannot change after they are built. So they are thread-safe by default, safe as map keys and easy to understand (String, Integer, LocalDate).

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you replace a long if/else or switch on object type with polymorphism?

Move each branch's behaviour into a class that implements a shared interface, and let dynamic dispatch pick the branch.

Before:

ExperiencedMost askedScenarioFree with sign-in
Answer

Design the classes for a parking lot system. How do you approach it?

Clarify requirements first: vehicle types, number of levels, pricing, entry and exit, payment, capacity display.

ExperiencedMost askedScenarioFree with sign-in
Answer

You must add a new payment method without modifying existing checkout code. How would you design it?

Apply Open/Closed with a Strategy interface and a registry.

ExperiencedMost askedScenarioFree with sign-in
Answer

Design a notification system where users choose email, SMS or push, and new channels will be added later.

Use Strategy for channels. Use a factory or registry to look them up. Use Observer if one event goes to many subscribers.

ExperiencedMost askedFree with sign-in
Answer

When would you use an abstract class and when an interface in a real project?

Use an interface to describe a capability that unrelated classes can offer and that callers depend on: PaymentGateway, Repository, Comparable. It keeps coupling low and makes mocks easy.

ExperiencedMost askedFree with sign-in
Answer

What is the diamond problem, and how do Java and Python handle it?

The diamond problem appears with multiple inheritance: D inherits from B and C, which both inherit from A. If B and C override a method differently, which version does D get?

ExperiencedMost askedFree with sign-in
Answer

What is the Interface Segregation Principle?

Clients should not be forced to depend on methods they do not use. Prefer several small, focused interfaces over one large one.

Example of breaking it:

ExperiencedMost askedFree with sign-in
Answer

How does run-time polymorphism work internally?

It uses dynamic dispatch. In Java each class has a method table (vtable). Every object carries a reference to its class. For an overridden method call, the JVM looks up the method in the real object's class at run time, not in the declared reference type.

ExperiencedMost askedFree with sign-in
Answer

How does Method Resolution Order (MRO) work in Python, and what does super() do?

MRO is the order Python searches classes for an attribute. It uses C3 linearisation, which keeps each class before its parents and preserves the order of bases as written. Class.__mro__ or Class.mro() shows it.

ExperiencedMost askedFree with sign-in
Answer

What are __init__, __new__ and other dunder methods in Python?

Dunder (double underscore) methods let your class plug into Python's syntax and built-ins.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between shallow copy and deep copy of an object?

A shallow copy creates a new outer object but the nested objects are shared with the original. A deep copy recursively copies everything, so the two are independent.

ExperiencedMost askedFree with sign-in
Answer

What is the Strategy pattern and how does it relate to the Open/Closed Principle?

Strategy defines a family of interchangeable algorithms behind one interface and lets the caller pick one at run time. The context holds a reference to the interface and delegates.

ExperiencedMost askedFree with sign-in
Answer

What is the Decorator pattern, and how is it different from a Python decorator?

The Decorator design pattern wraps an object with another that has the same interface to add behaviour dynamically, without subclassing. Example: BufferedReader(new FileReader(...)).

ExperiencedMost askedFree with sign-in
Answer

What is the Builder pattern and when is it useful?

Builder constructs a complex object step by step and produces it at the end. It is useful when a class has many optional parameters, or construction must be validated as a whole.

ExperiencedMost askedFree with sign-in
Answer

What are records and sealed classes in modern Java, and how do they help OOP design?

Record (Java 16): a compact immutable data carrier. The compiler generates the constructor, accessors, equals, hashCode and toString.

ExperiencedMost askedScenarioFree with sign-in
Answer

A subclass overrides a method and throws an exception for operations it cannot support, breaking callers. What do you do?

This breaks the Liskov Substitution rule: the child cannot honestly stand in for the parent.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your Singleton makes unit tests hard because state leaks between tests. How do you fix it?

The problem is hidden global state plus hard-wired access.

ExperiencedMost askedScenarioFree with sign-in
Answer

A class hierarchy has become five levels deep and every change breaks subclasses. How do you untangle it?

This is the fragile base class problem. Approach:

ExperiencedMost askedScenarioFree with sign-in
Answer

A constructor now takes eight parameters and many are optional. How do you clean it up?

This is the telescoping constructor smell. Options:

ExperiencedMost askedScenarioFree with sign-in
Answer

You find a God class with 3000 lines that everything depends on. How do you break it down safely?

Plan:

  1. Add tests around the public behaviour (characterisation tests), even rough ones.
  2. Group methods and fields by the data they touch. Clusters that use separate fields are separate responsibilities.
  3. Extract classes one at a time (Extract Class refactoring). Move a cluster and its fields to a new...

Data Structures and Algorithms

ExperiencedMost asked
Answer

How does HashMap work internally in Java?

HashMap is an array of buckets. For put(key, value):

  1. Compute key.hashCode() and spread its bits.
  2. Find the bucket index (hash & (capacity - 1); capacity is a power of two).
  3. If the bucket is empty, store a node. Otherwise compare keys with equals; replace the value if equal, else append to the chain.
  4. Since Java 8, a chain longer than 8 (with table size at least 64) turns into a red-black tree. So the worst-case lookup is O(log n) instead of O(n).
  5. When size exceeds capacity * 0.75, the table doubles and entries are redistributed.

Consequences: keys need matching equals/hashCode. If you change a key after inserting it, you lose it. The iteration order is not guaranteed. It is not thread-safe (use ConcurrentHashMap). A null key is allowed (bucket 0). Initial capacity matters if you know the size, to avoid rehashing.

What they are checking: Internals knowledge that interviewers love

ExperiencedMost askedFree with sign-in
Answer

How do AVL and Red-Black trees keep a BST balanced?

Both are self-balancing BSTs that keep height O(log n) so every operation stays O(log n).

ExperiencedMost askedFree with sign-in
Answer

What is Dijkstra's algorithm? What is its complexity and its limitation?

Dijkstra finds the shortest path from one source to all vertices in a graph with non-negative edge weights. It greedily picks the unvisited vertex with the smallest known distance (using a min-heap), then relaxes its outgoing edges.

ExperiencedMost askedFree with sign-in
Answer

How would you find the k-th largest element in an unsorted array?

Options:

  1. Sort: O(n log n). Simple, fine for small inputs.
  2. Min-heap of size k: push each element, pop when size exceeds k. Result is the heap root. O(n log k) time, O(k) space. Best for streams.
  3. Quickselect: partition around a pivot like quick sort but recurse into one side only. Average O(n), worst O(n^2) (random pivot makes this unlikely). Modifies the array.
ExperiencedMost askedFree with sign-in
Answer

What is the two pointers technique, and what is the sliding window technique?

Two pointers: two indices move through a sequence (often one from each end, or a slow one and a fast one). This avoids a nested loop. Typical for sorted arrays: pair sum, removing duplicates, reversing, partitioning. Turns O(n^2) into O(n).

ExperiencedMost askedScenarioFree with sign-in
Answer

Which data structure would you use to power an autocomplete feature?

A trie keyed by characters supports prefix lookup in O(L). Store a small list of top suggestions at each node (worked out in advance by frequency). Then a query returns results without walking the whole subtree.

ExperiencedMost askedScenarioFree with sign-in
Answer

You need the top 10 most frequent items in a stream of a billion records. It does not fit in memory. How do you do it?

Exact counting needs memory proportional to distinct items. Options:

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you find the shortest connection path between two users in a social network of millions of users?

Model users as vertices and friendships as edges (unweighted, undirected). Use BFS from the source: the first time you reach the target is the shortest path, in O(V + E).

ExperiencedMost askedFree with sign-in
Answer

Explain how an LRU cache is built from data structures and why.

LRU needs O(1) lookups and O(1) "move to most recent" and "evict oldest". One structure cannot do both:

  • A hash map gives O(1) lookup by key.
  • A doubly linked list keeps usage order; moving or removing a known node is O(1).
ExperiencedMost askedFree with sign-in
Answer

What is topological sorting and where is it used?

A topological order of a directed acyclic graph (DAG) lists the vertices so that for every edge u -> v, u comes before v. It exists only if the graph has no cycle.

Uses: build systems, course prerequisites, task scheduling, package dependency resolution.

ExperiencedMost askedFree with sign-in
Answer

How do you detect a cycle in a directed graph versus an undirected graph?

Undirected graph: DFS or BFS and look for a visited neighbour that is not the node's parent. Or use Union-Find: if an edge joins two vertices already in the same set, there is a cycle.

ExperiencedMost askedFree with sign-in
Answer

What is a trie and when would you use it?

A trie (prefix tree) stores strings character by character: each node is a character and a path from the root spells a prefix. Lookup, insert and prefix search take O(L), where L is the string length, independent of how many words are stored.

ExperiencedMost askedFree with sign-in
Answer

What is Union-Find (Disjoint Set Union) and what operations does it support?

Union-Find tracks a partition of elements into disjoint sets. Operations: find(x) returns the set representative, union(a, b) merges two sets. With path compression and union by rank, each operation is almost O(1) (inverse Ackermann).

ExperiencedMost askedFree with sign-in
Answer

Explain the 0/1 knapsack problem and its dynamic programming solution.

Given items with weights and values and a capacity W, choose a subset with maximum total value. The total weight must not exceed W. Each item is used at most once.

State: dp[w] = best value with capacity w. Iterate items, and iterate capacity downward so each item is used once.

ExperiencedMost askedFree with sign-in
Answer

How does heap sort work, and why is building a heap O(n)?

Heap sort: build a max-heap from the array. Then swap the root (largest) with the last unsorted element, make the heap one smaller, and sift down. Repeat. Result is ascending, in place: O(n log n) time in all cases, O(1) extra space, not stable.

ExperiencedMost askedFree with sign-in
Answer

What is amortized analysis? Give an example other than dynamic arrays.

Amortized analysis spreads the cost over a sequence of operations, even in the worst case. A rare expensive operation is shared by many cheap ones. It is not probabilistic.

ExperiencedMost askedFree with sign-in
Answer

What is load factor in a hash table and what happens when it gets too high?

Load factor = number of entries / number of buckets. A high load factor means more collisions: chains get longer (or probe sequences grow), pushing operations from O(1) toward O(n).

ExperiencedMost askedFree with sign-in
Answer

Explain Kruskal's and Prim's algorithms for a minimum spanning tree.

A minimum spanning tree (MST) connects all vertices of a weighted undirected graph. It has the smallest total edge weight and no cycles.

ExperiencedMost askedFree with sign-in
Answer

Why do databases use B-trees instead of binary search trees?

Disk and SSD reads fetch whole pages, so the cost is the number of page reads, not comparisons. A binary tree has height log2(n), which means many reads. A B-tree node holds hundreds of keys (one page), so the tree is very wide and shallow. With 500 keys per node, 100 million rows need only about 3 or 4 levels.

ExperiencedMost askedScenarioFree with sign-in
Answer

A sorted list needs frequent inserts and deletes while still supporting fast search. Which structure do you pick?

A sorted array gives O(log n) search but O(n) insert/delete because of shifting. A plain linked list gives O(1) insert but O(n) search.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your BST based lookup suddenly became slow after loading data from a sorted file. What happened and how do you fix it?

Inserting keys in sorted order into a plain BST creates a lopsided tree. Every node has only a right child, so it behaves like a linked list. Height becomes n and operations degrade from O(log n) to O(n).

ExperiencedMost askedScenarioFree with sign-in
Answer

You have to detect duplicates in a file with 100 million IDs but have only a little memory. What are your options?

Options by constraint:

  1. External sort: sort chunks that fit in memory, write them out, k-way merge, and compare neighbours. O(n log n) with sequential disk I/O, exact.
  2. Hash partitioning: split IDs into buckets on disk by hash(id) % B, so duplicates fall in the same bucket. Then check each bucket in...
ExperiencedMost askedScenarioFree with sign-in
Answer

Design the data structure for an undo/redo feature in a text editor.

Use two stacks of commands (Command pattern).

ExperiencedMost askedScenarioFree with sign-in
Answer

Your task scheduler must always run the highest priority job first, with new jobs arriving constantly. What do you use?

A priority queue implemented with a binary heap: insert and pop-highest are both O(log n), peek is O(1). A sorted list would make inserts O(n).

Coding

ExperiencedMost askedFree with sign-in
Answer

Find the longest substring without repeating characters.

Sliding window with a map of the last seen index of each character. When a repeat is inside the window, move the left edge past the previous occurrence.

ExperiencedMost askedFree with sign-in
Answer

Find the maximum subarray sum (Kadane's algorithm).

At each element, either extend the current subarray or start fresh, whichever is larger. Track the best seen.

ExperiencedMost askedScenarioFree with sign-in
Answer

Implement an LRU cache with O(1) get and put.

Combine a hash map (O(1) lookup) with a structure that tracks recency. In Python, OrderedDict is a hash map plus doubly linked list, with move_to_end and popitem.

ExperiencedMost askedFree with sign-in
Answer

Group a list of words into anagram groups.

Use a canonical key for each word: its sorted letters. Words with the same key are anagrams.

ExperiencedMost askedFree with sign-in
Answer

Merge overlapping intervals.

Sort by start. Then walk through: if the next interval starts before or at the end of the last merged one, extend the end. Otherwise, start a new interval.

ExperiencedMost askedFree with sign-in
Answer

Climbing stairs: how many distinct ways to climb n steps taking 1 or 2 at a time?

The number of ways to reach step n is the sum of the ways to reach n-1 and n-2. This is the Fibonacci pattern.

ExperiencedMost askedFree with sign-in
Answer

Coin change: find the minimum number of coins to make an amount.

Bottom-up DP: dp[a] is the minimum coins for amount a. For each amount try every coin. Greedy fails for some coin sets (for example coins 1, 3, 4 and amount 6).

ExperiencedMost askedFree with sign-in
Answer

Product of array except self, without using division.

For each index, the answer is the product of everything to its left times everything to its right. Compute prefix products going forward, then multiply by suffix products going back.

ExperiencedMost askedFree with sign-in
Answer

3Sum: find all unique triplets that add up to zero.

Sort the array. For each index i, use two pointers on the rest to find pairs that sum to -a[i]. Skip duplicates to keep results unique.

ExperiencedMost askedFree with sign-in
Answer

Best time to buy and sell a stock for maximum profit (one transaction).

Scan once, tracking the lowest price so far and the best profit if you sold today.

ExperiencedMost askedFree with sign-in
Answer

Level-order traversal of a binary tree.

Use BFS with a queue. Process one level at a time by reading the queue length before looping.

ExperiencedMost askedFree with sign-in
Answer

Find the maximum depth of a binary tree, and invert it.

Both are short recursions: depth is 1 + max of child depths; inversion swaps children at every node.

ExperiencedMost askedFree with sign-in
Answer

Validate whether a binary tree is a valid BST.

Pass down the allowed range for each node. Checking only the immediate children is a common bug, because a deep node must obey every ancestor.

ExperiencedMost askedFree with sign-in
Answer

Find the top K frequent elements in an array.

Count with a Counter. Then take the K most common using a heap (O(n log k)), or a bucket sort by frequency (O(n)).

ExperiencedMost askedFree with sign-in
Answer

Count the number of islands in a 2D grid of 1s and 0s.

Scan the grid. When you find an unvisited 1, count one island and flood fill it (DFS or BFS) marking all connected land.

ExperiencedMost askedScenarioFree with sign-in
Answer

Design a stack that supports push, pop, top and get-minimum, all in O(1).

Keep a second stack (or store pairs) that tracks the minimum at each depth. Every push records the smaller of the new value and the current minimum.

ExperiencedMost askedScenarioFree with sign-in
Answer

Implement a queue using two stacks.

Use an input stack for pushes and an output stack for pops. When the output stack is empty, move everything over, which reverses the order to FIFO.

ExperiencedMost askedScenarioFree with sign-in
Answer

Design a rate limiter that allows at most N requests per user per minute.

Use a sliding window log per user: keep the timestamps of recent requests in a deque. Drop the ones older than the window. Allow the request if fewer than N remain.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you verify and take ownership of code that an AI assistant generated for you?

Treat AI output like code from a new teammate: useful, but unreviewed. I never merge what I cannot explain line by line.

ExperiencedMost askedFree with sign-in
Answer

Find the majority element (appears more than n/2 times).

Boyer-Moore voting: keep a candidate and a counter. Matching element increments, different one decrements; when the counter hits zero pick a new candidate. A true majority always survives.

ExperiencedMost askedFree with sign-in
Answer

Find the longest palindromic substring.

Expand around every possible centre (n odd-length and n-1 even-length centres) and keep the longest.

ExperiencedMost askedScenarioFree with sign-in
Answer

Find the median of a stream of numbers (running median).

Keep two heaps: a max-heap for the lower half and a min-heap for the upper half, sizes balanced within one. The median is the top of the larger heap, or the average of both tops.

ExperiencedMost askedScenarioFree with sign-in
Answer

Design a hit counter that returns the number of hits in the last 5 minutes.

Store timestamps in a deque (hits arrive in time order). On each query, drop entries older than 300 seconds and return the length. For very high traffic, count into per-second buckets in a fixed array of 300 slots.

ExperiencedMost askedScenarioFree with sign-in
Answer

Design an in-memory key-value store where entries expire after a TTL.

Store (value, expires_at) in a dict. Check expiry lazily on reads. A background sweep (or heap ordered by expiry) removes dead entries so memory does not grow without bound.

ExperiencedMost askedScenarioFree with sign-in
Answer

Implement encode and decode for a URL shortener using base62.

Give each URL an auto-increment ID (from a database sequence or a distributed ID generator). Then encode the ID in base62 (0-9, a-z, A-Z). Decoding reverses it. This avoids collisions and gives short codes: 7 characters cover 62^7, about 3.5 trillion IDs.

ExperiencedMost askedFree with sign-in
Answer

Given a sorted rotated array, how do you search for a target in O(log n)?

Modified binary search: at each step one half is always sorted. Check whether the target lies in the sorted half. If not, throw that half away.

ExperiencedMost askedFree with sign-in
Answer

Find the length of the longest increasing subsequence.

Patience sorting with binary search: keep tails[i], the smallest possible tail of an increasing subsequence of length i + 1. For each number, replace the first tail that is greater or equal, or append.

ExperiencedMost askedScenarioFree with sign-in
Answer

A discount or bill amount must be split across line items in proportion to their prices. No money may be lost to rounding. How do you do it?

Work in the smallest currency unit (integer cents or paisa), so there is no floating point error. Work out each share with integer division. Then give out the leftover units one by one, so the shares add up exactly to the total. This is the largest remainder method.

REST API

ExperiencedMost asked
Answer

What is OAuth 2.0 and which grant types exist?

OAuth 2.0 is an authorization framework. It lets an app use a user's data on another service without getting the user's password. It gives the app an access token with limited permissions (scopes).

Roles: resource owner (user), client (app), authorization server, resource server (API).

Main flows:

  • Authorization Code with PKCE: for web, mobile and SPA apps. The user logs in at the provider, and the app trades a code for tokens. This is the recommended default.
  • Client Credentials: service-to-service, no user involved.
  • Refresh Token: gets new access tokens without a new login.
  • Device Code: for TVs and CLIs without a browser.
  • Implicit and Resource Owner Password flows are old and should be avoided.

OAuth 2.0 handles authorization. OpenID Connect adds an ID token on top, for login ("Sign in with Google").

What they are checking: Flow choice and the OAuth versus OIDC distinction

ExperiencedMost askedFree with sign-in
Answer

How do you version a REST API?

Versioning lets you change the API without breaking existing clients. Common strategies:

ExperiencedMost askedFree with sign-in
Answer

What is rate limiting and how would you implement it in an API?

Rate limiting limits how many requests a client can make in a time window. It protects the service from abuse and overload.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between REST, GraphQL and gRPC? When would you choose each?

RESTGraphQLgRPC
StyleResources over HTTPSingle endpoint, client-defined queriesRemote calls with Protocol Buffers
TransportHTTP/1.1 or 2, JSONHTTP, JSONHTTP/2, binary
Over/under-fetchingCommonSolved, client picks fieldsFixed messages
CachingEasy...
ExperiencedMost askedFree with sign-in
Answer

How do you handle errors in a REST API? What should an error response look like?

Use the correct status code and a consistent body that programs can read. The standard format is Problem Details (RFC 9457, previously 7807):

ExperiencedMost askedScenarioFree with sign-in
Answer

Design a REST API for a simple blog with posts and comments.

Resources: posts and comments (comments belong to a post).

ExperiencedMost askedScenarioFree with sign-in
Answer

Design the API for an order and payment flow so a network retry never charges a customer twice.

Use idempotency keys on the non-idempotent POST calls.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you secure a REST API?

Use many layers of defence:

ExperiencedMost askedScenarioFree with sign-in
Answer

An endpoint that lists orders is slow under load. How do you improve its performance?

First find the slow part with tracing, logs and database EXPLAIN. Then use the cheapest fix that works.

ExperiencedMost askedScenarioFree with sign-in
Answer

A frontend developer says the API works in Postman but fails in the browser with a CORS error. How do you debug it?

Postman does not enforce CORS. The browser does. So the problem is in the server response headers.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between OAuth 2.0 and OpenID Connect?

OAuth 2.0 answers "what may this app access?" and produces an access token for APIs. OpenID Connect (OIDC) is a small identity layer on top of OAuth 2.0. It answers "who is the user?". It gives an ID token (a JWT) with details about the user.

ExperiencedMost askedFree with sign-in
Answer

Where should a client store a JWT or token in a web app?

There is no perfect place; choose by threat model.

ExperiencedMost askedFree with sign-in
Answer

What is a CORS preflight request?

A preflight is an automatic OPTIONS request. The browser sends it before the real request when the call is not simple. For example, when it uses PUT/DELETE, a JSON Content-Type, or an Authorization header.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you handle a long-running operation in a REST API, such as generating a large report?

Do not keep the HTTP connection open. Use the asynchronous request-reply pattern.

ExperiencedMost askedFree with sign-in
Answer

How does HTTP caching work for APIs? Explain Cache-Control.

Caching reuses saved responses to cut delay and load. The server controls it with headers.

ExperiencedMost askedFree with sign-in
Answer

What is an API gateway and what does it do?

An API gateway is one entry point in front of the backend services. It handles shared jobs, so each service does not have to.

ExperiencedMost askedScenarioFree with sign-in
Answer

What is the N+1 problem in APIs and how do you fix it?

The N+1 problem happens when you fetch a list and then run one extra query for each item to load related data. For example, 100 orders with their customers become 101 queries.

ExperiencedMost askedScenarioFree with sign-in
Answer

Your mobile app versions cannot be forced to update, but the API needs a breaking change. What do you do?

Keep old clients working while new ones move over.

ExperiencedMost askedFree with sign-in
Answer

What are the advantages and disadvantages of GraphQL?

Advantages:

  • Clients ask for exactly the fields they need. This removes extra data and extra round trips.
  • One endpoint and a typed schema, with good tools.
  • You can change it without versions by marking old fields as deprecated.
ExperiencedMost askedFree with sign-in
Answer

What is HATEOAS?

HATEOAS stands for Hypermedia As The Engine Of Application State. Responses include links that tell the client what it can do next. The client follows the links instead of fixing the URLs in its code.

ExperiencedMost askedFree with sign-in
Answer

What is an ETag and how is it used for caching and concurrency control?

An ETag is an identifier for one version of a resource (often a hash or a version number). It is returned in the ETag header.

Caching with conditional GET:

GET /products/5
-> 200, ETag: "v7"
GET /products/5
If-None-Match: "v7"
-> 304 Not Modified (no body, saves bandwidth)
ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design bulk operations, such as importing 10,000 users through an API?

Do not send 10,000 separate requests. Do not send one request that times out.

ExperiencedMost askedFree with sign-in
Answer

What is idempotency key best practice for retrying failed requests on the client side?

Retry only when it is safe, and spread the retries out.

ExperiencedMost askedFree with sign-in
Answer

How would you design an API that is easy for other developers to use?

Treat the API like a product.

ExperiencedMost askedFree with sign-in
Answer

What is PKCE in OAuth 2.0, and why do single-page and mobile apps need it?

PKCE (Proof Key for Code Exchange, said "pixie") protects the authorization code flow. It is for apps that cannot keep a secret, such as browser and mobile apps. It stops an attacker who steals the authorization code from trading it for tokens.

ExperiencedFree with sign-in
Answer

How do caching and federation work in an Apollo GraphQL setup, and what problems do they solve?

Caching happens at several levels:

  • Client: Apollo Client keeps one cache entry per object, found by its type and id. When an object changes, every query that shows it updates. Fetch policies such as cache-first and network-only decide when it asks the server.
  • Server: cache hints per field and...

Django and FastAPI

ExperiencedMost asked
Answer

What is the N+1 query problem in Django and how do you fix it?

N+1 happens when you run one query to get N objects. Then you run one more query for each object to get a related row. That gives N+1 queries.

# 1 query for books + 1 query per book for author
for book in Book.objects.all():
    print(book.author.name)

Fixes:

  • select_related("author") for ForeignKey or OneToOne (JOIN).
  • prefetch_related("tags") for many-valued relations.
  • .only() / .values() to fetch only the columns you need.
  • Count in SQL (annotate(n=Count("comments"))) instead of counting in a loop.

Find it with django-debug-toolbar, assertNumQueries in tests, or the django.db.backends logger. In DRF, the serializer is the usual cause: put the select_related/prefetch_related in the viewset's get_queryset.

What they are checking: Recognising the pattern and tools to detect it

ExperiencedMost askedScenario
Answer

An API list endpoint makes about 500 database queries and takes 4 seconds. How do you diagnose and fix it?

Measure first. Then remove the repeated queries.

  1. Count queries with django-debug-toolbar or django-silk locally, or enable the django.db.backends logger. Tests can pin the number with self.assertNumQueries(3).
  2. If the query count grows with the number of rows, it is N+1. Find the field that the serializer or template reads, which causes one query per object.
  3. Fix in get_queryset: select_related for FKs, prefetch_related (with Prefetch objects for filtered relations) for reverse and M2M, and annotations for counts and sums.
  4. Send less data: only()/defer(), paginate (PageNumberPagination or cursor pagination), avoid big nested objects.
  5. Look at slow SQL with EXPLAIN ANALYZE and add indexes (db_index=True, Meta.indexes) on filtered and ordered columns.
  6. If it is still slow, cache the result in Redis and measure again.

Goal: a small, fixed number of queries, no matter how many rows. Add a test to keep it that way.

What they are checking: Methodical diagnosis with ORM-level tooling

ExperiencedMost asked
Answer

How does authentication work in Django and DRF? Compare session, token and JWT authentication.

Django's own auth uses sessions. Login stores a session id in a cookie, and the server looks up the user on each request. DRF adds authentication classes you can swap in, and they set request.user.

SessionToken (DRF TokenAuthentication)JWT (e.g. SimpleJWT)
StateServer stores sessionServer stores token in DBStateless signed token
TransportCookie (needs CSRF)Authorization: Token ...Authorization: Bearer ...
RevocationDelete sessionDelete tokenHard, needs short expiry plus a blocklist
Best forBrowser apps on same domainSimple clientsMobile/SPA, microservices

JWT practice: use a short-lived access token (a few minutes) and a refresh token to renew it. Sign with a strong secret or key pair. Always use HTTPS. If XSS is a worry, keep tokens out of localStorage (HttpOnly cookies are safer). Authentication says who you are. Permissions decide what you may do.

What they are checking: Pros and cons of stateful and stateless auth

ExperiencedMost askedFree with sign-in
Answer

Explain dependency injection in FastAPI with an example.

FastAPI's Depends lets you write reusable pieces (database session, current user, settings, pagination) as functions. FastAPI calls them and passes the results into your endpoint.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between `def` and `async def` endpoints in FastAPI?

FastAPI supports both. async def endpoints run directly on the event loop. Plain def endpoints run in a pool of worker threads, so they do not block it.

ExperiencedMost askedFree with sign-in
Answer

How do you deploy a Django or FastAPI app to production with gunicorn and uvicorn?

Run the app server behind a reverse proxy (Nginx or a cloud load balancer). Manage it with systemd or containers.

  • Django (WSGI): gunicorn project.wsgi:application --workers 4 --bind 0.0.0.0:8000.
  • Django or FastAPI (ASGI): gunicorn as process manager with uvicorn workers:
ExperiencedMost askedScenarioFree with sign-in
Answer

A Django or FastAPI endpoint is slow only under load. How do you find the cause?

A slowdown that only appears with many users usually means requests are fighting for a limited resource.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you scale a Django or FastAPI application to handle 10 times more traffic?

Scale in steps. Start with the cheapest wins.

ExperiencedMost askedScenarioFree with sign-in
Answer

Two users try to book the last seat at the same moment and both succeed. How do you prevent double booking?

This is a race condition: the code reads first and writes later. Make the check and the update happen as one step in the database.

Option 1: lock the row.

ExperiencedMost askedScenarioFree with sign-in
Answer

The app works locally but returns 500 errors only in production. How do you debug it?

Start with facts, not guesses.

ExperiencedMost askedScenarioFree with sign-in
Answer

Which would you pick for a new project: Django with DRF or FastAPI? Walk through your decision.

Decide by needs, team and tools, not by hype.

Pick Django + DRF when:

  • You need an admin panel, auth, ORM and migrations ready to use.
  • The product is one big app built around a database, or has pages made on the server.
  • The team knows Django, and you want proven conventions and many ready packages.
ExperiencedMost askedFree with sign-in
Answer

What are Django signals? When should you avoid them?

Signals tell one part of the app when something happens in another part (the observer pattern). Common ones: pre_save, post_save, post_delete, m2m_changed, request_finished.

ExperiencedMost askedFree with sign-in
Answer

What are APIView, generic views and ViewSets in DRF? When do you use each?

Each one does more for you than the last.

ExperiencedMost askedFree with sign-in
Answer

How do you run background tasks? Compare FastAPI BackgroundTasks with Celery.

FastAPI's BackgroundTasks runs a function after the response is sent, in the same process.

ExperiencedMost askedScenarioFree with sign-in
Answer

A user signs up and the endpoint takes 6 seconds, because it sends an email and calls an outside API. How do you fix this?

Keep only the essential work in the request. Move the slow parts out of it.

ExperiencedMost askedFree with sign-in
Answer

How do database transactions work in Django? What does `atomic` do?

By default, Django uses autocommit mode, so each query is its own transaction. transaction.atomic groups operations so they all save or all roll back.

ExperiencedMost askedFree with sign-in
Answer

How do you use Celery with Django? What problems does it solve?

Celery is a task queue that runs on many machines. The web process puts a message on a broker (Redis or RabbitMQ). Separate worker processes run it. So long or unreliable work runs outside the request.

ExperiencedMost askedFree with sign-in
Answer

What caching options does Django provide and how do you use them?

Django has a cache framework with several backends: local memory, file, database, Memcached and Redis (the usual choice in production).

ExperiencedMost askedFree with sign-in
Answer

How do you handle pagination, filtering and throttling in DRF?

All three can be set in settings or per view.

ExperiencedMost askedFree with sign-in
Answer

How do you connect FastAPI to a database with SQLAlchemy and manage sessions?

Create the engine and session factory once. Give each request its own session through a dependency that closes it afterwards.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between WSGI and ASGI?

Both are rules for how a Python web server talks to a web application.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you add a column to a table with 50 million rows in production without downtime?

Avoid long locks. Make sure old code and new code both work during the rollout (add first, remove later).

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you secure a public REST API built with Django or FastAPI against abuse?

Use many layers of defence.

ExperiencedMost askedFree with sign-in
Answer

How do you test a Django app and a FastAPI app?

Use pytest with the framework's test client, a test database and fixtures.

Django:

ExperiencedMost askedFree with sign-in
Answer

Why should you create a custom user model at the start of a Django project?

Django's default User is hard to change later. Other tables point to it with foreign keys, and migrations depend on it. Setting AUTH_USER_MODEL before the first migration lets you add fields (phone, role) or log in with email.

ExperiencedMost askedFree with sign-in
Answer

What is a custom through table in a Django ManyToMany relationship, and when do you need one?

A custom through model is a join table you define yourself for a ManyToManyField. It lets you store extra data about the link, such as when a student joined a course.

NestJS

ExperiencedMost asked
Answer

What are custom providers (useClass, useValue, useFactory, useExisting) and when do you use each?

Custom providers let you control how a token is resolved.

FormUse for
useClassSwap an implementation per environment
useValueConstants, config objects, mocks in tests
useFactoryBuild dynamically, with inject of other providers, optionally async
useExistingCreate an alias to another provider
@Module({
  providers: [
    { provide: 'CACHE', useFactory: async (cfg: ConfigService) => {
        const client = createClient({ url: cfg.get('REDIS_URL') });
        await client.connect();
        return client;
      },
      inject: [ConfigService] },
    { provide: PaymentGateway, useClass: process.env.NODE_ENV === 'test' ? FakeGateway : StripeGateway },
  ],
})
export class AppModule {}

Async factories delay app start until they resolve, which is useful for connections.

What they are checking: Whether you can wire non-trivial dependencies cleanly

ExperiencedMost asked
Answer

What is a circular dependency in NestJS and how do you resolve it with forwardRef?

A circular dependency happens when two providers (or modules) need each other. Nest cannot decide which to create first. forwardRef() delays the reference, so both can be resolved later.

@Injectable()
export class AService {
  constructor(@Inject(forwardRef(() => BService)) private b: BService) {}
}
@Injectable()
export class BService {
  constructor(@Inject(forwardRef(() => AService)) private a: AService) {}
}
// modules need it too:
@Module({ imports: [forwardRef(() => BModule)] })
export class AModule {}

This is only a workaround. The better fix is to remove the cycle. Move the shared logic to a third service, use events (EventEmitter2) for one direction, or move the code to the right module. Also watch for circular file imports. They show up as undefined.

What they are checking: Whether you treat forwardRef as a last resort and know design fixes

ExperiencedMost asked
Answer

What is the order of the NestJS request lifecycle?

Incoming request flow is: middleware, guards, interceptors (before), pipes, controller handler, service, interceptors (after), exception filters (only on errors), then the response.

  1. Global, then module-bound middleware.
  2. Guards (global, controller, route).
  3. Interceptors, pre-controller part.
  4. Pipes (global, controller, route, param).
  5. Controller method and service.
  6. Interceptors, post-response part (reverse order).
  7. Exception filters catch anything thrown from the guard onward.

Within each type, global runs first, then controller-level, then route-level. Interceptors unwind in reverse on the way out. A guard that returns false stops the pipeline before pipes and the handler.

What they are checking: Whether you can place each building block in the pipeline

ExperiencedMost asked
Answer

How do guards work in NestJS and how would you implement role-based access control?

A guard implements CanActivate and returns a boolean (or promise or observable) that decides whether the request proceeds. For RBAC, combine a roles decorator that stores metadata with a guard that reads it using Reflector.

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(ctx: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride<string[]>('roles', [ctx.getHandler(), ctx.getClass()]);
    if (!required) return true;
    const { user } = ctx.switchToHttp().getRequest();
    return required.some(r => user?.roles?.includes(r));
  }
}

@Roles('admin')
@UseGuards(JwtAuthGuard, RolesGuard)
@Delete(':id')
remove(@Param('id') id: string) {}

Order matters: authentication first so request.user exists. Returning false gives 403.

What they are checking: Whether you can implement authorisation with metadata and guards

ExperiencedMost askedFree with sign-in
Answer

How do you run a database transaction in NestJS?

Run all related writes in one transaction so they either all commit or all roll back. With TypeORM use a DataSource and a query runner or the transaction helper; with Prisma use $transaction.

ExperiencedMost askedFree with sign-in
Answer

How do you implement JWT authentication with Passport in NestJS?

Use @nestjs/passport with passport-jwt. A login endpoint checks the credentials and issues a signed token with JwtService. A JwtStrategy plus AuthGuard('jwt') protects routes.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design an idempotent payment endpoint so a retry never charges the customer twice?

Require an Idempotency-Key header made by the client. Store the key with a fingerprint of the request and the result. Then a repeat gets the saved response and does not run again.

ExperiencedMost askedScenarioFree with sign-in
Answer

Design a reconciliation job that matches your payment records against a provider's settlement file.

Compare both sources by a stable key, classify the differences, and make the job re-runnable and auditable.

ExperiencedMost askedScenarioFree with sign-in
Answer

An endpoint that lists orders is slow under load. How do you diagnose and fix it?

Measure first, then fix the biggest cost, which is usually the database.

ExperiencedMost askedScenarioFree with sign-in
Answer

Two requests update the same account balance at the same time and the final balance is wrong. How do you prevent this?

This is a lost-update race. Prevent it by letting the database handle changes one at a time. Use an atomic update, a row lock, or optimistic versioning.

ExperiencedMost askedFree with sign-in
Answer

What are provider scopes in NestJS (DEFAULT, REQUEST, TRANSIENT)?

Scope sets how long a provider lives. DEFAULT is one instance for the whole app (a singleton). REQUEST makes a new instance for each incoming request. TRANSIENT makes a new instance for each class that injects it.

ExperiencedMost askedFree with sign-in
Answer

Prisma versus TypeORM in a NestJS project: how do you choose?

Pick Prisma for type-safe queries, a clear schema file and good migrations. Pick TypeORM when you prefer decorators, the Active Record or Data Mapper style, or need features such as complex entity inheritance.

ExperiencedMost askedFree with sign-in
Answer

How would you design refresh tokens and logout with JWT in NestJS?

Issue a short-lived access token (about 15 minutes) and a long-lived refresh token. Store the refresh token on the server as a hash, and replace it on each use.

ExperiencedMost askedFree with sign-in
Answer

What are the transport options for NestJS microservices, and how do you set one up?

Nest abstracts transports so the same patterns work over TCP, Redis, NATS, MQTT, RabbitMQ, Kafka and gRPC. You create a microservice app with NestFactory.createMicroservice and call it from a client built with ClientProxy.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you integrate multiple payment gateways behind one interface in NestJS?

Define one common interface and implement it for each gateway (adapter). Then pick the right one at run time (strategy) through DI.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you add rate limiting and brute-force protection to a login endpoint?

Apply a global throttler, with a stricter limit on login routes. Count by IP and by account. Slow attackers down more after repeated failures.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you run background jobs reliably in NestJS, such as sending emails with retries?

Use a queue (BullMQ with Redis through @nestjs/bullmq) so work is persisted, retried and processed outside the request.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you safely handle incoming webhooks, for example from a payment provider?

Verify authenticity, acknowledge fast, and process each event exactly once by its id.

ExperiencedMost askedFree with sign-in
Answer

What does the transform option of ValidationPipe do, and what is class-transformer used for?

With transform: true the pipe turns the plain payload into an instance of the DTO class, and changes simple values to the declared type. It uses class-transformer.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between @MessagePattern and @EventPattern?

@MessagePattern handles request-response messages, where the sender waits for a reply. @EventPattern handles fire-and-forget events, with no reply.

ExperiencedMost askedFree with sign-in
Answer

How do you write end-to-end tests for a NestJS API?

Create the full app (or a part of it) from AppModule in a testing module. Then call it over HTTP with supertest, without opening a real port.

ExperiencedMost askedFree with sign-in
Answer

What are dynamic modules in NestJS (forRoot, forRootAsync, forFeature)?

A dynamic module is a module whose providers are set up when it is imported. A static method that returns a DynamicModule does this. So one reusable module can be set up in a different way by each user.

ExperiencedMost askedFree with sign-in
Answer

What are the differences between using Express and Fastify as the HTTP adapter in NestJS?

Nest works with different platforms. Express is the default and has the most middleware. Fastify handles more requests per second and uses fewer resources, with a design built around schemas.

ExperiencedMost askedFree with sign-in
Answer

How do you create a custom parameter decorator, for example @CurrentUser()?

Use createParamDecorator to pull a value out of the ExecutionContext so controllers stay clean.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you add health checks and graceful shutdown to a NestJS service running in containers?

Add liveness and readiness endpoints with @nestjs/terminus. Enable shutdown hooks, so work in progress finishes before the process exits.

ExperiencedMost askedFree with sign-in
Answer

Which design patterns do you commonly use in NestJS applications, and where do they appear?

NestJS is built around several patterns, and I also apply others on top of it.

System Design

ExperiencedMost asked
Answer

What is database sharding and what are its challenges?

Sharding splits one dataset across many database servers (shards). Each shard holds some of the rows. So storage and traffic can grow by adding servers.

Strategies:

  • Range-based: by id or date range. Simple, but hot spots (latest range gets all writes).
  • Hash-based: hash(user_id) mod N. Even spread, but resharding moves much data; consistent hashing reduces that.
  • Directory-based: a lookup service maps keys to shards. Flexible, extra component.

Challenges:

  • Choosing a shard key with high cardinality and even distribution; a poor key causes hot shards.
  • Cross-shard joins and transactions become hard or impossible.
  • Resharding when adding nodes.
  • Extra work to run it: backups, schema changes, monitoring per shard.
  • Global unique ids need a generator (Snowflake style, UUIDs).

Before sharding, exhaust cheaper options: indexes, caching, read replicas, partitioning, archiving old data.

What they are checking: Shard key reasoning

ExperiencedMost askedScenario
Answer

How would you design a URL shortener like bit.ly?

Requirements: make a short link for a long URL, redirect fast, many more reads than writes (about 100 to 1), optional expiry, and click analytics.

Capacity example: 100 million new URLs per month, about 40 writes/s and 4,000 reads/s; 7 characters of base62 give 62^7, about 3.5 trillion codes.

API:

  • POST /urls with {long_url} returns {short_url}.
  • GET /{code} returns 301 or 302 to the long URL. Use 302 if you want every click tracked. Use 301 when browsers may cache it.

Key generation:

  • Counter or ID generator encoded in base62: unique, no collisions, but predictable.
  • Random 7 characters plus a uniqueness check (retry on collision).
  • Pre-generated key service handing out unused keys in batches to app servers.

Storage: a key-value table code -> long_url, created_at, expiry, user_id. NoSQL (DynamoDB, Cassandra) or sharded SQL by code works.

Scaling reads: cache popular codes in Redis (LRU), put a CDN or edge in front, and run stateless app servers behind a load balancer.

Extras: rate limits, checks for abuse and malware, click analytics done later through a queue, custom aliases, and removing expired links.

What they are checking: Structured approach: requirements, API, storage, scale

ExperiencedMost askedScenario
Answer

How would you design a chat application like WhatsApp?

Requirements: 1:1 and group chat, real-time delivery, message history, online status, read receipts, media sharing, and millions of users at the same time.

Core design:

  • Connection: clients keep a WebSocket connection to a chat gateway. Gateways are stateless apart from the connection, kept behind a load balancer.
  • Routing: a session service (Redis) maps user_id -> gateway. To send, the sender's gateway looks up the recipient's gateway and forwards the message.
  • Offline users: store the message and send a push notification (APNs/FCM); deliver on reconnect.
  • Persistence: save messages in a store split by conversation (Cassandra or DynamoDB). Key it by (conversation_id, message_id) with ids ordered by time, for ordering and paging.
  • Ordering and delivery: per-conversation sequence numbers; at-least-once delivery with client acks and deduplication by message id.
  • Groups: fan-out on write for small groups, via a queue (Kafka) for large ones.
  • Media: upload to object storage (S3) with pre-signed URLs, send only the link in the message, and serve it through a CDN.
  • Presence: heartbeats stored in Redis with TTL.
  • Security: TLS, optionally end-to-end encryption.

Scale by sharding on conversation or user id and adding gateway instances.

What they are checking: Real-time architecture and delivery guarantees

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design a rate limiter?

Goal: limit each client to N requests per time window, with low cost and counters shared across servers.

Where: at the API gateway or middleware, before expensive work.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design a notification system that sends email, SMS and push notifications?

Requirements: multiple channels, millions of notifications, user preferences, reliable delivery, no duplicates, rate limits per provider.

ExperiencedMost askedFree with sign-in
Answer

How do you design for failure in a distributed system? Explain circuit breakers, retries and timeouts.

Assume any network call can be slow or fail, and prevent one failure from cascading.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design a system that handles 10 times more traffic next month? Walk through your approach.

Work from measurement to action.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you handle one transaction across many microservices, such as an order that touches inventory, payment and shipping?

Avoid two-phase commit across services (slow, fragile). Use the Saga pattern: a sequence of local transactions where each step has a compensating action.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design a system to handle a sudden traffic spike, like a flash sale?

Protect the critical path and shed the rest.

ExperiencedMost askedFree with sign-in
Answer

How do you make a system highly available? What does 99.99 percent availability mean?

Availability is the share of time the system works. 99.9 percent allows about 8.8 hours of downtime a year; 99.99 percent allows about 52 minutes; 99.999 percent about 5 minutes.

ExperiencedMost askedFree with sign-in
Answer

What is consistent hashing and why is it used?

Consistent hashing maps both keys and servers onto a circular hash space (ring). A key belongs to the first server found clockwise from its hash.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design a news feed or timeline like Twitter or Instagram?

The key decision is fan-out on write versus fan-out on read.

ExperiencedMost askedFree with sign-in
Answer

How do you generate unique IDs in a distributed system?

Options and pros and cons:

ExperiencedMost askedFree with sign-in
Answer

How do you monitor a production system? What do logs, metrics and traces each provide?

The three pillars of observability answer different questions.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design the backend for an e-commerce site covering catalog, cart, checkout and orders?

Split by capability, keep the checkout path correct and the browsing path fast.

ExperiencedMost askedFree with sign-in
Answer

What are read replicas, when do you use them, and what problems can they cause?

A read replica is a copy of the primary database. It gets changes through replication and answers read-only queries. You use it to handle many reads, move reports and analytics off the primary, and improve availability or speed in other regions.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design a parking lot system or any object-oriented low-level design problem? What is your approach?

Low-level design questions test modelling, not scale. Follow a repeatable path.

ExperiencedMost askedScenarioFree with sign-in
Answer

How do you design a search feature, such as search on an e-commerce site?

Do not run LIKE '%term%' over a large table. Use a search index.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design a file storage and sharing service like Google Drive or Dropbox?

Requirements: upload, download, sync across devices, sharing with permissions, large files, versioning.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a join and copied (denormalised) data in a distributed system? Why do we avoid joins across services?

Inside one database a join is cheap and consistent. Across services or shards a join means network calls, partial failures and no shared transaction.

ExperiencedMost askedFree with sign-in
Answer

How would you choose between REST, message queues and gRPC for communication between services?

Match the mechanism to the interaction.

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design a distributed cache like Redis for a large-scale system?

Goals: sub-millisecond reads, high availability, horizontal scale, bounded memory.

ExperiencedMost askedFree with sign-in
Answer

What is the difference between a primary-replica setup and a multi-primary setup for a database?

Primary-replica (single leader): all writes go to one primary, which streams changes to replicas that serve reads. Simple and consistent for writes. Limits: write throughput is capped by one node, and failover needs promotion (brief downtime or lag).

ExperiencedMost askedScenarioFree with sign-in
Answer

How would you design data isolation for a multi-tenant SaaS application?

There are three common models, and the choice depends on isolation needs, number of tenants and cost.

ExperiencedMost askedScenarioFree with sign-in
Answer

Several services need user login. How would you design centralised authentication and authorisation across them?

Put authentication in one identity service (or a managed provider such as Keycloak, Auth0 or Cognito). Every other service trusts the tokens it issues. Services do not keep their own passwords.

ExperiencedMost askedFree with sign-in
Answer

How do you handle failures when consuming messages from Kafka?

For each failure, decide if it is temporary or permanent. Make sure no failure blocks the partition forever or loses a message silently.