Scenario Based

Software Engineer | 170 questions | 2026

Scenario based Software Engineer interview questions

"What would you do if..." questions, by topic. Tap a question to see how a strong candidate answers.

Python

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 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 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 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.

JavaScript

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 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 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 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.

FresherMost askedScenarioFree with sign-in
Answer

How do you find duplicate records in a table?

Group by the columns that define a duplicate and keep groups with more than one row.

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.

FresherMost askedScenarioFree with sign-in
Answer

Write a query to find customers who have never placed an order.

Use an anti join: LEFT JOIN and keep rows with no match, or NOT EXISTS.

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 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.

FresherMost askedScenarioFree with sign-in
Answer

How do you design tables for a many-to-many relationship, such as students and courses?

Use a junction (bridge) table. It holds the foreign keys of both sides, plus any attributes of the relationship itself.

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 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 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.

Java

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 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.

FresherMost askedScenarioFree with sign-in
Answer

You get a ConcurrentModificationException while iterating a list. Why does it happen and how do you fix it?

It happens when a collection is structurally modified during iteration by anything other than the iterator itself. The fail-fast iterator compares a modCount and throws.

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 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 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 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.

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

FresherMost askedScenarioFree with sign-in
Answer

You get the error "Property 'x' does not exist on type 'A | B'". What causes it and how do you fix it?

When a value has a union type, you can only access properties that exist on every member. TypeScript does not know yet which member you have. So using a property that exists on only one of them is an error.

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 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 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.

Next.js

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 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 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 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 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.

Angular

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 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 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 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.

Node.js

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 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 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.

C# and .NET

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 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 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 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.

OOP

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 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 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 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 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 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 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 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 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 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 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 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.

Django and FastAPI

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 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 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 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.

NestJS

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.

FresherMost askedScenarioFree with sign-in
Answer

Two services are circularly dependent in your NestJS codebase and the app fails to boot. How do you refactor it properly?

Find why each one needs the other. Then break the cycle by moving shared logic or reversing one direction, instead of leaving forwardRef everywhere.

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 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.

System Design

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 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 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 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 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 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 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.